From 055c282a0364362d849e4ed8249b3bd701f21362 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 24 Oct 2024 02:12:52 +0000 Subject: [PATCH 1/3] chore: Configure Ruby clients for google-ads-ad_manager PiperOrigin-RevId: 689139590 Source-Link: https://github.com/googleapis/googleapis/commit/296f2ac1aa9abccb7708b639b7839faa1809087f Source-Link: https://github.com/googleapis/googleapis-gen/commit/26927362e0aa1293258fc23fe3ce83c5c21d5fbb Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLXdlYnNlY3VyaXR5c2Nhbm5lci8uT3dsQm90LnlhbWwiLCJoIjoiMjY5MjczNjJlMGFhMTI5MzI1OGZjMjNmZTNjZTgzYzVjMjFkNWZiYiJ9 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLXdvcmtmbG93cy8uT3dsQm90LnlhbWwiLCJoIjoiMjY5MjczNjJlMGFhMTI5MzI1OGZjMjNmZTNjZTgzYzVjMjFkNWZiYiJ9 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLXdvcmtzdGF0aW9ucy8uT3dsQm90LnlhbWwiLCJoIjoiMjY5MjczNjJlMGFhMTI5MzI1OGZjMjNmZTNjZTgzYzVjMjFkNWZiYiJ9 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWdlby10eXBlLy5Pd2xCb3QueWFtbCIsImgiOiIyNjkyNzM2MmUwYWExMjkzMjU4ZmMyM2ZlM2NlODNjNWMyMWQ1ZmJiIn0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtYWRkcmVzc3ZhbGlkYXRpb24vLk93bEJvdC55YW1sIiwiaCI6IjI2OTI3MzYyZTBhYTEyOTMyNThmYzIzZmUzY2U4M2M1YzIxZDVmYmIifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtYXJlYWluc2lnaHRzLy5Pd2xCb3QueWFtbCIsImgiOiIyNjkyNzM2MmUwYWExMjkzMjU4ZmMyM2ZlM2NlODNjNWMyMWQ1ZmJiIn0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtZmxlZXRlbmdpbmUtZGVsaXZlcnkvLk93bEJvdC55YW1sIiwiaCI6IjI2OTI3MzYyZTBhYTEyOTMyNThmYzIzZmUzY2U4M2M1YzIxZDVmYmIifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtZmxlZXRlbmdpbmUvLk93bEJvdC55YW1sIiwiaCI6IjI2OTI3MzYyZTBhYTEyOTMyNThmYzIzZmUzY2U4M2M1YzIxZDVmYmIifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtbWFwc3BsYXRmb3JtZGF0YXNldHMvLk93bEJvdC55YW1sIiwiaCI6IjI2OTI3MzYyZTBhYTEyOTMyNThmYzIzZmUzY2U4M2M1YzIxZDVmYmIifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcGxhY2VzLy5Pd2xCb3QueWFtbCIsImgiOiIyNjkyNzM2MmUwYWExMjkzMjU4ZmMyM2ZlM2NlODNjNWMyMWQ1ZmJiIn0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGVvcHRpbWl6YXRpb24vLk93bEJvdC55YW1sIiwiaCI6IjI2OTI3MzYyZTBhYTEyOTMyNThmYzIzZmUzY2U4M2M1YzIxZDVmYmIifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGluZy8uT3dsQm90LnlhbWwiLCJoIjoiMjY5MjczNjJlMGFhMTI5MzI1OGZjMjNmZTNjZTgzYzVjMjFkNWZiYiJ9 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtc29sYXIvLk93bEJvdC55YW1sIiwiaCI6IjI2OTI3MzYyZTBhYTEyOTMyNThmYzIzZmUzY2U4M2M1YzIxZDVmYmIifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWFjY291bnRzLy5Pd2xCb3QueWFtbCIsImgiOiIyNjkyNzM2MmUwYWExMjkzMjU4ZmMyM2ZlM2NlODNjNWMyMWQ1ZmJiIn0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWNvbnZlcnNpb25zLy5Pd2xCb3QueWFtbCIsImgiOiIyNjkyNzM2MmUwYWExMjkzMjU4ZmMyM2ZlM2NlODNjNWMyMWQ1ZmJiIn0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWRhdGFzb3VyY2VzLy5Pd2xCb3QueWFtbCIsImgiOiIyNjkyNzM2MmUwYWExMjkzMjU4ZmMyM2ZlM2NlODNjNWMyMWQ1ZmJiIn0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWludmVudG9yaWVzLy5Pd2xCb3QueWFtbCIsImgiOiIyNjkyNzM2MmUwYWExMjkzMjU4ZmMyM2ZlM2NlODNjNWMyMWQ1ZmJiIn0= Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWxmcC8uT3dsQm90LnlhbWwiLCJoIjoiMjY5MjczNjJlMGFhMTI5MzI1OGZjMjNmZTNjZTgzYzVjMjFkNWZiYiJ9 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LW5vdGlmaWNhdGlvbnMvLk93bEJvdC55YW1sIiwiaCI6IjI2OTI3MzYyZTBhYTEyOTMyNThmYzIzZmUzY2U4M2M1YzIxZDVmYmIifQ== Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LXByb2R1Y3RzLy5Pd2xCb3QueWFtbCIsImgiOiIyNjkyNzM2MmUwYWExMjkzMjU4ZmMyM2ZlM2NlODNjNWMyMWQ1ZmJiIn0= --- .../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 + .../docs/websecurityscanner_v1/services_.rst | 6 + .../v1/docs/websecurityscanner_v1/types_.rst | 6 + .../web_security_scanner.rst | 10 + .../cloud/websecurityscanner/__init__.py | 95 + .../cloud/websecurityscanner/gapic_version.py | 16 + .../google/cloud/websecurityscanner/py.typed | 2 + .../cloud/websecurityscanner_v1/__init__.py | 96 + .../websecurityscanner_v1/gapic_metadata.json | 223 + .../websecurityscanner_v1/gapic_version.py | 16 + .../cloud/websecurityscanner_v1/py.typed | 2 + .../services/__init__.py | 15 + .../services/web_security_scanner/__init__.py | 22 + .../web_security_scanner/async_client.py | 1353 ++ .../services/web_security_scanner/client.py | 1710 ++ .../services/web_security_scanner/pagers.py | 571 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../web_security_scanner/transports/base.py | 416 + .../web_security_scanner/transports/grpc.py | 592 + .../transports/grpc_asyncio.py | 763 + .../web_security_scanner/transports/rest.py | 1532 ++ .../transports/rest_base.py | 512 + .../websecurityscanner_v1/types/__init__.py | 108 + .../types/crawled_url.py | 62 + .../websecurityscanner_v1/types/finding.py | 209 + .../types/finding_addon.py | 303 + .../types/finding_type_stats.py | 54 + .../types/scan_config.py | 361 + .../types/scan_config_error.py | 241 + .../websecurityscanner_v1/types/scan_run.py | 181 + .../types/scan_run_error_trace.py | 107 + .../types/scan_run_log.py | 98 + .../types/scan_run_warning_trace.py | 82 + .../types/web_security_scanner.py | 484 + .../v1/mypy.ini | 3 + .../v1/noxfile.py | 280 + ...ta_google.cloud.websecurityscanner.v1.json | 1998 ++ ...curity_scanner_create_scan_config_async.py | 51 + ...ecurity_scanner_create_scan_config_sync.py | 51 + ...curity_scanner_delete_scan_config_async.py | 49 + ...ecurity_scanner_delete_scan_config_sync.py | 49 + ..._web_security_scanner_get_finding_async.py | 51 + ...d_web_security_scanner_get_finding_sync.py | 51 + ..._security_scanner_get_scan_config_async.py | 51 + ...b_security_scanner_get_scan_config_sync.py | 51 + ...web_security_scanner_get_scan_run_async.py | 51 + ..._web_security_scanner_get_scan_run_sync.py | 51 + ...ecurity_scanner_list_crawled_urls_async.py | 52 + ...security_scanner_list_crawled_urls_sync.py | 52 + ...y_scanner_list_finding_type_stats_async.py | 51 + ...ty_scanner_list_finding_type_stats_sync.py | 51 + ...eb_security_scanner_list_findings_async.py | 52 + ...web_security_scanner_list_findings_sync.py | 52 + ...ecurity_scanner_list_scan_configs_async.py | 52 + ...security_scanner_list_scan_configs_sync.py | 52 + ...b_security_scanner_list_scan_runs_async.py | 52 + ...eb_security_scanner_list_scan_runs_sync.py | 52 + ...b_security_scanner_start_scan_run_async.py | 51 + ...eb_security_scanner_start_scan_run_sync.py | 51 + ...eb_security_scanner_stop_scan_run_async.py | 51 + ...web_security_scanner_stop_scan_run_sync.py | 51 + ...curity_scanner_update_scan_config_async.py | 51 + ...ecurity_scanner_update_scan_config_sync.py | 51 + .../fixup_websecurityscanner_v1_keywords.py | 188 + .../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/websecurityscanner_v1/__init__.py | 16 + .../test_web_security_scanner.py | 8720 ++++++++ .../v1alpha/.coveragerc | 13 + .../v1alpha/.flake8 | 33 + .../v1alpha/MANIFEST.in | 2 + .../v1alpha/README.rst | 49 + .../v1alpha/docs/_static/custom.css | 3 + .../v1alpha/docs/conf.py | 376 + .../v1alpha/docs/index.rst | 7 + .../websecurityscanner_v1alpha/services_.rst | 6 + .../websecurityscanner_v1alpha/types_.rst | 6 + .../web_security_scanner.rst | 10 + .../cloud/websecurityscanner/__init__.py | 83 + .../cloud/websecurityscanner/gapic_version.py | 16 + .../google/cloud/websecurityscanner/py.typed | 2 + .../websecurityscanner_v1alpha/__init__.py | 84 + .../gapic_metadata.json | 223 + .../gapic_version.py | 16 + .../cloud/websecurityscanner_v1alpha/py.typed | 2 + .../services/__init__.py | 15 + .../services/web_security_scanner/__init__.py | 22 + .../web_security_scanner/async_client.py | 1698 ++ .../services/web_security_scanner/client.py | 2060 ++ .../services/web_security_scanner/pagers.py | 571 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../web_security_scanner/transports/base.py | 417 + .../web_security_scanner/transports/grpc.py | 593 + .../transports/grpc_asyncio.py | 764 + .../web_security_scanner/transports/rest.py | 1533 ++ .../transports/rest_base.py | 617 + .../types/__init__.py | 88 + .../types/crawled_url.py | 62 + .../types/finding.py | 241 + .../types/finding_addon.py | 160 + .../types/finding_type_stats.py | 56 + .../types/scan_config.py | 268 + .../types/scan_run.py | 159 + .../types/web_security_scanner.py | 485 + .../v1alpha/mypy.ini | 3 + .../v1alpha/noxfile.py | 280 + ...ogle.cloud.websecurityscanner.v1alpha.json | 2126 ++ ...curity_scanner_create_scan_config_async.py | 57 + ...ecurity_scanner_create_scan_config_sync.py | 57 + ...curity_scanner_delete_scan_config_async.py | 50 + ...ecurity_scanner_delete_scan_config_sync.py | 50 + ..._web_security_scanner_get_finding_async.py | 52 + ...d_web_security_scanner_get_finding_sync.py | 52 + ..._security_scanner_get_scan_config_async.py | 52 + ...b_security_scanner_get_scan_config_sync.py | 52 + ...web_security_scanner_get_scan_run_async.py | 52 + ..._web_security_scanner_get_scan_run_sync.py | 52 + ...ecurity_scanner_list_crawled_urls_async.py | 53 + ...security_scanner_list_crawled_urls_sync.py | 53 + ...y_scanner_list_finding_type_stats_async.py | 52 + ...ty_scanner_list_finding_type_stats_sync.py | 52 + ...eb_security_scanner_list_findings_async.py | 54 + ...web_security_scanner_list_findings_sync.py | 54 + ...ecurity_scanner_list_scan_configs_async.py | 53 + ...security_scanner_list_scan_configs_sync.py | 53 + ...b_security_scanner_list_scan_runs_async.py | 53 + ...eb_security_scanner_list_scan_runs_sync.py | 53 + ...b_security_scanner_start_scan_run_async.py | 52 + ...eb_security_scanner_start_scan_run_sync.py | 52 + ...eb_security_scanner_stop_scan_run_async.py | 52 + ...web_security_scanner_stop_scan_run_sync.py | 52 + ...curity_scanner_update_scan_config_async.py | 56 + ...ecurity_scanner_update_scan_config_sync.py | 56 + ...xup_websecurityscanner_v1alpha_keywords.py | 188 + .../v1alpha/setup.py | 98 + .../v1alpha/testing/constraints-3.10.txt | 6 + .../v1alpha/testing/constraints-3.11.txt | 6 + .../v1alpha/testing/constraints-3.12.txt | 6 + .../v1alpha/testing/constraints-3.13.txt | 6 + .../v1alpha/testing/constraints-3.7.txt | 10 + .../v1alpha/testing/constraints-3.8.txt | 6 + .../v1alpha/testing/constraints-3.9.txt | 6 + .../v1alpha/tests/__init__.py | 16 + .../v1alpha/tests/unit/__init__.py | 16 + .../v1alpha/tests/unit/gapic/__init__.py | 16 + .../websecurityscanner_v1alpha/__init__.py | 16 + .../test_web_security_scanner.py | 11488 ++++++++++ .../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 + .../websecurityscanner_v1beta/services_.rst | 6 + .../docs/websecurityscanner_v1beta/types_.rst | 6 + .../web_security_scanner.rst | 10 + .../cloud/websecurityscanner/__init__.py | 91 + .../cloud/websecurityscanner/gapic_version.py | 16 + .../google/cloud/websecurityscanner/py.typed | 2 + .../websecurityscanner_v1beta/__init__.py | 92 + .../gapic_metadata.json | 223 + .../gapic_version.py | 16 + .../cloud/websecurityscanner_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../services/web_security_scanner/__init__.py | 22 + .../web_security_scanner/async_client.py | 1700 ++ .../services/web_security_scanner/client.py | 2062 ++ .../services/web_security_scanner/pagers.py | 571 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../web_security_scanner/transports/base.py | 417 + .../web_security_scanner/transports/grpc.py | 593 + .../transports/grpc_asyncio.py | 764 + .../web_security_scanner/transports/rest.py | 1533 ++ .../transports/rest_base.py | 617 + .../types/__init__.py | 102 + .../types/crawled_url.py | 62 + .../types/finding.py | 169 + .../types/finding_addon.py | 183 + .../types/finding_type_stats.py | 53 + .../types/scan_config.py | 319 + .../types/scan_config_error.py | 241 + .../types/scan_run.py | 178 + .../types/scan_run_error_trace.py | 106 + .../types/scan_run_warning_trace.py | 79 + .../types/web_security_scanner.py | 485 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ...oogle.cloud.websecurityscanner.v1beta.json | 2126 ++ ...curity_scanner_create_scan_config_async.py | 57 + ...ecurity_scanner_create_scan_config_sync.py | 57 + ...curity_scanner_delete_scan_config_async.py | 50 + ...ecurity_scanner_delete_scan_config_sync.py | 50 + ..._web_security_scanner_get_finding_async.py | 52 + ...d_web_security_scanner_get_finding_sync.py | 52 + ..._security_scanner_get_scan_config_async.py | 52 + ...b_security_scanner_get_scan_config_sync.py | 52 + ...web_security_scanner_get_scan_run_async.py | 52 + ..._web_security_scanner_get_scan_run_sync.py | 52 + ...ecurity_scanner_list_crawled_urls_async.py | 53 + ...security_scanner_list_crawled_urls_sync.py | 53 + ...y_scanner_list_finding_type_stats_async.py | 52 + ...ty_scanner_list_finding_type_stats_sync.py | 52 + ...eb_security_scanner_list_findings_async.py | 54 + ...web_security_scanner_list_findings_sync.py | 54 + ...ecurity_scanner_list_scan_configs_async.py | 53 + ...security_scanner_list_scan_configs_sync.py | 53 + ...b_security_scanner_list_scan_runs_async.py | 53 + ...eb_security_scanner_list_scan_runs_sync.py | 53 + ...b_security_scanner_start_scan_run_async.py | 52 + ...eb_security_scanner_start_scan_run_sync.py | 52 + ...eb_security_scanner_stop_scan_run_async.py | 52 + ...web_security_scanner_stop_scan_run_sync.py | 52 + ...curity_scanner_update_scan_config_async.py | 56 + ...ecurity_scanner_update_scan_config_sync.py | 56 + ...ixup_websecurityscanner_v1beta_keywords.py | 188 + .../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 + .../websecurityscanner_v1beta/__init__.py | 16 + .../test_web_security_scanner.py | 11533 ++++++++++ .../google-cloud-workflows/v1/.coveragerc | 13 + .../google-cloud-workflows/v1/.flake8 | 33 + .../google-cloud-workflows/v1/MANIFEST.in | 2 + .../google-cloud-workflows/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../google-cloud-workflows/v1/docs/conf.py | 376 + .../v1/docs/executions_v1/executions.rst | 10 + .../v1/docs/executions_v1/services_.rst | 6 + .../v1/docs/executions_v1/types_.rst | 6 + .../google-cloud-workflows/v1/docs/index.rst | 7 + .../v1/docs/workflows_v1/services_.rst | 6 + .../v1/docs/workflows_v1/types_.rst | 6 + .../v1/docs/workflows_v1/workflows.rst | 10 + .../v1/google/cloud/workflows/__init__.py | 43 + .../cloud/workflows/executions/__init__.py | 41 + .../workflows/executions/gapic_version.py | 16 + .../cloud/workflows/executions/py.typed | 2 + .../cloud/workflows/executions_v1/__init__.py | 42 + .../executions_v1/gapic_metadata.json | 63 + .../workflows/executions_v1/gapic_version.py | 16 + .../cloud/workflows/executions_v1/py.typed | 2 + .../executions_v1/services/__init__.py | 15 + .../services/executions/__init__.py | 22 + .../services/executions/async_client.py | 697 + .../services/executions/client.py | 1057 + .../services/executions/pagers.py | 162 + .../services/executions/transports/README.rst | 9 + .../executions/transports/__init__.py | 33 + .../services/executions/transports/base.py | 196 + .../services/executions/transports/grpc.py | 354 + .../executions/transports/grpc_asyncio.py | 390 + .../workflows/executions_v1/types/__init__.py | 34 + .../executions_v1/types/executions.py | 580 + .../google/cloud/workflows/gapic_version.py | 16 + .../v1/google/cloud/workflows/py.typed | 2 + .../v1/google/cloud/workflows_v1/__init__.py | 44 + .../cloud/workflows_v1/gapic_metadata.json | 103 + .../cloud/workflows_v1/gapic_version.py | 16 + .../v1/google/cloud/workflows_v1/py.typed | 2 + .../cloud/workflows_v1/services/__init__.py | 15 + .../services/workflows/__init__.py | 22 + .../services/workflows/async_client.py | 1149 + .../workflows_v1/services/workflows/client.py | 1505 ++ .../workflows_v1/services/workflows/pagers.py | 162 + .../services/workflows/transports/README.rst | 9 + .../services/workflows/transports/__init__.py | 38 + .../services/workflows/transports/base.py | 286 + .../services/workflows/transports/grpc.py | 497 + .../workflows/transports/grpc_asyncio.py | 563 + .../services/workflows/transports/rest.py | 1224 ++ .../workflows/transports/rest_base.py | 423 + .../cloud/workflows_v1/types/__init__.py | 36 + .../cloud/workflows_v1/types/workflows.py | 521 + .../google-cloud-workflows/v1/mypy.ini | 3 + .../google-cloud-workflows/v1/noxfile.py | 280 + ..._google.cloud.workflows.executions.v1.json | 667 + ...et_metadata_google.cloud.workflows.v1.json | 844 + ...rated_executions_cancel_execution_async.py | 52 + ...erated_executions_cancel_execution_sync.py | 52 + ...rated_executions_create_execution_async.py | 52 + ...erated_executions_create_execution_sync.py | 52 + ...enerated_executions_get_execution_async.py | 52 + ...generated_executions_get_execution_sync.py | 52 + ...erated_executions_list_executions_async.py | 53 + ...nerated_executions_list_executions_sync.py | 53 + ...nerated_workflows_create_workflow_async.py | 61 + ...enerated_workflows_create_workflow_sync.py | 61 + ...nerated_workflows_delete_workflow_async.py | 56 + ...enerated_workflows_delete_workflow_sync.py | 56 + ..._generated_workflows_get_workflow_async.py | 52 + ...1_generated_workflows_get_workflow_sync.py | 52 + ...enerated_workflows_list_workflows_async.py | 53 + ...generated_workflows_list_workflows_sync.py | 53 + ...nerated_workflows_update_workflow_async.py | 59 + ...enerated_workflows_update_workflow_sync.py | 59 + .../scripts/fixup_executions_v1_keywords.py | 179 + .../v1/scripts/fixup_workflows_v1_keywords.py | 180 + .../google-cloud-workflows/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 + .../unit/gapic/executions_v1/__init__.py | 16 + .../gapic/executions_v1/test_executions.py | 3165 +++ .../tests/unit/gapic/workflows_v1/__init__.py | 16 + .../unit/gapic/workflows_v1/test_workflows.py | 6232 ++++++ .../google-cloud-workflows/v1beta/.coveragerc | 13 + .../google-cloud-workflows/v1beta/.flake8 | 33 + .../google-cloud-workflows/v1beta/MANIFEST.in | 2 + .../google-cloud-workflows/v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../docs/executions_v1beta/executions.rst | 10 + .../docs/executions_v1beta/services_.rst | 6 + .../v1beta/docs/executions_v1beta/types_.rst | 6 + .../v1beta/docs/index.rst | 7 + .../docs/workflows_v1beta/services_.rst | 6 + .../v1beta/docs/workflows_v1beta/types_.rst | 6 + .../docs/workflows_v1beta/workflows.rst | 10 + .../v1beta/google/cloud/workflows/__init__.py | 43 + .../cloud/workflows/executions/__init__.py | 41 + .../workflows/executions/gapic_version.py | 16 + .../cloud/workflows/executions/py.typed | 2 + .../workflows/executions_v1beta/__init__.py | 42 + .../executions_v1beta/gapic_metadata.json | 63 + .../executions_v1beta/gapic_version.py | 16 + .../workflows/executions_v1beta/py.typed | 2 + .../executions_v1beta/services/__init__.py | 15 + .../services/executions/__init__.py | 22 + .../services/executions/async_client.py | 699 + .../services/executions/client.py | 1059 + .../services/executions/pagers.py | 162 + .../services/executions/transports/README.rst | 9 + .../executions/transports/__init__.py | 33 + .../services/executions/transports/base.py | 196 + .../services/executions/transports/grpc.py | 355 + .../executions/transports/grpc_asyncio.py | 391 + .../executions_v1beta/types/__init__.py | 34 + .../executions_v1beta/types/executions.py | 324 + .../google/cloud/workflows/gapic_version.py | 16 + .../v1beta/google/cloud/workflows/py.typed | 2 + .../google/cloud/workflows_v1beta/__init__.py | 44 + .../workflows_v1beta/gapic_metadata.json | 103 + .../cloud/workflows_v1beta/gapic_version.py | 16 + .../google/cloud/workflows_v1beta/py.typed | 2 + .../workflows_v1beta/services/__init__.py | 15 + .../services/workflows/__init__.py | 22 + .../services/workflows/async_client.py | 894 + .../services/workflows/client.py | 1246 ++ .../services/workflows/pagers.py | 162 + .../services/workflows/transports/README.rst | 9 + .../services/workflows/transports/__init__.py | 38 + .../services/workflows/transports/base.py | 217 + .../services/workflows/transports/grpc.py | 406 + .../workflows/transports/grpc_asyncio.py | 447 + .../services/workflows/transports/rest.py | 760 + .../workflows/transports/rest_base.py | 297 + .../cloud/workflows_v1beta/types/__init__.py | 36 + .../cloud/workflows_v1beta/types/workflows.py | 403 + .../google-cloud-workflows/v1beta/mypy.ini | 3 + .../google-cloud-workflows/v1beta/noxfile.py | 280 + ...gle.cloud.workflows.executions.v1beta.json | 667 + ...etadata_google.cloud.workflows.v1beta.json | 844 + ...rated_executions_cancel_execution_async.py | 52 + ...erated_executions_cancel_execution_sync.py | 52 + ...rated_executions_create_execution_async.py | 52 + ...erated_executions_create_execution_sync.py | 52 + ...enerated_executions_get_execution_async.py | 52 + ...generated_executions_get_execution_sync.py | 52 + ...erated_executions_list_executions_async.py | 53 + ...nerated_executions_list_executions_sync.py | 53 + ...nerated_workflows_create_workflow_async.py | 61 + ...enerated_workflows_create_workflow_sync.py | 61 + ...nerated_workflows_delete_workflow_async.py | 56 + ...enerated_workflows_delete_workflow_sync.py | 56 + ..._generated_workflows_get_workflow_async.py | 52 + ...a_generated_workflows_get_workflow_sync.py | 52 + ...enerated_workflows_list_workflows_async.py | 53 + ...generated_workflows_list_workflows_sync.py | 53 + ...nerated_workflows_update_workflow_async.py | 59 + ...enerated_workflows_update_workflow_sync.py | 59 + .../fixup_executions_v1beta_keywords.py | 179 + .../fixup_workflows_v1beta_keywords.py | 180 + .../google-cloud-workflows/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 + .../unit/gapic/executions_v1beta/__init__.py | 16 + .../executions_v1beta/test_executions.py | 3145 +++ .../unit/gapic/workflows_v1beta/__init__.py | 16 + .../gapic/workflows_v1beta/test_workflows.py | 5286 +++++ .../google-cloud-workstations/v1/.coveragerc | 13 + .../google-cloud-workstations/v1/.flake8 | 33 + .../google-cloud-workstations/v1/MANIFEST.in | 2 + .../google-cloud-workstations/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../google-cloud-workstations/v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../v1/docs/workstations_v1/services_.rst | 6 + .../v1/docs/workstations_v1/types_.rst | 6 + .../v1/docs/workstations_v1/workstations.rst | 10 + .../v1/google/cloud/workstations/__init__.py | 87 + .../cloud/workstations/gapic_version.py | 16 + .../v1/google/cloud/workstations/py.typed | 2 + .../google/cloud/workstations_v1/__init__.py | 88 + .../cloud/workstations_v1/gapic_metadata.json | 328 + .../cloud/workstations_v1/gapic_version.py | 16 + .../v1/google/cloud/workstations_v1/py.typed | 2 + .../workstations_v1/services/__init__.py | 15 + .../services/workstations/__init__.py | 22 + .../services/workstations/async_client.py | 3183 +++ .../services/workstations/client.py | 3536 +++ .../services/workstations/pagers.py | 702 + .../workstations/transports/README.rst | 9 + .../workstations/transports/__init__.py | 38 + .../services/workstations/transports/base.py | 612 + .../services/workstations/transports/grpc.py | 948 + .../workstations/transports/grpc_asyncio.py | 1180 + .../services/workstations/transports/rest.py | 3048 +++ .../workstations/transports/rest_base.py | 1129 + .../cloud/workstations_v1/types/__init__.py | 80 + .../workstations_v1/types/workstations.py | 1953 ++ .../google-cloud-workstations/v1/mypy.ini | 3 + .../google-cloud-workstations/v1/noxfile.py | 280 + ...metadata_google.cloud.workstations.v1.json | 3307 +++ ...d_workstations_create_workstation_async.py | 57 + ...ations_create_workstation_cluster_async.py | 57 + ...tations_create_workstation_cluster_sync.py | 57 + ...tations_create_workstation_config_async.py | 57 + ...stations_create_workstation_config_sync.py | 57 + ...ed_workstations_create_workstation_sync.py | 57 + ...d_workstations_delete_workstation_async.py | 56 + ...ations_delete_workstation_cluster_async.py | 56 + ...tations_delete_workstation_cluster_sync.py | 56 + ...tations_delete_workstation_config_async.py | 56 + ...stations_delete_workstation_config_sync.py | 56 + ...ed_workstations_delete_workstation_sync.py | 56 + ...orkstations_generate_access_token_async.py | 52 + ...workstations_generate_access_token_sync.py | 52 + ...ated_workstations_get_workstation_async.py | 52 + ...kstations_get_workstation_cluster_async.py | 52 + ...rkstations_get_workstation_cluster_sync.py | 52 + ...rkstations_get_workstation_config_async.py | 52 + ...orkstations_get_workstation_config_sync.py | 52 + ...rated_workstations_get_workstation_sync.py | 52 + ...s_list_usable_workstation_configs_async.py | 53 + ...ns_list_usable_workstation_configs_sync.py | 53 + ...stations_list_usable_workstations_async.py | 53 + ...kstations_list_usable_workstations_sync.py | 53 + ...tations_list_workstation_clusters_async.py | 53 + ...stations_list_workstation_clusters_sync.py | 53 + ...stations_list_workstation_configs_async.py | 53 + ...kstations_list_workstation_configs_sync.py | 53 + ...ed_workstations_list_workstations_async.py | 53 + ...ted_workstations_list_workstations_sync.py | 53 + ...ed_workstations_start_workstation_async.py | 56 + ...ted_workstations_start_workstation_sync.py | 56 + ...ted_workstations_stop_workstation_async.py | 56 + ...ated_workstations_stop_workstation_sync.py | 56 + ...d_workstations_update_workstation_async.py | 55 + ...ations_update_workstation_cluster_async.py | 55 + ...tations_update_workstation_cluster_sync.py | 55 + ...tations_update_workstation_config_async.py | 55 + ...stations_update_workstation_config_sync.py | 55 + ...ed_workstations_update_workstation_sync.py | 55 + .../scripts/fixup_workstations_v1_keywords.py | 195 + .../google-cloud-workstations/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 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/workstations_v1/__init__.py | 16 + .../workstations_v1/test_workstations.py | 17992 +++++++++++++++ .../v1beta/.coveragerc | 13 + .../google-cloud-workstations/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 + .../docs/workstations_v1beta/services_.rst | 6 + .../docs/workstations_v1beta/types_.rst | 6 + .../docs/workstations_v1beta/workstations.rst | 10 + .../google/cloud/workstations/__init__.py | 87 + .../cloud/workstations/gapic_version.py | 16 + .../v1beta/google/cloud/workstations/py.typed | 2 + .../cloud/workstations_v1beta/__init__.py | 88 + .../workstations_v1beta/gapic_metadata.json | 328 + .../workstations_v1beta/gapic_version.py | 16 + .../google/cloud/workstations_v1beta/py.typed | 2 + .../workstations_v1beta/services/__init__.py | 15 + .../services/workstations/__init__.py | 22 + .../services/workstations/async_client.py | 3183 +++ .../services/workstations/client.py | 3536 +++ .../services/workstations/pagers.py | 702 + .../workstations/transports/README.rst | 9 + .../workstations/transports/__init__.py | 38 + .../services/workstations/transports/base.py | 612 + .../services/workstations/transports/grpc.py | 948 + .../workstations/transports/grpc_asyncio.py | 1180 + .../services/workstations/transports/rest.py | 3048 +++ .../workstations/transports/rest_base.py | 1129 + .../workstations_v1beta/types/__init__.py | 80 + .../workstations_v1beta/types/workstations.py | 2087 ++ .../google-cloud-workstations/v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ...data_google.cloud.workstations.v1beta.json | 3307 +++ ...d_workstations_create_workstation_async.py | 57 + ...ations_create_workstation_cluster_async.py | 57 + ...tations_create_workstation_cluster_sync.py | 57 + ...tations_create_workstation_config_async.py | 57 + ...stations_create_workstation_config_sync.py | 57 + ...ed_workstations_create_workstation_sync.py | 57 + ...d_workstations_delete_workstation_async.py | 56 + ...ations_delete_workstation_cluster_async.py | 56 + ...tations_delete_workstation_cluster_sync.py | 56 + ...tations_delete_workstation_config_async.py | 56 + ...stations_delete_workstation_config_sync.py | 56 + ...ed_workstations_delete_workstation_sync.py | 56 + ...orkstations_generate_access_token_async.py | 52 + ...workstations_generate_access_token_sync.py | 52 + ...ated_workstations_get_workstation_async.py | 52 + ...kstations_get_workstation_cluster_async.py | 52 + ...rkstations_get_workstation_cluster_sync.py | 52 + ...rkstations_get_workstation_config_async.py | 52 + ...orkstations_get_workstation_config_sync.py | 52 + ...rated_workstations_get_workstation_sync.py | 52 + ...s_list_usable_workstation_configs_async.py | 53 + ...ns_list_usable_workstation_configs_sync.py | 53 + ...stations_list_usable_workstations_async.py | 53 + ...kstations_list_usable_workstations_sync.py | 53 + ...tations_list_workstation_clusters_async.py | 53 + ...stations_list_workstation_clusters_sync.py | 53 + ...stations_list_workstation_configs_async.py | 53 + ...kstations_list_workstation_configs_sync.py | 53 + ...ed_workstations_list_workstations_async.py | 53 + ...ted_workstations_list_workstations_sync.py | 53 + ...ed_workstations_start_workstation_async.py | 56 + ...ted_workstations_start_workstation_sync.py | 56 + ...ted_workstations_stop_workstation_async.py | 56 + ...ated_workstations_stop_workstation_sync.py | 56 + ...d_workstations_update_workstation_async.py | 55 + ...ations_update_workstation_cluster_async.py | 55 + ...tations_update_workstation_cluster_sync.py | 55 + ...tations_update_workstation_config_async.py | 55 + ...stations_update_workstation_config_sync.py | 55 + ...ed_workstations_update_workstation_sync.py | 55 + .../fixup_workstations_v1beta_keywords.py | 195 + .../google-cloud-workstations/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/workstations_v1beta/__init__.py | 16 + .../workstations_v1beta/test_workstations.py | 17999 ++++++++++++++++ .../google-geo-type/viewport-py/.coveragerc | 13 + .../google-geo-type/viewport-py/.flake8 | 33 + .../google-geo-type/viewport-py/MANIFEST.in | 2 + .../google-geo-type/viewport-py/README.rst | 49 + .../viewport-py/docs/_static/custom.css | 3 + .../google-geo-type/viewport-py/docs/conf.py | 376 + .../viewport-py/docs/index.rst | 7 + .../viewport-py/docs/type/services_.rst | 4 + .../viewport-py/docs/type/types_.rst | 6 + .../viewport-py/google/geo/type/__init__.py | 26 + .../google/geo/type/gapic_metadata.json | 7 + .../google/geo/type/gapic_version.py | 16 + .../viewport-py/google/geo/type/py.typed | 2 + .../google/geo/type/services/__init__.py | 15 + .../google/geo/type/types/__init__.py | 22 + .../google/geo/type/types/viewport.py | 84 + .../google-geo-type/viewport-py/mypy.ini | 3 + .../google-geo-type/viewport-py/noxfile.py | 280 + .../scripts/fixup_type_keywords.py | 175 + .../google-geo-type/viewport-py/setup.py | 98 + .../viewport-py/testing/constraints-3.10.txt | 6 + .../viewport-py/testing/constraints-3.11.txt | 6 + .../viewport-py/testing/constraints-3.12.txt | 6 + .../viewport-py/testing/constraints-3.13.txt | 6 + .../viewport-py/testing/constraints-3.7.txt | 10 + .../viewport-py/testing/constraints-3.8.txt | 6 + .../viewport-py/testing/constraints-3.9.txt | 6 + .../viewport-py/tests/__init__.py | 16 + .../viewport-py/tests/unit/__init__.py | 16 + .../viewport-py/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/type/__init__.py | 16 + .../v1/.coveragerc | 13 + .../google-maps-addressvalidation/v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../address_validation.rst | 6 + .../docs/addressvalidation_v1/services_.rst | 6 + .../v1/docs/addressvalidation_v1/types_.rst | 6 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../google/maps/addressvalidation/__init__.py | 55 + .../maps/addressvalidation/gapic_version.py | 16 + .../v1/google/maps/addressvalidation/py.typed | 2 + .../maps/addressvalidation_v1/__init__.py | 56 + .../addressvalidation_v1/gapic_metadata.json | 58 + .../addressvalidation_v1/gapic_version.py | 16 + .../google/maps/addressvalidation_v1/py.typed | 2 + .../addressvalidation_v1/services/__init__.py | 15 + .../services/address_validation/__init__.py | 22 + .../address_validation/async_client.py | 392 + .../services/address_validation/client.py | 740 + .../address_validation/transports/README.rst | 9 + .../address_validation/transports/__init__.py | 38 + .../address_validation/transports/base.py | 167 + .../address_validation/transports/grpc.py | 301 + .../transports/grpc_asyncio.py | 327 + .../address_validation/transports/rest.py | 391 + .../transports/rest_base.py | 185 + .../addressvalidation_v1/types/__init__.py | 56 + .../addressvalidation_v1/types/address.py | 244 + .../types/address_validation_service.py | 413 + .../addressvalidation_v1/types/geocode.py | 132 + .../addressvalidation_v1/types/metadata_.py | 76 + .../addressvalidation_v1/types/usps_data.py | 493 + .../google-maps-addressvalidation/v1/mypy.ini | 3 + .../v1/noxfile.py | 280 + ...ation_provide_validation_feedback_async.py | 53 + ...dation_provide_validation_feedback_sync.py | 53 + ...dress_validation_validate_address_async.py | 51 + ...ddress_validation_validate_address_sync.py | 51 + ...data_google.maps.addressvalidation.v1.json | 321 + .../fixup_addressvalidation_v1_keywords.py | 177 + .../google-maps-addressvalidation/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 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/addressvalidation_v1/__init__.py | 16 + .../test_address_validation.py | 2364 ++ .../google-maps-areainsights/v1/.coveragerc | 13 + .../google-maps-areainsights/v1/.flake8 | 33 + .../google-maps-areainsights/v1/MANIFEST.in | 2 + .../google-maps-areainsights/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/areainsights_v1/area_insights.rst | 6 + .../v1/docs/areainsights_v1/services_.rst | 6 + .../v1/docs/areainsights_v1/types_.rst | 6 + .../google-maps-areainsights/v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../v1/google/maps/areainsights/__init__.py | 47 + .../google/maps/areainsights/gapic_version.py | 16 + .../v1/google/maps/areainsights/py.typed | 2 + .../google/maps/areainsights_v1/__init__.py | 48 + .../maps/areainsights_v1/gapic_metadata.json | 43 + .../maps/areainsights_v1/gapic_version.py | 16 + .../v1/google/maps/areainsights_v1/py.typed | 2 + .../maps/areainsights_v1/services/__init__.py | 15 + .../services/area_insights/__init__.py | 22 + .../services/area_insights/async_client.py | 321 + .../services/area_insights/client.py | 678 + .../area_insights/transports/README.rst | 9 + .../area_insights/transports/__init__.py | 38 + .../services/area_insights/transports/base.py | 163 + .../services/area_insights/transports/grpc.py | 282 + .../area_insights/transports/grpc_asyncio.py | 312 + .../services/area_insights/transports/rest.py | 275 + .../area_insights/transports/rest_base.py | 138 + .../maps/areainsights_v1/types/__init__.py | 40 + .../types/area_insights_service.py | 512 + .../google-maps-areainsights/v1/mypy.ini | 3 + .../google-maps-areainsights/v1/noxfile.py | 280 + ...ed_area_insights_compute_insights_async.py | 52 + ...ted_area_insights_compute_insights_sync.py | 52 + ..._metadata_google.maps.areainsights.v1.json | 168 + .../scripts/fixup_areainsights_v1_keywords.py | 176 + .../google-maps-areainsights/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 + .../unit/gapic/areainsights_v1/__init__.py | 16 + .../areainsights_v1/test_area_insights.py | 1935 ++ .../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 + .../delivery_service.rst | 10 + .../fleetengine_delivery_v1/services_.rst | 6 + .../docs/fleetengine_delivery_v1/types_.rst | 6 + .../v1/docs/index.rst | 7 + .../maps/fleetengine_delivery/__init__.py | 81 + .../fleetengine_delivery/gapic_version.py | 16 + .../google/maps/fleetengine_delivery/py.typed | 2 + .../maps/fleetengine_delivery_v1/__init__.py | 82 + .../gapic_metadata.json | 178 + .../fleetengine_delivery_v1/gapic_version.py | 16 + .../maps/fleetengine_delivery_v1/py.typed | 2 + .../services/__init__.py | 15 + .../services/delivery_service/__init__.py | 22 + .../services/delivery_service/async_client.py | 1558 ++ .../services/delivery_service/client.py | 1924 ++ .../services/delivery_service/pagers.py | 299 + .../delivery_service/transports/README.rst | 9 + .../delivery_service/transports/__init__.py | 38 + .../delivery_service/transports/base.py | 373 + .../delivery_service/transports/grpc.py | 516 + .../transports/grpc_asyncio.py | 672 + .../delivery_service/transports/rest.py | 1318 ++ .../delivery_service/transports/rest_base.py | 514 + .../fleetengine_delivery_v1/types/__init__.py | 84 + .../fleetengine_delivery_v1/types/common.py | 471 + .../types/delivery_api.py | 603 + .../types/delivery_vehicles.py | 414 + .../fleetengine_delivery_v1/types/header.py | 168 + .../types/task_tracking_info.py | 166 + .../fleetengine_delivery_v1/types/tasks.py | 473 + .../v1/maps-fleetengine-delivery-v1-py.tar.gz | 0 .../v1/mypy.ini | 3 + .../v1/noxfile.py | 280 + ...livery_service_batch_create_tasks_async.py | 59 + ...elivery_service_batch_create_tasks_sync.py | 59 + ...y_service_create_delivery_vehicle_async.py | 53 + ...ry_service_create_delivery_vehicle_sync.py | 53 + ...ated_delivery_service_create_task_async.py | 58 + ...rated_delivery_service_create_task_sync.py | 58 + ...very_service_get_delivery_vehicle_async.py | 52 + ...ivery_service_get_delivery_vehicle_sync.py | 52 + ...nerated_delivery_service_get_task_async.py | 52 + ...enerated_delivery_service_get_task_sync.py | 52 + ...ry_service_get_task_tracking_info_async.py | 52 + ...ery_service_get_task_tracking_info_sync.py | 52 + ...ry_service_list_delivery_vehicles_async.py | 53 + ...ery_service_list_delivery_vehicles_sync.py | 53 + ...rated_delivery_service_list_tasks_async.py | 53 + ...erated_delivery_service_list_tasks_sync.py | 53 + ...y_service_update_delivery_vehicle_async.py | 51 + ...ry_service_update_delivery_vehicle_sync.py | 51 + ...ated_delivery_service_update_task_async.py | 56 + ...rated_delivery_service_update_task_sync.py | 56 + ...metadata_maps.fleetengine.delivery.v1.json | 1665 ++ .../fixup_fleetengine_delivery_v1_keywords.py | 185 + .../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 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/fleetengine_delivery_v1/__init__.py | 16 + .../test_delivery_service.py | 9124 ++++++++ .../google-maps-fleetengine/v1/.coveragerc | 13 + .../google-maps-fleetengine/v1/.flake8 | 33 + .../google-maps-fleetengine/v1/MANIFEST.in | 2 + .../google-maps-fleetengine/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../google-maps-fleetengine/v1/docs/conf.py | 376 + .../v1/docs/fleetengine_v1/services_.rst | 7 + .../v1/docs/fleetengine_v1/trip_service.rst | 10 + .../v1/docs/fleetengine_v1/types_.rst | 6 + .../docs/fleetengine_v1/vehicle_service.rst | 10 + .../google-maps-fleetengine/v1/docs/index.rst | 7 + .../v1/google/maps/fleetengine/__init__.py | 123 + .../google/maps/fleetengine/gapic_version.py | 16 + .../v1/google/maps/fleetengine/py.typed | 2 + .../v1/google/maps/fleetengine_v1/__init__.py | 124 + .../maps/fleetengine_v1/gapic_metadata.json | 147 + .../maps/fleetengine_v1/gapic_version.py | 16 + .../v1/google/maps/fleetengine_v1/py.typed | 2 + .../maps/fleetengine_v1/services/__init__.py | 15 + .../services/trip_service/__init__.py | 22 + .../services/trip_service/async_client.py | 675 + .../services/trip_service/client.py | 1030 + .../services/trip_service/pagers.py | 163 + .../trip_service/transports/README.rst | 9 + .../trip_service/transports/__init__.py | 33 + .../services/trip_service/transports/base.py | 248 + .../services/trip_service/transports/grpc.py | 377 + .../trip_service/transports/grpc_asyncio.py | 454 + .../services/vehicle_service/__init__.py | 22 + .../services/vehicle_service/async_client.py | 827 + .../services/vehicle_service/client.py | 1182 + .../services/vehicle_service/pagers.py | 163 + .../vehicle_service/transports/README.rst | 9 + .../vehicle_service/transports/__init__.py | 33 + .../vehicle_service/transports/base.py | 270 + .../vehicle_service/transports/grpc.py | 455 + .../transports/grpc_asyncio.py | 546 + .../maps/fleetengine_v1/types/__init__.py | 124 + .../maps/fleetengine_v1/types/fleetengine.py | 628 + .../maps/fleetengine_v1/types/header.py | 168 + .../maps/fleetengine_v1/types/traffic.py | 108 + .../maps/fleetengine_v1/types/trip_api.py | 460 + .../google/maps/fleetengine_v1/types/trips.py | 490 + .../maps/fleetengine_v1/types/vehicle_api.py | 1050 + .../maps/fleetengine_v1/types/vehicles.py | 580 + .../google-maps-fleetengine/v1/mypy.ini | 3 + .../google-maps-fleetengine/v1/noxfile.py | 280 + ...enerated_trip_service_create_trip_async.py | 53 + ...generated_trip_service_create_trip_sync.py | 53 + ...1_generated_trip_service_get_trip_async.py | 52 + ...v1_generated_trip_service_get_trip_sync.py | 52 + ...trip_service_report_billable_trip_async.py | 51 + ..._trip_service_report_billable_trip_sync.py | 51 + ...nerated_trip_service_search_trips_async.py | 53 + ...enerated_trip_service_search_trips_sync.py | 53 + ...enerated_trip_service_update_trip_async.py | 52 + ...generated_trip_service_update_trip_sync.py | 52 + ...ed_vehicle_service_create_vehicle_async.py | 53 + ...ted_vehicle_service_create_vehicle_sync.py | 53 + ...rated_vehicle_service_get_vehicle_async.py | 52 + ...erated_vehicle_service_get_vehicle_sync.py | 52 + ...ted_vehicle_service_list_vehicles_async.py | 54 + ...ated_vehicle_service_list_vehicles_sync.py | 54 + ...d_vehicle_service_search_vehicles_async.py | 57 + ...ed_vehicle_service_search_vehicles_sync.py | 57 + ...ed_vehicle_service_update_vehicle_async.py | 52 + ...service_update_vehicle_attributes_async.py | 56 + ..._service_update_vehicle_attributes_sync.py | 56 + ...ted_vehicle_service_update_vehicle_sync.py | 52 + .../snippet_metadata_maps.fleetengine.v1.json | 1692 ++ .../scripts/fixup_fleetengine_v1_keywords.py | 186 + .../google-maps-fleetengine/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 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/fleetengine_v1/__init__.py | 16 + .../gapic/fleetengine_v1/test_trip_service.py | 3085 +++ .../fleetengine_v1/test_vehicle_service.py | 3340 +++ .../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 | 907 + .../services/maps_platform_datasets/client.py | 1258 ++ .../services/maps_platform_datasets/pagers.py | 299 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../maps_platform_datasets/transports/base.py | 254 + .../maps_platform_datasets/transports/grpc.py | 403 + .../transports/grpc_asyncio.py | 476 + .../maps_platform_datasets/transports/rest.py | 787 + .../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 | 6146 ++++++ .../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 | 81 + .../v1/google/maps/places/gapic_version.py | 16 + .../v1/google/maps/places/py.typed | 2 + .../v1/google/maps/places_v1/__init__.py | 82 + .../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 | 691 + .../maps/places_v1/services/places/client.py | 1073 + .../services/places/transports/README.rst | 9 + .../services/places/transports/__init__.py | 38 + .../services/places/transports/base.py | 210 + .../services/places/transports/grpc.py | 380 + .../places/transports/grpc_asyncio.py | 421 + .../services/places/transports/rest.py | 708 + .../services/places/transports/rest_base.py | 307 + .../google/maps/places_v1/types/__init__.py | 104 + .../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 | 1208 ++ .../maps/places_v1/types/places_service.py | 1316 ++ .../google/maps/places_v1/types/polyline.py | 62 + .../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 | 83 + .../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 | 4498 ++++ .../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 | 548 + .../services/route_optimization/client.py | 898 + .../route_optimization/transports/README.rst | 9 + .../route_optimization/transports/__init__.py | 38 + .../route_optimization/transports/base.py | 198 + .../route_optimization/transports/grpc.py | 394 + .../transports/grpc_asyncio.py | 434 + .../route_optimization/transports/rest.py | 547 + .../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 | 2749 +++ .../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 | 113 + .../v2/google/maps/routing/gapic_version.py | 16 + .../v2/google/maps/routing/py.typed | 2 + .../v2/google/maps/routing_v2/__init__.py | 114 + .../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 | 460 + .../maps/routing_v2/services/routes/client.py | 808 + .../services/routes/transports/README.rst | 9 + .../services/routes/transports/__init__.py | 38 + .../services/routes/transports/base.py | 167 + .../services/routes/transports/grpc.py | 369 + .../routes/transports/grpc_asyncio.py | 395 + .../services/routes/transports/rest.py | 384 + .../services/routes/transports/rest_base.py | 185 + .../google/maps/routing_v2/types/__init__.py | 150 + .../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 + .../v2/google/maps/routing_v2/types/route.py | 787 + .../maps/routing_v2/types/route_label.py | 58 + .../maps/routing_v2/types/route_modifiers.py | 98 + .../routing_v2/types/route_travel_mode.py | 63 + .../maps/routing_v2/types/routes_service.py | 713 + .../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 | 2389 ++ .../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 | 521 + .../maps/solar_v1/services/solar/client.py | 869 + .../services/solar/transports/README.rst | 9 + .../services/solar/transports/__init__.py | 38 + .../services/solar/transports/base.py | 210 + .../services/solar/transports/grpc.py | 327 + .../services/solar/transports/grpc_asyncio.py | 385 + .../services/solar/transports/rest.py | 548 + .../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 | 2921 +++ .../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 | 357 + .../services/account_issue_service/client.py | 722 + .../services/account_issue_service/pagers.py | 162 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../account_issue_service/transports/base.py | 154 + .../account_issue_service/transports/grpc.py | 271 + .../transports/grpc_asyncio.py | 292 + .../account_issue_service/transports/rest.py | 272 + .../transports/rest_base.py | 128 + .../services/account_tax_service/__init__.py | 22 + .../account_tax_service/async_client.py | 588 + .../services/account_tax_service/client.py | 942 + .../services/account_tax_service/pagers.py | 162 + .../account_tax_service/transports/README.rst | 9 + .../transports/__init__.py | 38 + .../account_tax_service/transports/base.py | 183 + .../account_tax_service/transports/grpc.py | 331 + .../transports/grpc_asyncio.py | 362 + .../account_tax_service/transports/rest.py | 502 + .../transports/rest_base.py | 213 + .../services/accounts_service/__init__.py | 22 + .../services/accounts_service/async_client.py | 852 + .../services/accounts_service/client.py | 1223 ++ .../services/accounts_service/pagers.py | 297 + .../accounts_service/transports/README.rst | 9 + .../accounts_service/transports/__init__.py | 38 + .../accounts_service/transports/base.py | 225 + .../accounts_service/transports/grpc.py | 425 + .../transports/grpc_asyncio.py | 471 + .../accounts_service/transports/rest.py | 776 + .../accounts_service/transports/rest_base.py | 326 + .../autofeed_settings_service/__init__.py | 22 + .../autofeed_settings_service/async_client.py | 461 + .../autofeed_settings_service/client.py | 816 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 298 + .../transports/grpc_asyncio.py | 324 + .../transports/rest.py | 388 + .../transports/rest_base.py | 175 + .../business_identity_service/__init__.py | 22 + .../business_identity_service/async_client.py | 456 + .../business_identity_service/client.py | 811 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 299 + .../transports/grpc_asyncio.py | 325 + .../transports/rest.py | 386 + .../transports/rest_base.py | 175 + .../business_info_service/__init__.py | 22 + .../business_info_service/async_client.py | 456 + .../services/business_info_service/client.py | 811 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../business_info_service/transports/base.py | 168 + .../business_info_service/transports/grpc.py | 297 + .../transports/grpc_asyncio.py | 323 + .../business_info_service/transports/rest.py | 383 + .../transports/rest_base.py | 175 + .../email_preferences_service/__init__.py | 22 + .../email_preferences_service/async_client.py | 479 + .../email_preferences_service/client.py | 834 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 314 + .../transports/grpc_asyncio.py | 340 + .../transports/rest.py | 394 + .../transports/rest_base.py | 175 + .../services/homepage_service/__init__.py | 22 + .../services/homepage_service/async_client.py | 622 + .../services/homepage_service/client.py | 977 + .../homepage_service/transports/README.rst | 9 + .../homepage_service/transports/__init__.py | 38 + .../homepage_service/transports/base.py | 197 + .../homepage_service/transports/grpc.py | 363 + .../transports/grpc_asyncio.py | 399 + .../homepage_service/transports/rest.py | 594 + .../homepage_service/transports/rest_base.py | 270 + .../online_return_policy_service/__init__.py | 22 + .../async_client.py | 469 + .../online_return_policy_service/client.py | 824 + .../online_return_policy_service/pagers.py | 162 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 303 + .../transports/grpc_asyncio.py | 329 + .../transports/rest.py | 392 + .../transports/rest_base.py | 165 + .../services/programs_service/__init__.py | 22 + .../services/programs_service/async_client.py | 702 + .../services/programs_service/client.py | 1055 + .../services/programs_service/pagers.py | 162 + .../programs_service/transports/README.rst | 9 + .../programs_service/transports/__init__.py | 38 + .../programs_service/transports/base.py | 196 + .../programs_service/transports/grpc.py | 361 + .../transports/grpc_asyncio.py | 397 + .../programs_service/transports/rest.py | 633 + .../programs_service/transports/rest_base.py | 259 + .../services/regions_service/__init__.py | 22 + .../services/regions_service/async_client.py | 806 + .../services/regions_service/client.py | 1167 + .../services/regions_service/pagers.py | 162 + .../regions_service/transports/README.rst | 9 + .../regions_service/transports/__init__.py | 38 + .../regions_service/transports/base.py | 211 + .../regions_service/transports/grpc.py | 383 + .../transports/grpc_asyncio.py | 424 + .../regions_service/transports/rest.py | 698 + .../regions_service/transports/rest_base.py | 297 + .../shipping_settings_service/__init__.py | 22 + .../shipping_settings_service/async_client.py | 430 + .../shipping_settings_service/client.py | 786 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 299 + .../transports/grpc_asyncio.py | 325 + .../transports/rest.py | 385 + .../transports/rest_base.py | 175 + .../__init__.py | 22 + .../async_client.py | 504 + .../client.py | 877 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 168 + .../transports/grpc.py | 299 + .../transports/grpc_asyncio.py | 325 + .../transports/rest.py | 437 + .../transports/rest_base.py | 165 + .../terms_of_service_service/__init__.py | 22 + .../terms_of_service_service/async_client.py | 509 + .../terms_of_service_service/client.py | 873 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 183 + .../transports/grpc.py | 327 + .../transports/grpc_asyncio.py | 358 + .../transports/rest.py | 458 + .../transports/rest_base.py | 203 + .../services/user_service/__init__.py | 22 + .../services/user_service/async_client.py | 786 + .../services/user_service/client.py | 1147 + .../services/user_service/pagers.py | 162 + .../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 | 379 + .../user_service/transports/grpc_asyncio.py | 420 + .../services/user_service/transports/rest.py | 677 + .../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/merchant-accounts-v1beta-py.tar.gz | Bin 0 -> 360448 bytes .../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 | 2424 +++ .../test_account_tax_service.py | 3791 ++++ .../test_accounts_service.py | 5618 +++++ .../test_autofeed_settings_service.py | 2887 +++ .../test_business_identity_service.py | 2873 +++ .../test_business_info_service.py | 2891 +++ .../test_email_preferences_service.py | 2875 +++ .../test_homepage_service.py | 3946 ++++ .../test_online_return_policy_service.py | 3115 +++ .../test_programs_service.py | 4414 ++++ .../test_regions_service.py | 5190 +++++ .../test_shipping_settings_service.py | 2731 +++ ...erms_of_service_agreement_state_service.py | 2851 +++ .../test_terms_of_service_service.py | 3324 +++ .../test_user_service.py | 5200 +++++ .../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 | 894 + .../conversion_sources_service/client.py | 1246 ++ .../conversion_sources_service/pagers.py | 162 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 225 + .../transports/grpc.py | 411 + .../transports/grpc_asyncio.py | 457 + .../transports/rest.py | 803 + .../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 | 5696 +++++ .../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 | 879 + .../services/data_sources_service/client.py | 1231 ++ .../services/data_sources_service/pagers.py | 162 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../data_sources_service/transports/base.py | 225 + .../data_sources_service/transports/grpc.py | 416 + .../transports/grpc_asyncio.py | 462 + .../data_sources_service/transports/rest.py | 772 + .../transports/rest_base.py | 344 + .../services/file_uploads_service/__init__.py | 22 + .../file_uploads_service/async_client.py | 348 + .../services/file_uploads_service/client.py | 704 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../file_uploads_service/transports/base.py | 154 + .../file_uploads_service/transports/grpc.py | 271 + .../transports/grpc_asyncio.py | 292 + .../file_uploads_service/transports/rest.py | 280 + .../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 | 5682 +++++ .../test_file_uploads_service.py | 2177 ++ .../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 | 557 + .../local_inventory_service/client.py | 912 + .../local_inventory_service/pagers.py | 162 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 183 + .../transports/grpc.py | 342 + .../transports/grpc_asyncio.py | 373 + .../transports/rest.py | 468 + .../transports/rest_base.py | 213 + .../regional_inventory_service/__init__.py | 22 + .../async_client.py | 563 + .../regional_inventory_service/client.py | 918 + .../regional_inventory_service/pagers.py | 162 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 183 + .../transports/grpc.py | 343 + .../transports/grpc_asyncio.py | 374 + .../transports/rest.py | 472 + .../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 | 3659 ++++ .../test_regional_inventory_service.py | 3631 ++++ .../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 | 333 + .../services/lfp_inventory_service/client.py | 690 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../lfp_inventory_service/transports/base.py | 154 + .../lfp_inventory_service/transports/grpc.py | 274 + .../transports/grpc_asyncio.py | 295 + .../lfp_inventory_service/transports/rest.py | 277 + .../transports/rest_base.py | 138 + .../services/lfp_sale_service/__init__.py | 22 + .../services/lfp_sale_service/async_client.py | 333 + .../services/lfp_sale_service/client.py | 690 + .../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 | 272 + .../transports/grpc_asyncio.py | 293 + .../lfp_sale_service/transports/rest.py | 278 + .../lfp_sale_service/transports/rest_base.py | 138 + .../services/lfp_store_service/__init__.py | 22 + .../lfp_store_service/async_client.py | 684 + .../services/lfp_store_service/client.py | 1037 + .../services/lfp_store_service/pagers.py | 162 + .../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 | 354 + .../transports/grpc_asyncio.py | 390 + .../lfp_store_service/transports/rest.py | 584 + .../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 | 2152 ++ .../test_lfp_sale_service.py | 2134 ++ .../test_lfp_store_service.py | 4555 ++++ .../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 | 804 + .../notifications_api_service/client.py | 1156 + .../notifications_api_service/pagers.py | 162 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 211 + .../transports/grpc.py | 398 + .../transports/grpc_asyncio.py | 439 + .../transports/rest.py | 691 + .../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 | 5172 +++++ .../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 + .../product_inputs_service.rst | 6 + .../products_service.rst | 10 + .../merchant_products_v1beta/services_.rst | 7 + .../docs/merchant_products_v1beta/types_.rst | 6 + .../shopping/merchant_products/__init__.py | 87 + .../merchant_products/gapic_version.py | 16 + .../shopping/merchant_products/py.typed | 2 + .../merchant_products_v1beta/__init__.py | 88 + .../gapic_metadata.json | 107 + .../merchant_products_v1beta/gapic_version.py | 16 + .../merchant_products_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../product_inputs_service/__init__.py | 22 + .../product_inputs_service/async_client.py | 462 + .../services/product_inputs_service/client.py | 827 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../product_inputs_service/transports/base.py | 169 + .../product_inputs_service/transports/grpc.py | 309 + .../transports/grpc_asyncio.py | 335 + .../product_inputs_service/transports/rest.py | 384 + .../transports/rest_base.py | 176 + .../services/products_service/__init__.py | 22 + .../services/products_service/async_client.py | 490 + .../services/products_service/client.py | 845 + .../services/products_service/pagers.py | 162 + .../products_service/transports/README.rst | 9 + .../products_service/transports/__init__.py | 38 + .../products_service/transports/base.py | 168 + .../products_service/transports/grpc.py | 308 + .../transports/grpc_asyncio.py | 334 + .../products_service/transports/rest.py | 398 + .../products_service/transports/rest_base.py | 165 + .../types/__init__.py | 80 + .../types/productinputs.py | 220 + .../types/products.py | 240 + .../types/products_common.py | 1906 ++ .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 280 + ...puts_service_delete_product_input_async.py | 51 + ...nputs_service_delete_product_input_sync.py | 51 + ...puts_service_insert_product_input_async.py | 60 + ...nputs_service_insert_product_input_sync.py | 60 + ...ated_products_service_get_product_async.py | 52 + ...rated_products_service_get_product_sync.py | 52 + ...ed_products_service_list_products_async.py | 53 + ...ted_products_service_list_products_sync.py | 53 + ...gle.shopping.merchant.products.v1beta.json | 645 + ...fixup_merchant_products_v1beta_keywords.py | 179 + .../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_products_v1beta/__init__.py | 16 + .../test_product_inputs_service.py | 2788 +++ .../test_products_service.py | 3096 +++ 1971 files changed, 551003 insertions(+) create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/web_security_scanner.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/py.typed create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_log.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/scripts/fixup_websecurityscanner_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.coveragerc create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.flake8 create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/README.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/services_.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/types_.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/py.typed create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/mypy.ini create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/noxfile.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/setup.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/.flake8 create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/README.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/services_.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/types_.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/py.typed create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/py.typed create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/setup.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-workflows/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-workflows/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-workflows/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/executions.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/workflows.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/py.typed create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/async_client.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/client.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/pagers.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/base.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/executions.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/py.typed create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/async_client.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/client.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/pagers.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/base.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/workflows.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-workflows/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_executions_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_workflows_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/test_executions.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/test_workflows.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/.flake8 create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/README.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/executions.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/services_.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/types_.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/services_.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/types_.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/workflows.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/py.typed create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/py.typed create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/async_client.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/client.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/pagers.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/base.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/executions.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/py.typed create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/py.typed create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/async_client.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/client.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/pagers.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/base.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/workflows.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_async.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_sync.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_executions_v1beta_keywords.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_workflows_v1beta_keywords.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/setup.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/test_executions.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/test_workflows.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-workstations/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-workstations/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-workstations/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/.flake8 create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/README.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services_.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types_.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/setup.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/.coveragerc create mode 100644 owl-bot-staging/google-geo-type/viewport-py/.flake8 create mode 100644 owl-bot-staging/google-geo-type/viewport-py/MANIFEST.in create mode 100644 owl-bot-staging/google-geo-type/viewport-py/README.rst create mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/_static/custom.css create mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/conf.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/index.rst create mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/type/services_.rst create mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/type/types_.rst create mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/__init__.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_metadata.json create mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_version.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/py.typed create mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/services/__init__.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/__init__.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/viewport.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/mypy.ini create mode 100644 owl-bot-staging/google-geo-type/viewport-py/noxfile.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/scripts/fixup_type_keywords.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/setup.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-geo-type/viewport-py/tests/__init__.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/type/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/.coveragerc create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/.flake8 create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/README.rst create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/address_validation.rst create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/services_.rst create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/types_.rst create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/conf.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/index.rst create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/gapic_version.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/py.typed create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_version.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/py.typed create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/async_client.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/client.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/README.rst create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/base.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest_base.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address_validation_service.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/geocode.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/metadata_.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/usps_data.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/mypy.ini create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/noxfile.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_async.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_sync.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/scripts/fixup_addressvalidation_v1_keywords.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/setup.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/test_address_validation.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/.coveragerc create mode 100644 owl-bot-staging/google-maps-areainsights/v1/.flake8 create mode 100644 owl-bot-staging/google-maps-areainsights/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-areainsights/v1/README.rst create mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/area_insights.rst create mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/services_.rst create mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/types_.rst create mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/conf.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/index.rst create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/gapic_version.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/py.typed create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_version.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/py.typed create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/async_client.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/client.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/README.rst create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/base.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest_base.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/area_insights_service.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/mypy.ini create mode 100644 owl-bot-staging/google-maps-areainsights/v1/noxfile.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_async.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_sync.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/snippet_metadata_google.maps.areainsights.v1.json create mode 100644 owl-bot-staging/google-maps-areainsights/v1/scripts/fixup_areainsights_v1_keywords.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/setup.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/test_area_insights.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/.flake8 create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/conf.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/gapic_version.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_version.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/README.rst create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/maps-fleetengine-delivery-v1-py.tar.gz create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/noxfile.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/setup.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/.coveragerc create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/.flake8 create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/README.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/mypy.ini create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/noxfile.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/setup.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py 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/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/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/merchant-accounts-v1beta-py.tar.gz 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-products/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/product_inputs_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/products_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/productinputs.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products_common.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.products.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/scripts/fixup_merchant_products_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_product_inputs_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_products_service.py diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/.coveragerc b/owl-bot-staging/google-cloud-websecurityscanner/v1/.coveragerc new file mode 100644 index 000000000000..085a92b30288 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/websecurityscanner/__init__.py + google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1/.flake8 b/owl-bot-staging/google-cloud-websecurityscanner/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/MANIFEST.in b/owl-bot-staging/google-cloud-websecurityscanner/v1/MANIFEST.in new file mode 100644 index 000000000000..9d26e3bccd4a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/websecurityscanner *.py +recursive-include google/cloud/websecurityscanner_v1 *.py diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/README.rst new file mode 100644 index 000000000000..4de4c103eee6 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Websecurityscanner 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 Cloud Websecurityscanner 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-cloud-websecurityscanner/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/conf.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/conf.py new file mode 100644 index 000000000000..40ff11b301ef --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner 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-cloud-websecurityscanner" +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 Cloud 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-cloud-websecurityscanner-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-cloud-websecurityscanner.tex", + u"google-cloud-websecurityscanner 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-cloud-websecurityscanner", + u"Google Cloud Websecurityscanner 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-cloud-websecurityscanner", + u"google-cloud-websecurityscanner Documentation", + author, + "google-cloud-websecurityscanner", + "GAPIC library for Google Cloud Websecurityscanner 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-cloud-websecurityscanner/v1/docs/index.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/index.rst new file mode 100644 index 000000000000..44c047fb4284 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + websecurityscanner_v1/services_ + websecurityscanner_v1/types_ diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/services_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/services_.rst new file mode 100644 index 000000000000..6fb98e606cb4 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Websecurityscanner v1 API +=================================================== +.. toctree:: + :maxdepth: 2 + + web_security_scanner diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/types_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/types_.rst new file mode 100644 index 000000000000..ad00a256c35d --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Websecurityscanner v1 API +================================================ + +.. automodule:: google.cloud.websecurityscanner_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/web_security_scanner.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/web_security_scanner.rst new file mode 100644 index 000000000000..4925421b2eda --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/web_security_scanner.rst @@ -0,0 +1,10 @@ +WebSecurityScanner +------------------------------------ + +.. automodule:: google.cloud.websecurityscanner_v1.services.web_security_scanner + :members: + :inherited-members: + +.. automodule:: google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/__init__.py new file mode 100644 index 000000000000..8e29513bc1fb --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/__init__.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 google.cloud.websecurityscanner import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.websecurityscanner_v1.services.web_security_scanner.client import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient + +from google.cloud.websecurityscanner_v1.types.crawled_url import CrawledUrl +from google.cloud.websecurityscanner_v1.types.finding import Finding +from google.cloud.websecurityscanner_v1.types.finding_addon import Form +from google.cloud.websecurityscanner_v1.types.finding_addon import OutdatedLibrary +from google.cloud.websecurityscanner_v1.types.finding_addon import ViolatingResource +from google.cloud.websecurityscanner_v1.types.finding_addon import VulnerableHeaders +from google.cloud.websecurityscanner_v1.types.finding_addon import VulnerableParameters +from google.cloud.websecurityscanner_v1.types.finding_addon import Xss +from google.cloud.websecurityscanner_v1.types.finding_addon import Xxe +from google.cloud.websecurityscanner_v1.types.finding_type_stats import FindingTypeStats +from google.cloud.websecurityscanner_v1.types.scan_config import ScanConfig +from google.cloud.websecurityscanner_v1.types.scan_config_error import ScanConfigError +from google.cloud.websecurityscanner_v1.types.scan_run import ScanRun +from google.cloud.websecurityscanner_v1.types.scan_run_error_trace import ScanRunErrorTrace +from google.cloud.websecurityscanner_v1.types.scan_run_log import ScanRunLog +from google.cloud.websecurityscanner_v1.types.scan_run_warning_trace import ScanRunWarningTrace +from google.cloud.websecurityscanner_v1.types.web_security_scanner import CreateScanConfigRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import DeleteScanConfigRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetFindingRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetScanConfigRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetScanRunRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListCrawledUrlsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListCrawledUrlsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingTypeStatsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingTypeStatsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanConfigsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanConfigsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanRunsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanRunsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import StartScanRunRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import StopScanRunRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ('WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', + 'CrawledUrl', + 'Finding', + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'Xxe', + 'FindingTypeStats', + 'ScanConfig', + 'ScanConfigError', + 'ScanRun', + 'ScanRunErrorTrace', + 'ScanRunLog', + 'ScanRunWarningTrace', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/py.typed new file mode 100644 index 000000000000..8cfb5d256398 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/__init__.py new file mode 100644 index 000000000000..5f1bfbc58721 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/__init__.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.web_security_scanner import WebSecurityScannerClient +from .services.web_security_scanner import WebSecurityScannerAsyncClient + +from .types.crawled_url import CrawledUrl +from .types.finding import Finding +from .types.finding_addon import Form +from .types.finding_addon import OutdatedLibrary +from .types.finding_addon import ViolatingResource +from .types.finding_addon import VulnerableHeaders +from .types.finding_addon import VulnerableParameters +from .types.finding_addon import Xss +from .types.finding_addon import Xxe +from .types.finding_type_stats import FindingTypeStats +from .types.scan_config import ScanConfig +from .types.scan_config_error import ScanConfigError +from .types.scan_run import ScanRun +from .types.scan_run_error_trace import ScanRunErrorTrace +from .types.scan_run_log import ScanRunLog +from .types.scan_run_warning_trace import ScanRunWarningTrace +from .types.web_security_scanner import CreateScanConfigRequest +from .types.web_security_scanner import DeleteScanConfigRequest +from .types.web_security_scanner import GetFindingRequest +from .types.web_security_scanner import GetScanConfigRequest +from .types.web_security_scanner import GetScanRunRequest +from .types.web_security_scanner import ListCrawledUrlsRequest +from .types.web_security_scanner import ListCrawledUrlsResponse +from .types.web_security_scanner import ListFindingsRequest +from .types.web_security_scanner import ListFindingsResponse +from .types.web_security_scanner import ListFindingTypeStatsRequest +from .types.web_security_scanner import ListFindingTypeStatsResponse +from .types.web_security_scanner import ListScanConfigsRequest +from .types.web_security_scanner import ListScanConfigsResponse +from .types.web_security_scanner import ListScanRunsRequest +from .types.web_security_scanner import ListScanRunsResponse +from .types.web_security_scanner import StartScanRunRequest +from .types.web_security_scanner import StopScanRunRequest +from .types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ( + 'WebSecurityScannerAsyncClient', +'CrawledUrl', +'CreateScanConfigRequest', +'DeleteScanConfigRequest', +'Finding', +'FindingTypeStats', +'Form', +'GetFindingRequest', +'GetScanConfigRequest', +'GetScanRunRequest', +'ListCrawledUrlsRequest', +'ListCrawledUrlsResponse', +'ListFindingTypeStatsRequest', +'ListFindingTypeStatsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListScanConfigsRequest', +'ListScanConfigsResponse', +'ListScanRunsRequest', +'ListScanRunsResponse', +'OutdatedLibrary', +'ScanConfig', +'ScanConfigError', +'ScanRun', +'ScanRunErrorTrace', +'ScanRunLog', +'ScanRunWarningTrace', +'StartScanRunRequest', +'StopScanRunRequest', +'UpdateScanConfigRequest', +'ViolatingResource', +'VulnerableHeaders', +'VulnerableParameters', +'WebSecurityScannerClient', +'Xss', +'Xxe', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json new file mode 100644 index 000000000000..9f9d16e522dc --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json @@ -0,0 +1,223 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.websecurityscanner_v1", + "protoPackage": "google.cloud.websecurityscanner.v1", + "schema": "1.0", + "services": { + "WebSecurityScanner": { + "clients": { + "grpc": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebSecurityScannerAsyncClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + }, + "rest": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/py.typed new file mode 100644 index 000000000000..8cfb5d256398 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py new file mode 100644 index 000000000000..3aeec5e07d95 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__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 WebSecurityScannerClient +from .async_client import WebSecurityScannerAsyncClient + +__all__ = ( + 'WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py new file mode 100644 index 000000000000..428a9bc8f21c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py @@ -0,0 +1,1353 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.websecurityscanner_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.cloud.websecurityscanner_v1.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import finding_addon +from google.cloud.websecurityscanner_v1.types import finding_type_stats +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .client import WebSecurityScannerClient + + +class WebSecurityScannerAsyncClient: + """Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + """ + + _client: WebSecurityScannerClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WebSecurityScannerClient._DEFAULT_UNIVERSE + + finding_path = staticmethod(WebSecurityScannerClient.finding_path) + parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) + common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) + parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) + common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) + parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) + common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) + parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) + common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) + parse_common_location_path = staticmethod(WebSecurityScannerClient.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: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, 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: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, 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 WebSecurityScannerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: 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 = WebSecurityScannerClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner 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,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): + 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 WebSecurityScannerTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WebSecurityScannerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_scan_config(self, + request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.CreateScanConfigRequest( + ) + + # Make the request + response = await client.create_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest, dict]]): + The request object. Request for the ``CreateScanConfig`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # 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, web_security_scanner.CreateScanConfigRequest): + request = web_security_scanner.CreateScanConfigRequest(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_scan_config] + + # Certain fields should be provided within 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_scan_config(self, + request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.DeleteScanConfigRequest( + ) + + # Make the request + await client.delete_scan_config(request=request) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest, dict]]): + The request object. Request for the ``DeleteScanConfig`` 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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, web_security_scanner.DeleteScanConfigRequest): + request = web_security_scanner.DeleteScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_scan_config] + + # Certain fields should be provided within 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 get_scan_config(self, + request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetScanConfigRequest( + ) + + # Make the request + response = await client.get_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.GetScanConfigRequest, dict]]): + The request object. Request for the ``GetScanConfig`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # 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, web_security_scanner.GetScanConfigRequest): + request = web_security_scanner.GetScanConfigRequest(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_scan_config] + + # Certain fields should be provided within 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_scan_configs(self, + request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsAsyncPager: + r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1 + + async def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListScanConfigsRequest( + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest, dict]]): + The request object. Request for the ``ListScanConfigs`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: + Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): + request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] + + # Certain fields should be provided within 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.ListScanConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_scan_config(self, + request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.UpdateScanConfigRequest( + ) + + # Make the request + response = await client.update_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest, dict]]): + The request object. Request for the ``UpdateScanConfigRequest`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # 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, web_security_scanner.UpdateScanConfigRequest): + request = web_security_scanner.UpdateScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_scan_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.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 start_scan_run(self, + request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.StartScanRunRequest( + ) + + # Make the request + response = await client.start_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.StartScanRunRequest, dict]]): + The request object. Request for the ``StartScanRun`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # 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, web_security_scanner.StartScanRunRequest): + request = web_security_scanner.StartScanRunRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.start_scan_run] + + # Certain fields should be provided within 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_scan_run(self, + request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetScanRunRequest( + ) + + # Make the request + response = await client.get_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.GetScanRunRequest, dict]]): + The request object. Request for the ``GetScanRun`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # 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, web_security_scanner.GetScanRunRequest): + request = web_security_scanner.GetScanRunRequest(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_scan_run] + + # Certain fields should be provided within 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_scan_runs(self, + request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsAsyncPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListScanRunsRequest( + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListScanRunsRequest, dict]]): + The request object. Request for the ``ListScanRuns`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsAsyncPager: + Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): + request = web_security_scanner.ListScanRunsRequest(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_scan_runs] + + # Certain fields should be provided within 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.ListScanRunsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def stop_scan_run(self, + request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.StopScanRunRequest( + ) + + # Make the request + response = await client.stop_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.StopScanRunRequest, dict]]): + The request object. Request for the ``StopScanRun`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # 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, web_security_scanner.StopScanRunRequest): + request = web_security_scanner.StopScanRunRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.stop_scan_run] + + # Certain fields should be provided within 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_crawled_urls(self, + request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsAsyncPager: + r"""List CrawledUrls under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListCrawledUrlsRequest( + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest, dict]]): + The request object. Request for the ``ListCrawledUrls`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: + Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] + + # Certain fields should be provided within 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.ListCrawledUrlsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_finding(self, + request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_get_finding(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetFindingRequest( + ) + + # Make the request + response = await client.get_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.GetFindingRequest, dict]]): + The request object. Request for the ``GetFinding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # 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, web_security_scanner.GetFindingRequest): + request = web_security_scanner.GetFindingRequest(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_finding] + + # Certain fields should be provided within 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_findings(self, + request: Optional[Union[web_security_scanner.ListFindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""List Findings under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_list_findings(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListFindingsRequest( + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListFindingsRequest, dict]]): + The request object. Request for the ``ListFindings`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsAsyncPager: + Response for the ListFindings 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, web_security_scanner.ListFindingsRequest): + request = web_security_scanner.ListFindingsRequest(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_findings] + + # Certain fields should be provided within 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.ListFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_finding_type_stats(self, + request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + async def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListFindingTypeStatsRequest( + ) + + # Make the request + response = await client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest, dict]]): + The request object. Request for the ``ListFindingTypeStats`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats method. + """ + # 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, web_security_scanner.ListFindingTypeStatsRequest): + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] + + # Certain fields should be provided within 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) -> "WebSecurityScannerAsyncClient": + 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__ = ( + "WebSecurityScannerAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py new file mode 100644 index 000000000000..001f1d5c2c43 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py @@ -0,0 +1,1710 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.websecurityscanner_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 + +from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import finding_addon +from google.cloud.websecurityscanner_v1.types import finding_type_stats +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WebSecurityScannerGrpcTransport +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .transports.rest import WebSecurityScannerRestTransport + + +class WebSecurityScannerClientMeta(type): + """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] + _transport_registry["grpc"] = WebSecurityScannerGrpcTransport + _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport + _transport_registry["rest"] = WebSecurityScannerRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WebSecurityScannerTransport]: + """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 WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): + """Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + """ + + @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 = "websecurityscanner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "websecurityscanner.{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: + WebSecurityScannerClient: 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: + WebSecurityScannerClient: 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) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?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 = WebSecurityScannerClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WebSecurityScannerClient._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 = WebSecurityScannerClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + WebSecurityScannerClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): + 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 WebSecurityScannerTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WebSecurityScannerClient._read_environment_variables() + self._client_cert_source = WebSecurityScannerClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = WebSecurityScannerClient._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 + + 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, WebSecurityScannerTransport) + if transport_provided: + # transport is a WebSecurityScannerTransport 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(WebSecurityScannerTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + WebSecurityScannerClient._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[WebSecurityScannerTransport], Callable[..., WebSecurityScannerTransport]] = ( + WebSecurityScannerClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WebSecurityScannerTransport], 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, + ) + + def create_scan_config(self, + request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.CreateScanConfigRequest( + ) + + # Make the request + response = client.create_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest, dict]): + The request object. Request for the ``CreateScanConfig`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # 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, web_security_scanner.CreateScanConfigRequest): + request = web_security_scanner.CreateScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_scan_config] + + # Certain fields should be provided within 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_scan_config(self, + request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.DeleteScanConfigRequest( + ) + + # Make the request + client.delete_scan_config(request=request) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest, dict]): + The request object. Request for the ``DeleteScanConfig`` method. + retry (google.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. + """ + # 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, web_security_scanner.DeleteScanConfigRequest): + request = web_security_scanner.DeleteScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_scan_config] + + # Certain fields should be provided within 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 get_scan_config(self, + request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetScanConfigRequest( + ) + + # Make the request + response = client.get_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.GetScanConfigRequest, dict]): + The request object. Request for the ``GetScanConfig`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # 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, web_security_scanner.GetScanConfigRequest): + request = web_security_scanner.GetScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_scan_config] + + # Certain fields should be provided within 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_scan_configs(self, + request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsPager: + r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1 + + def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListScanConfigsRequest( + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest, dict]): + The request object. Request for the ``ListScanConfigs`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsPager: + Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): + request = web_security_scanner.ListScanConfigsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_scan_configs] + + # Certain fields should be provided within 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.ListScanConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_scan_config(self, + request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.UpdateScanConfigRequest( + ) + + # Make the request + response = client.update_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest, dict]): + The request object. Request for the ``UpdateScanConfigRequest`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # 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, web_security_scanner.UpdateScanConfigRequest): + request = web_security_scanner.UpdateScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_scan_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.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 start_scan_run(self, + request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.StartScanRunRequest( + ) + + # Make the request + response = client.start_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.StartScanRunRequest, dict]): + The request object. Request for the ``StartScanRun`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # 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, web_security_scanner.StartScanRunRequest): + request = web_security_scanner.StartScanRunRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.start_scan_run] + + # Certain fields should be provided within 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_scan_run(self, + request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetScanRunRequest( + ) + + # Make the request + response = client.get_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.GetScanRunRequest, dict]): + The request object. Request for the ``GetScanRun`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # 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, web_security_scanner.GetScanRunRequest): + request = web_security_scanner.GetScanRunRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_scan_run] + + # Certain fields should be provided within 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_scan_runs(self, + request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListScanRunsRequest( + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListScanRunsRequest, dict]): + The request object. Request for the ``ListScanRuns`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsPager: + Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): + request = web_security_scanner.ListScanRunsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_scan_runs] + + # Certain fields should be provided within 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.ListScanRunsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stop_scan_run(self, + request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.StopScanRunRequest( + ) + + # Make the request + response = client.stop_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.StopScanRunRequest, dict]): + The request object. Request for the ``StopScanRun`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # 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, web_security_scanner.StopScanRunRequest): + request = web_security_scanner.StopScanRunRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stop_scan_run] + + # Certain fields should be provided within 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_crawled_urls(self, + request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsPager: + r"""List CrawledUrls under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListCrawledUrlsRequest( + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest, dict]): + The request object. Request for the ``ListCrawledUrls`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsPager: + Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): + request = web_security_scanner.ListCrawledUrlsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_crawled_urls] + + # Certain fields should be provided within 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.ListCrawledUrlsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_finding(self, + request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_get_finding(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetFindingRequest( + ) + + # Make the request + response = client.get_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.GetFindingRequest, dict]): + The request object. Request for the ``GetFinding`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # 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, web_security_scanner.GetFindingRequest): + request = web_security_scanner.GetFindingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_finding] + + # Certain fields should be provided within 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_findings(self, + request: Optional[Union[web_security_scanner.ListFindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""List Findings under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_list_findings(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListFindingsRequest( + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListFindingsRequest, dict]): + The request object. Request for the ``ListFindings`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsPager: + Response for the ListFindings 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, web_security_scanner.ListFindingsRequest): + request = web_security_scanner.ListFindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_findings] + + # Certain fields should be provided within 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.ListFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_finding_type_stats(self, + request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1 + + def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListFindingTypeStatsRequest( + ) + + # Make the request + response = client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest, dict]): + The request object. Request for the ``ListFindingTypeStats`` method. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats method. + """ + # 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, web_security_scanner.ListFindingTypeStatsRequest): + request = web_security_scanner.ListFindingTypeStatsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_finding_type_stats] + + # Certain fields should be provided within 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) -> "WebSecurityScannerClient": + 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__ = ( + "WebSecurityScannerClient", +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py new file mode 100644 index 000000000000..1f2e9022259c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py @@ -0,0 +1,571 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner + + +class ListScanConfigsPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListScanConfigsResponse], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + for page in self.pages: + yield from page.scan_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanConfigsAsyncPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` + attributes are available on the 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[web_security_scanner.ListScanConfigsResponse]], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListScanRunsResponse], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListScanRunsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + for page in self.pages: + yield from page.scan_runs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsAsyncPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` + attributes are available on the 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[web_security_scanner.ListScanRunsResponse]], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListScanRunsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_runs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListCrawledUrlsResponse], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + for page in self.pages: + yield from page.crawled_urls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsAsyncPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` + attributes are available on the 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[web_security_scanner.ListCrawledUrlsResponse]], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + async def async_generator(): + async for page in self.pages: + for response in page.crawled_urls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListFindingsResponse], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListFindingsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: + 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[finding.Finding]: + for page in self.pages: + yield from page.findings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` + attributes are available on the 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[web_security_scanner.ListFindingsResponse]], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListFindingsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: + 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[finding.Finding]: + async def async_generator(): + async for page in self.pages: + for response in page.findings: + 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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/README.rst new file mode 100644 index 000000000000..3479ee767648 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`WebSecurityScannerTransport` is the ABC for all transports. +- public child `WebSecurityScannerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `WebSecurityScannerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseWebSecurityScannerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `WebSecurityScannerRestTransport` 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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py new file mode 100644 index 000000000000..e24819a4ee07 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/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 WebSecurityScannerTransport +from .grpc import WebSecurityScannerGrpcTransport +from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .rest import WebSecurityScannerRestTransport +from .rest import WebSecurityScannerRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] +_transport_registry['grpc'] = WebSecurityScannerGrpcTransport +_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport +_transport_registry['rest'] = WebSecurityScannerRestTransport + +__all__ = ( + 'WebSecurityScannerTransport', + 'WebSecurityScannerGrpcTransport', + 'WebSecurityScannerGrpcAsyncIOTransport', + 'WebSecurityScannerRestTransport', + 'WebSecurityScannerRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py new file mode 100644 index 000000000000..9e3ddff0edf5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/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 google.cloud.websecurityscanner_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.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WebSecurityScannerTransport(abc.ABC): + """Abstract transport class for WebSecurityScanner.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_scan_config: gapic_v1.method.wrap_method( + self.create_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.delete_scan_config: gapic_v1.method.wrap_method( + self.delete_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_config: gapic_v1.method.wrap_method( + self.get_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_configs: gapic_v1.method.wrap_method( + self.list_scan_configs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_scan_config: gapic_v1.method.wrap_method( + self.update_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.start_scan_run: gapic_v1.method.wrap_method( + self.start_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_run: gapic_v1.method.wrap_method( + self.get_scan_run, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_runs: gapic_v1.method.wrap_method( + self.list_scan_runs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.stop_scan_run: gapic_v1.method.wrap_method( + self.stop_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.list_crawled_urls: gapic_v1.method.wrap_method( + self.list_crawled_urls, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_finding: gapic_v1.method.wrap_method( + self.get_finding, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_finding_type_stats: gapic_v1.method.wrap_method( + self.list_finding_type_stats, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Union[ + web_security_scanner.ListScanConfigsResponse, + Awaitable[web_security_scanner.ListScanConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Union[ + web_security_scanner.ListScanRunsResponse, + Awaitable[web_security_scanner.ListScanRunsResponse] + ]]: + raise NotImplementedError() + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Union[ + web_security_scanner.ListCrawledUrlsResponse, + Awaitable[web_security_scanner.ListCrawledUrlsResponse] + ]]: + raise NotImplementedError() + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Union[ + web_security_scanner.ListFindingsResponse, + Awaitable[web_security_scanner.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Union[ + web_security_scanner.ListFindingTypeStatsResponse, + Awaitable[web_security_scanner.ListFindingTypeStatsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WebSecurityScannerTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py new file mode 100644 index 000000000000..65a71b7c972b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO + + +class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): + """gRPC backend transport for WebSecurityScanner. + + Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'websecurityscanner.googleapis.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_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + ~.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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + ~.ListScanConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + ~.ListScanRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + ~.ListCrawledUrlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + finding.Finding]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + ~.ListFindingTypeStatsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WebSecurityScannerGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py new file mode 100644 index 000000000000..fecf2a018924 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py @@ -0,0 +1,763 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .grpc import WebSecurityScannerGrpcTransport + + +class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): + """gRPC AsyncIO backend transport for WebSecurityScanner. + + Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'websecurityscanner.googleapis.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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + 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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Awaitable[web_security_scanner.ListScanConfigsResponse]]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + Awaitable[~.ListScanConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Awaitable[web_security_scanner.ListScanRunsResponse]]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + Awaitable[~.ListScanRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + Awaitable[~.ListCrawledUrlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Awaitable[web_security_scanner.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + Awaitable[~.ListFindingTypeStatsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + 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_scan_config: self._wrap_method( + self.create_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.delete_scan_config: self._wrap_method( + self.delete_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_config: self._wrap_method( + self.get_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_configs: self._wrap_method( + self.list_scan_configs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_scan_config: self._wrap_method( + self.update_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.start_scan_run: self._wrap_method( + self.start_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_run: self._wrap_method( + self.get_scan_run, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_runs: self._wrap_method( + self.list_scan_runs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.stop_scan_run: self._wrap_method( + self.stop_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.list_crawled_urls: self._wrap_method( + self.list_crawled_urls, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_finding: self._wrap_method( + self.get_finding, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_findings: self._wrap_method( + self.list_findings, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_finding_type_stats: self._wrap_method( + self.list_finding_type_stats, + 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=600.0, + ), + default_timeout=600.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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'WebSecurityScannerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py new file mode 100644 index 000000000000..1a84eb8b4067 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py @@ -0,0 +1,1532 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + + +from .rest_base import _BaseWebSecurityScannerRestTransport +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 + + +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 WebSecurityScannerRestInterceptor: + """Interceptor for WebSecurityScanner. + + 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 WebSecurityScannerRestTransport. + + .. code-block:: python + class MyCustomWebSecurityScannerInterceptor(WebSecurityScannerRestInterceptor): + def pre_create_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crawled_urls(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crawled_urls(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_finding_type_stats(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_finding_type_stats(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_runs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_runs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WebSecurityScannerRestTransport(interceptor=MyCustomWebSecurityScannerInterceptor()) + client = WebSecurityScannerClient(transport=transport) + + + """ + def pre_create_scan_config(self, request: web_security_scanner.CreateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.CreateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_create_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: + """Post-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_delete_scan_config(self, request: web_security_scanner.DeleteScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.DeleteScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def pre_get_finding(self, request: web_security_scanner.GetFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_finding(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for get_finding + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_config(self, request: web_security_scanner.GetScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: + """Post-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_run(self, request: web_security_scanner.GetScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_crawled_urls(self, request: web_security_scanner.ListCrawledUrlsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListCrawledUrlsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_crawled_urls(self, response: web_security_scanner.ListCrawledUrlsResponse) -> web_security_scanner.ListCrawledUrlsResponse: + """Post-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_findings(self, request: web_security_scanner.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_findings(self, response: web_security_scanner.ListFindingsResponse) -> web_security_scanner.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_finding_type_stats(self, request: web_security_scanner.ListFindingTypeStatsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingTypeStatsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_finding_type_stats(self, response: web_security_scanner.ListFindingTypeStatsResponse) -> web_security_scanner.ListFindingTypeStatsResponse: + """Post-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_configs(self, request: web_security_scanner.ListScanConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_configs(self, response: web_security_scanner.ListScanConfigsResponse) -> web_security_scanner.ListScanConfigsResponse: + """Post-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_runs(self, request: web_security_scanner.ListScanRunsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanRunsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_runs(self, response: web_security_scanner.ListScanRunsResponse) -> web_security_scanner.ListScanRunsResponse: + """Post-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_start_scan_run(self, request: web_security_scanner.StartScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StartScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_start_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_stop_scan_run(self, request: web_security_scanner.StopScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StopScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_stop_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_update_scan_config(self, request: web_security_scanner.UpdateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.UpdateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_update_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: + """Post-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WebSecurityScannerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WebSecurityScannerRestInterceptor + + +class WebSecurityScannerRestTransport(_BaseWebSecurityScannerRestTransport): + """REST backend synchronous transport for WebSecurityScanner. + + Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'websecurityscanner.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[WebSecurityScannerRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 WebSecurityScannerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateScanConfig(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.CreateScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.CreateScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_config.ScanConfig: + r"""Call the create scan config method over HTTP. + + Args: + request (~.web_security_scanner.CreateScanConfigRequest): + The request object. Request for the ``CreateScanConfig`` method. + retry (google.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. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_http_options() + request, metadata = self._interceptor.pre_create_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._CreateScanConfig._get_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 = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_scan_config(resp) + return resp + + class _DeleteScanConfig(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.DeleteScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.DeleteScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete scan config method over HTTP. + + Args: + request (~.web_security_scanner.DeleteScanConfigRequest): + The request object. Request for the ``DeleteScanConfig`` method. + retry (google.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. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_http_options() + request, metadata = self._interceptor.pre_delete_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._DeleteScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 _GetFinding(_BaseWebSecurityScannerRestTransport._BaseGetFinding, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.GetFinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.GetFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the get finding method over HTTP. + + Args: + request (~.web_security_scanner.GetFindingRequest): + The request object. Request for the ``GetFinding`` method. + retry (google.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. + + Returns: + ~.finding.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_http_options() + request, metadata = self._interceptor.pre_get_finding(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._GetFinding._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = finding.Finding() + pb_resp = finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_finding(resp) + return resp + + class _GetScanConfig(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.GetScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.GetScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_config.ScanConfig: + r"""Call the get scan config method over HTTP. + + Args: + request (~.web_security_scanner.GetScanConfigRequest): + The request object. Request for the ``GetScanConfig`` method. + retry (google.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. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_http_options() + request, metadata = self._interceptor.pre_get_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._GetScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_config(resp) + return resp + + class _GetScanRun(_BaseWebSecurityScannerRestTransport._BaseGetScanRun, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.GetScanRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.GetScanRunRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_run.ScanRun: + r"""Call the get scan run method over HTTP. + + Args: + request (~.web_security_scanner.GetScanRunRequest): + The request object. Request for the ``GetScanRun`` method. + retry (google.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. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_http_options() + request, metadata = self._interceptor.pre_get_scan_run(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._GetScanRun._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_run(resp) + return resp + + class _ListCrawledUrls(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListCrawledUrls") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListCrawledUrlsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListCrawledUrlsResponse: + r"""Call the list crawled urls method over HTTP. + + Args: + request (~.web_security_scanner.ListCrawledUrlsRequest): + The request object. Request for the ``ListCrawledUrls`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListCrawledUrlsResponse: + Response for the ``ListCrawledUrls`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_http_options() + request, metadata = self._interceptor.pre_list_crawled_urls(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListCrawledUrls._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListCrawledUrlsResponse() + pb_resp = web_security_scanner.ListCrawledUrlsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crawled_urls(resp) + return resp + + class _ListFindings(_BaseWebSecurityScannerRestTransport._BaseListFindings, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListFindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingsRequest): + The request object. Request for the ``ListFindings`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListFindingsResponse: + Response for the ``ListFindings`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_http_options() + request, metadata = self._interceptor.pre_list_findings(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListFindings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListFindingsResponse() + pb_resp = web_security_scanner.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListFindingTypeStats(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListFindingTypeStats") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListFindingTypeStatsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""Call the list finding type stats method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingTypeStatsRequest): + The request object. Request for the ``ListFindingTypeStats`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListFindingTypeStatsResponse: + Response for the ``ListFindingTypeStats`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_http_options() + request, metadata = self._interceptor.pre_list_finding_type_stats(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListFindingTypeStats._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListFindingTypeStatsResponse() + pb_resp = web_security_scanner.ListFindingTypeStatsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_finding_type_stats(resp) + return resp + + class _ListScanConfigs(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListScanConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListScanConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListScanConfigsResponse: + r"""Call the list scan configs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanConfigsRequest): + The request object. Request for the ``ListScanConfigs`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListScanConfigsResponse: + Response for the ``ListScanConfigs`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_http_options() + request, metadata = self._interceptor.pre_list_scan_configs(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListScanConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListScanConfigsResponse() + pb_resp = web_security_scanner.ListScanConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_configs(resp) + return resp + + class _ListScanRuns(_BaseWebSecurityScannerRestTransport._BaseListScanRuns, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListScanRuns") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListScanRunsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListScanRunsResponse: + r"""Call the list scan runs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanRunsRequest): + The request object. Request for the ``ListScanRuns`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListScanRunsResponse: + Response for the ``ListScanRuns`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_http_options() + request, metadata = self._interceptor.pre_list_scan_runs(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListScanRuns._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListScanRunsResponse() + pb_resp = web_security_scanner.ListScanRunsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_runs(resp) + return resp + + class _StartScanRun(_BaseWebSecurityScannerRestTransport._BaseStartScanRun, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.StartScanRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.StartScanRunRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_run.ScanRun: + r"""Call the start scan run method over HTTP. + + Args: + request (~.web_security_scanner.StartScanRunRequest): + The request object. Request for the ``StartScanRun`` method. + retry (google.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. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_http_options() + request, metadata = self._interceptor.pre_start_scan_run(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._StartScanRun._get_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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_start_scan_run(resp) + return resp + + class _StopScanRun(_BaseWebSecurityScannerRestTransport._BaseStopScanRun, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.StopScanRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.StopScanRunRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_run.ScanRun: + r"""Call the stop scan run method over HTTP. + + Args: + request (~.web_security_scanner.StopScanRunRequest): + The request object. Request for the ``StopScanRun`` method. + retry (google.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. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_http_options() + request, metadata = self._interceptor.pre_stop_scan_run(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._StopScanRun._get_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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_stop_scan_run(resp) + return resp + + class _UpdateScanConfig(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.UpdateScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.UpdateScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_config.ScanConfig: + r"""Call the update scan config method over HTTP. + + Args: + request (~.web_security_scanner.UpdateScanConfigRequest): + The request object. Request for the ``UpdateScanConfigRequest`` method. + retry (google.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. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_http_options() + request, metadata = self._interceptor.pre_update_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._UpdateScanConfig._get_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 = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_scan_config(resp) + return resp + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + scan_config.ScanConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + 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._DeleteScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + finding.Finding]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + scan_config.ScanConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + scan_run.ScanRun]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCrawledUrls(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFindingTypeStats(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScanConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScanRuns(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + scan_run.ScanRun]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StartScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + scan_run.ScanRun]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StopScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + scan_config.ScanConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WebSecurityScannerRestTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest_base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest_base.py new file mode 100644 index 000000000000..88b128878474 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest_base.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 WebSecurityScannerTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + + +class _BaseWebSecurityScannerRestTransport(WebSecurityScannerTransport): + """Base REST backend transport for WebSecurityScanner. + + 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 = 'websecurityscanner.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: 'websecurityscanner.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 _BaseCreateScanConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/scanConfigs', + 'body': 'scan_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.CreateScanConfigRequest.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["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteScanConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/scanConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.DeleteScanConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _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 _BaseGetFinding: + 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/*/scanConfigs/*/scanRuns/*/findings/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.GetFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _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 _BaseGetScanConfig: + 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/*/scanConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.GetScanConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _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 _BaseGetScanRun: + 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/*/scanConfigs/*/scanRuns/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.GetScanRunRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _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 _BaseListCrawledUrls: + 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/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListCrawledUrlsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _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 _BaseListFindings: + 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/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _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 _BaseListFindingTypeStats: + 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/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListFindingTypeStatsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _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 _BaseListScanConfigs: + 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/{parent=projects/*}/scanConfigs', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListScanConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _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 _BaseListScanRuns: + 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/{parent=projects/*/scanConfigs/*}/scanRuns', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListScanRunsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _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 _BaseStartScanRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/scanConfigs/*}:start', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.StartScanRunRequest.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["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStopScanRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/scanConfigs/*/scanRuns/*}:stop', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.StopScanRunRequest.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["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateScanConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{scan_config.name=projects/*/scanConfigs/*}', + 'body': 'scan_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.UpdateScanConfigRequest.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["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseWebSecurityScannerRestTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/__init__.py new file mode 100644 index 000000000000..cc33ca771c3b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_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 .crawled_url import ( + CrawledUrl, +) +from .finding import ( + Finding, +) +from .finding_addon import ( + Form, + OutdatedLibrary, + ViolatingResource, + VulnerableHeaders, + VulnerableParameters, + Xss, + Xxe, +) +from .finding_type_stats import ( + FindingTypeStats, +) +from .scan_config import ( + ScanConfig, +) +from .scan_config_error import ( + ScanConfigError, +) +from .scan_run import ( + ScanRun, +) +from .scan_run_error_trace import ( + ScanRunErrorTrace, +) +from .scan_run_log import ( + ScanRunLog, +) +from .scan_run_warning_trace import ( + ScanRunWarningTrace, +) +from .web_security_scanner import ( + CreateScanConfigRequest, + DeleteScanConfigRequest, + GetFindingRequest, + GetScanConfigRequest, + GetScanRunRequest, + ListCrawledUrlsRequest, + ListCrawledUrlsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListFindingTypeStatsRequest, + ListFindingTypeStatsResponse, + ListScanConfigsRequest, + ListScanConfigsResponse, + ListScanRunsRequest, + ListScanRunsResponse, + StartScanRunRequest, + StopScanRunRequest, + UpdateScanConfigRequest, +) + +__all__ = ( + 'CrawledUrl', + 'Finding', + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'Xxe', + 'FindingTypeStats', + 'ScanConfig', + 'ScanConfigError', + 'ScanRun', + 'ScanRunErrorTrace', + 'ScanRunLog', + 'ScanRunWarningTrace', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py new file mode 100644 index 000000000000..422126dfc89d --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/crawled_url.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.cloud.websecurityscanner.v1', + manifest={ + 'CrawledUrl', + }, +) + + +class CrawledUrl(proto.Message): + r"""A CrawledUrl resource represents a URL that was crawled + during a ScanRun. Web Security Scanner Service crawls the web + applications, following all links within the scope of sites, to + find the URLs to test against. + + Attributes: + http_method (str): + Output only. The http method of the request + that was used to visit the URL, in uppercase. + url (str): + Output only. The URL that was crawled. + body (str): + Output only. The body of the request that was + used to visit the URL. + """ + + http_method: str = proto.Field( + proto.STRING, + number=1, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + body: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding.py new file mode 100644 index 000000000000..e40e0b8f7e7b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding.py @@ -0,0 +1,209 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner_v1.types import finding_addon + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""A Finding resource represents a vulnerability instance + identified during a ScanRun. + + Attributes: + name (str): + Output only. The resource name of the + Finding. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. + The finding IDs are generated by the system. + finding_type (str): + Output only. The type of the Finding. + Detailed and up-to-date information on findings + can be found here: + + https://cloud.google.com/security-command-center/docs/how-to-remediate-web-security-scanner-findings + severity (google.cloud.websecurityscanner_v1.types.Finding.Severity): + Output only. The severity level of the + reported vulnerability. + http_method (str): + Output only. The http method of the request + that triggered the vulnerability, in uppercase. + fuzzed_url (str): + Output only. The URL produced by the + server-side fuzzer and used in the request that + triggered the vulnerability. + body (str): + Output only. The body of the request that + triggered the vulnerability. + description (str): + Output only. The description of the + vulnerability. + reproduction_url (str): + Output only. The URL containing + human-readable payload that user can leverage to + reproduce the vulnerability. + frame_url (str): + Output only. If the vulnerability was + originated from nested IFrame, the immediate + parent IFrame is reported. + final_url (str): + Output only. The URL where the browser lands + when the vulnerability is detected. + tracking_id (str): + Output only. The tracking ID uniquely + identifies a vulnerability instance across + multiple ScanRuns. + form (google.cloud.websecurityscanner_v1.types.Form): + Output only. An addon containing information + reported for a vulnerability with an HTML form, + if any. + outdated_library (google.cloud.websecurityscanner_v1.types.OutdatedLibrary): + Output only. An addon containing information + about outdated libraries. + violating_resource (google.cloud.websecurityscanner_v1.types.ViolatingResource): + Output only. An addon containing detailed + information regarding any resource causing the + vulnerability such as JavaScript sources, image, + audio files, etc. + vulnerable_headers (google.cloud.websecurityscanner_v1.types.VulnerableHeaders): + Output only. An addon containing information + about vulnerable or missing HTTP headers. + vulnerable_parameters (google.cloud.websecurityscanner_v1.types.VulnerableParameters): + Output only. An addon containing information + about request parameters which were found to be + vulnerable. + xss (google.cloud.websecurityscanner_v1.types.Xss): + Output only. An addon containing information + reported for an XSS, if any. + xxe (google.cloud.websecurityscanner_v1.types.Xxe): + Output only. An addon containing information + reported for an XXE, if any. + """ + class Severity(proto.Enum): + r"""The severity level of a vulnerability. + + Values: + SEVERITY_UNSPECIFIED (0): + No severity specified. The default value. + CRITICAL (1): + Critical severity. + HIGH (2): + High severity. + MEDIUM (3): + Medium severity. + LOW (4): + Low severity. + """ + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + finding_type: str = proto.Field( + proto.STRING, + number=2, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=17, + enum=Severity, + ) + http_method: str = proto.Field( + proto.STRING, + number=3, + ) + fuzzed_url: str = proto.Field( + proto.STRING, + number=4, + ) + body: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + reproduction_url: str = proto.Field( + proto.STRING, + number=7, + ) + frame_url: str = proto.Field( + proto.STRING, + number=8, + ) + final_url: str = proto.Field( + proto.STRING, + number=9, + ) + tracking_id: str = proto.Field( + proto.STRING, + number=10, + ) + form: finding_addon.Form = proto.Field( + proto.MESSAGE, + number=16, + message=finding_addon.Form, + ) + outdated_library: finding_addon.OutdatedLibrary = proto.Field( + proto.MESSAGE, + number=11, + message=finding_addon.OutdatedLibrary, + ) + violating_resource: finding_addon.ViolatingResource = proto.Field( + proto.MESSAGE, + number=12, + message=finding_addon.ViolatingResource, + ) + vulnerable_headers: finding_addon.VulnerableHeaders = proto.Field( + proto.MESSAGE, + number=15, + message=finding_addon.VulnerableHeaders, + ) + vulnerable_parameters: finding_addon.VulnerableParameters = proto.Field( + proto.MESSAGE, + number=13, + message=finding_addon.VulnerableParameters, + ) + xss: finding_addon.Xss = proto.Field( + proto.MESSAGE, + number=14, + message=finding_addon.Xss, + ) + xxe: finding_addon.Xxe = proto.Field( + proto.MESSAGE, + number=18, + message=finding_addon.Xxe, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py new file mode 100644 index 000000000000..f60af7eb4bc8 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner.v1', + manifest={ + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableParameters', + 'VulnerableHeaders', + 'Xss', + 'Xxe', + }, +) + + +class Form(proto.Message): + r"""! Information about a vulnerability with an HTML. + + Attributes: + action_uri (str): + ! The URI where to send the form when it's + submitted. + fields (MutableSequence[str]): + ! The names of form fields related to the + vulnerability. + """ + + action_uri: str = proto.Field( + proto.STRING, + number=1, + ) + fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class OutdatedLibrary(proto.Message): + r"""Information reported for an outdated library. + + Attributes: + library_name (str): + The name of the outdated library. + version (str): + The version number. + learn_more_urls (MutableSequence[str]): + URLs to learn more information about the + vulnerabilities in the library. + """ + + library_name: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + learn_more_urls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ViolatingResource(proto.Message): + r"""Information regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, etc. + + Attributes: + content_type (str): + The MIME type of this resource. + resource_url (str): + URL of this violating resource. + """ + + content_type: str = proto.Field( + proto.STRING, + number=1, + ) + resource_url: str = proto.Field( + proto.STRING, + number=2, + ) + + +class VulnerableParameters(proto.Message): + r"""Information about vulnerable request parameters. + + Attributes: + parameter_names (MutableSequence[str]): + The vulnerable parameter names. + """ + + parameter_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class VulnerableHeaders(proto.Message): + r"""Information about vulnerable or missing HTTP Headers. + + Attributes: + headers (MutableSequence[google.cloud.websecurityscanner_v1.types.VulnerableHeaders.Header]): + List of vulnerable headers. + missing_headers (MutableSequence[google.cloud.websecurityscanner_v1.types.VulnerableHeaders.Header]): + List of missing headers. + """ + + class Header(proto.Message): + r"""Describes a HTTP Header. + + Attributes: + name (str): + Header name. + value (str): + Header value. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + headers: MutableSequence[Header] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Header, + ) + missing_headers: MutableSequence[Header] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Header, + ) + + +class Xss(proto.Message): + r"""Information reported for an XSS. + + Attributes: + stack_traces (MutableSequence[str]): + Stack traces leading to the point where the + XSS occurred. + error_message (str): + An error message generated by a javascript + breakage. + attack_vector (google.cloud.websecurityscanner_v1.types.Xss.AttackVector): + The attack vector of the payload triggering + this XSS. + stored_xss_seeding_url (str): + The reproduction url for the seeding POST + request of a Stored XSS. + """ + class AttackVector(proto.Enum): + r"""Types of XSS attack vector. + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + Unknown attack vector. + LOCAL_STORAGE (1): + The attack comes from fuzzing the browser's + localStorage. + SESSION_STORAGE (2): + The attack comes from fuzzing the browser's + sessionStorage. + WINDOW_NAME (3): + The attack comes from fuzzing the window's + name property. + REFERRER (4): + The attack comes from fuzzing the referrer + property. + FORM_INPUT (5): + The attack comes from fuzzing an input + element. + COOKIE (6): + The attack comes from fuzzing the browser's + cookies. + POST_MESSAGE (7): + The attack comes from hijacking the post + messaging mechanism. + GET_PARAMETERS (8): + The attack comes from fuzzing parameters in + the url. + URL_FRAGMENT (9): + The attack comes from fuzzing the fragment in + the url. + HTML_COMMENT (10): + The attack comes from fuzzing the HTML + comments. + POST_PARAMETERS (11): + The attack comes from fuzzing the POST + parameters. + PROTOCOL (12): + The attack comes from fuzzing the protocol. + STORED_XSS (13): + The attack comes from the server side and is + stored. + SAME_ORIGIN (14): + The attack is a Same-Origin Method Execution + attack via a GET parameter. + USER_CONTROLLABLE_URL (15): + The attack payload is received from a + third-party host via a URL that is + user-controllable + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + LOCAL_STORAGE = 1 + SESSION_STORAGE = 2 + WINDOW_NAME = 3 + REFERRER = 4 + FORM_INPUT = 5 + COOKIE = 6 + POST_MESSAGE = 7 + GET_PARAMETERS = 8 + URL_FRAGMENT = 9 + HTML_COMMENT = 10 + POST_PARAMETERS = 11 + PROTOCOL = 12 + STORED_XSS = 13 + SAME_ORIGIN = 14 + USER_CONTROLLABLE_URL = 15 + + stack_traces: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=3, + enum=AttackVector, + ) + stored_xss_seeding_url: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Xxe(proto.Message): + r"""Information reported for an XXE. + + Attributes: + payload_value (str): + The XML string that triggered the XXE + vulnerability. Non-payload values might be + redacted. + payload_location (google.cloud.websecurityscanner_v1.types.Xxe.Location): + Location within the request where the payload + was placed. + """ + class Location(proto.Enum): + r"""Locations within a request where XML was substituted. + + Values: + LOCATION_UNSPECIFIED (0): + Unknown Location. + COMPLETE_REQUEST_BODY (1): + The XML payload replaced the complete request + body. + """ + LOCATION_UNSPECIFIED = 0 + COMPLETE_REQUEST_BODY = 1 + + payload_value: str = proto.Field( + proto.STRING, + number=1, + ) + payload_location: Location = proto.Field( + proto.ENUM, + number=2, + enum=Location, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py new file mode 100644 index 000000000000..f78910e4e18b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'FindingTypeStats', + }, +) + + +class FindingTypeStats(proto.Message): + r"""A FindingTypeStats resource represents stats regarding a + specific FindingType of Findings under a given ScanRun. + + Attributes: + finding_type (str): + Output only. The finding type associated with + the stats. + finding_count (int): + Output only. The count of findings belonging + to this finding type. + """ + + finding_type: str = proto.Field( + proto.STRING, + number=1, + ) + finding_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config.py new file mode 100644 index 000000000000..fe4b7c4479dc --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config.py @@ -0,0 +1,361 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner.v1', + manifest={ + 'ScanConfig', + }, +) + + +class ScanConfig(proto.Message): + r"""A ScanConfig resource contains the configurations to launch a + scan. + + Attributes: + name (str): + The resource name of the ScanConfig. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + The ScanConfig IDs are generated by the system. + display_name (str): + Required. The user provided display name of + the ScanConfig. + max_qps (int): + The maximum QPS during scanning. A valid value ranges from 5 + to 20 inclusively. If the field is unspecified or its value + is set 0, server will default to 15. Other values outside of + [5, 20] range will be rejected with INVALID_ARGUMENT error. + starting_urls (MutableSequence[str]): + Required. The starting URLs from which the + scanner finds site pages. + authentication (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication): + The authentication configuration. If + specified, service will use the authentication + configuration during scanning. + user_agent (google.cloud.websecurityscanner_v1.types.ScanConfig.UserAgent): + The user agent used during scanning. + blacklist_patterns (MutableSequence[str]): + The excluded URL patterns as described in + https://cloud.google.com/security-command-center/docs/how-to-use-web-security-scanner#excluding_urls + schedule (google.cloud.websecurityscanner_v1.types.ScanConfig.Schedule): + The schedule of the ScanConfig. + export_to_security_command_center (google.cloud.websecurityscanner_v1.types.ScanConfig.ExportToSecurityCommandCenter): + Controls export of scan configurations and + results to Security Command Center. + risk_level (google.cloud.websecurityscanner_v1.types.ScanConfig.RiskLevel): + The risk level selected for the scan + managed_scan (bool): + Whether the scan config is managed by Web + Security Scanner, output only. + static_ip_scan (bool): + Whether the scan configuration has enabled + static IP address scan feature. If enabled, the + scanner will access applications from static IP + addresses. + ignore_http_status_errors (bool): + Whether to keep scanning even if most + requests return HTTP error codes. + """ + class UserAgent(proto.Enum): + r"""Type of user agents used for scanning. + + Values: + USER_AGENT_UNSPECIFIED (0): + The user agent is unknown. Service will default to + CHROME_LINUX. + CHROME_LINUX (1): + Chrome on Linux. This is the service default + if unspecified. + CHROME_ANDROID (2): + Chrome on Android. + SAFARI_IPHONE (3): + Safari on IPhone. + """ + USER_AGENT_UNSPECIFIED = 0 + CHROME_LINUX = 1 + CHROME_ANDROID = 2 + SAFARI_IPHONE = 3 + + class RiskLevel(proto.Enum): + r"""Scan risk levels supported by Web Security Scanner. LOW + impact scanning will minimize requests with the potential to + modify data. To achieve the maximum scan coverage, NORMAL risk + level is recommended. + + Values: + RISK_LEVEL_UNSPECIFIED (0): + Use default, which is NORMAL. + NORMAL (1): + Normal scanning (Recommended) + LOW (2): + Lower impact scanning + """ + RISK_LEVEL_UNSPECIFIED = 0 + NORMAL = 1 + LOW = 2 + + class ExportToSecurityCommandCenter(proto.Enum): + r"""Controls export of scan configurations and results to + Security Command Center. + + Values: + EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED (0): + Use default, which is ENABLED. + ENABLED (1): + Export results of this scan to Security + Command Center. + DISABLED (2): + Do not export results of this scan to + Security Command Center. + """ + EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + + class Authentication(proto.Message): + r"""Scan authentication configuration. + + 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_account (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.GoogleAccount): + Authentication using a Google account. + + This field is a member of `oneof`_ ``authentication``. + custom_account (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.CustomAccount): + Authentication using a custom account. + + This field is a member of `oneof`_ ``authentication``. + iap_credential (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.IapCredential): + Authentication using Identity-Aware-Proxy + (IAP). + + This field is a member of `oneof`_ ``authentication``. + """ + + class GoogleAccount(proto.Message): + r"""Describes authentication configuration that uses a Google + account. + + Attributes: + username (str): + Required. The user name of the Google + account. + password (str): + Required. Input only. The password of the + Google account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + """ + + username: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + + class CustomAccount(proto.Message): + r"""Describes authentication configuration that uses a custom + account. + + Attributes: + username (str): + Required. The user name of the custom + account. + password (str): + Required. Input only. The password of the + custom account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + login_url (str): + Required. The login form URL of the website. + """ + + username: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + login_url: str = proto.Field( + proto.STRING, + number=3, + ) + + class IapCredential(proto.Message): + r"""Describes authentication configuration for + Identity-Aware-Proxy (IAP). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + iap_test_service_account_info (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo): + Authentication configuration when + Web-Security-Scanner service account is added in + Identity-Aware-Proxy (IAP) access policies. + + This field is a member of `oneof`_ ``iap_credentials``. + """ + + class IapTestServiceAccountInfo(proto.Message): + r"""Describes authentication configuration when + Web-Security-Scanner service account is added in + Identity-Aware-Proxy (IAP) access policies. + + Attributes: + target_audience_client_id (str): + Required. Describes OAuth2 client id of + resources protected by Identity-Aware-Proxy + (IAP). + """ + + target_audience_client_id: str = proto.Field( + proto.STRING, + number=1, + ) + + iap_test_service_account_info: 'ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo' = proto.Field( + proto.MESSAGE, + number=1, + oneof='iap_credentials', + message='ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo', + ) + + google_account: 'ScanConfig.Authentication.GoogleAccount' = proto.Field( + proto.MESSAGE, + number=1, + oneof='authentication', + message='ScanConfig.Authentication.GoogleAccount', + ) + custom_account: 'ScanConfig.Authentication.CustomAccount' = proto.Field( + proto.MESSAGE, + number=2, + oneof='authentication', + message='ScanConfig.Authentication.CustomAccount', + ) + iap_credential: 'ScanConfig.Authentication.IapCredential' = proto.Field( + proto.MESSAGE, + number=4, + oneof='authentication', + message='ScanConfig.Authentication.IapCredential', + ) + + class Schedule(proto.Message): + r"""Scan schedule configuration. + + Attributes: + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + A timestamp indicates when the next run will + be scheduled. The value is refreshed by the + server after each run. If unspecified, it will + default to current server time, which means the + scan will be scheduled to start immediately. + interval_duration_days (int): + Required. The duration of time between + executions in days. + """ + + schedule_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + interval_duration_days: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + max_qps: int = proto.Field( + proto.INT32, + number=3, + ) + starting_urls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + authentication: Authentication = proto.Field( + proto.MESSAGE, + number=5, + message=Authentication, + ) + user_agent: UserAgent = proto.Field( + proto.ENUM, + number=6, + enum=UserAgent, + ) + blacklist_patterns: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + schedule: Schedule = proto.Field( + proto.MESSAGE, + number=8, + message=Schedule, + ) + export_to_security_command_center: ExportToSecurityCommandCenter = proto.Field( + proto.ENUM, + number=10, + enum=ExportToSecurityCommandCenter, + ) + risk_level: RiskLevel = proto.Field( + proto.ENUM, + number=12, + enum=RiskLevel, + ) + managed_scan: bool = proto.Field( + proto.BOOL, + number=13, + ) + static_ip_scan: bool = proto.Field( + proto.BOOL, + number=14, + ) + ignore_http_status_errors: bool = proto.Field( + proto.BOOL, + number=15, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py new file mode 100644 index 000000000000..3667d0f1c616 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner.v1', + manifest={ + 'ScanConfigError', + }, +) + + +class ScanConfigError(proto.Message): + r"""Defines a custom error message used by CreateScanConfig and + UpdateScanConfig APIs when scan configuration validation fails. + It is also reported as part of a ScanRunErrorTrace message if + scan validation fails due to a scan configuration error. + + Attributes: + code (google.cloud.websecurityscanner_v1.types.ScanConfigError.Code): + Output only. Indicates the reason code for a + configuration failure. + field_name (str): + Output only. Indicates the full name of the ScanConfig field + that triggers this error, for example "scan_config.max_qps". + This field is provided for troubleshooting purposes only and + its actual value can change in the future. + """ + class Code(proto.Enum): + r"""Output only. + Defines an error reason code. + Next id: 44 + + Values: + CODE_UNSPECIFIED (0): + There is no error. + OK (0): + There is no error. + INTERNAL_ERROR (1): + Indicates an internal server error. + Please DO NOT USE THIS ERROR CODE unless the + root cause is truly unknown. + APPENGINE_API_BACKEND_ERROR (2): + One of the seed URLs is an App Engine URL but + we cannot validate the scan settings due to an + App Engine API backend error. + APPENGINE_API_NOT_ACCESSIBLE (3): + One of the seed URLs is an App Engine URL but + we cannot access the App Engine API to validate + scan settings. + APPENGINE_DEFAULT_HOST_MISSING (4): + One of the seed URLs is an App Engine URL but + the Default Host of the App Engine is not set. + CANNOT_USE_GOOGLE_COM_ACCOUNT (6): + Google corporate accounts can not be used for + scanning. + CANNOT_USE_OWNER_ACCOUNT (7): + The account of the scan creator can not be + used for scanning. + COMPUTE_API_BACKEND_ERROR (8): + This scan targets Compute Engine, but we + cannot validate scan settings due to a Compute + Engine API backend error. + COMPUTE_API_NOT_ACCESSIBLE (9): + This scan targets Compute Engine, but we + cannot access the Compute Engine API to validate + the scan settings. + CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT (10): + The Custom Login URL does not belong to the + current project. + CUSTOM_LOGIN_URL_MALFORMED (11): + The Custom Login URL is malformed (can not be + parsed). + CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS (12): + The Custom Login URL is mapped to a + non-routable IP address in DNS. + CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS (13): + The Custom Login URL is mapped to an IP + address which is not reserved for the current + project. + CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS (14): + The Custom Login URL has a non-routable IP + address. + CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS (15): + The Custom Login URL has an IP address which + is not reserved for the current project. + DUPLICATE_SCAN_NAME (16): + Another scan with the same name + (case-sensitive) already exists. + INVALID_FIELD_VALUE (18): + A field is set to an invalid value. + FAILED_TO_AUTHENTICATE_TO_TARGET (19): + There was an error trying to authenticate to + the scan target. + FINDING_TYPE_UNSPECIFIED (20): + Finding type value is not specified in the + list findings request. + FORBIDDEN_TO_SCAN_COMPUTE (21): + Scan targets Compute Engine, yet current + project was not whitelisted for Google Compute + Engine Scanning Alpha access. + FORBIDDEN_UPDATE_TO_MANAGED_SCAN (43): + User tries to update managed scan + MALFORMED_FILTER (22): + The supplied filter is malformed. For + example, it can not be parsed, does not have a + filter type in expression, or the same filter + type appears more than once. + MALFORMED_RESOURCE_NAME (23): + The supplied resource name is malformed (can + not be parsed). + PROJECT_INACTIVE (24): + The current project is not in an active + state. + REQUIRED_FIELD (25): + A required field is not set. + RESOURCE_NAME_INCONSISTENT (26): + Project id, scanconfig id, scanrun id, or + finding id are not consistent with each other in + resource name. + SCAN_ALREADY_RUNNING (27): + The scan being requested to start is already + running. + SCAN_NOT_RUNNING (28): + The scan that was requested to be stopped is + not running. + SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT (29): + One of the seed URLs does not belong to the + current project. + SEED_URL_MALFORMED (30): + One of the seed URLs is malformed (can not be + parsed). + SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS (31): + One of the seed URLs is mapped to a + non-routable IP address in DNS. + SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS (32): + One of the seed URLs is mapped to an IP + address which is not reserved for the current + project. + SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS (33): + One of the seed URLs has on-routable IP + address. + SEED_URL_HAS_UNRESERVED_IP_ADDRESS (35): + One of the seed URLs has an IP address that + is not reserved for the current project. + SERVICE_ACCOUNT_NOT_CONFIGURED (36): + The Web Security Scanner service account is + not configured under the project. + TOO_MANY_SCANS (37): + A project has reached the maximum number of + scans. + UNABLE_TO_RESOLVE_PROJECT_INFO (38): + Resolving the details of the current project + fails. + UNSUPPORTED_BLACKLIST_PATTERN_FORMAT (39): + One or more blacklist patterns were in the + wrong format. + UNSUPPORTED_FILTER (40): + The supplied filter is not supported. + UNSUPPORTED_FINDING_TYPE (41): + The supplied finding type is not supported. + For example, we do not provide findings of the + given finding type. + UNSUPPORTED_URL_SCHEME (42): + The URL scheme of one or more of the supplied + URLs is not supported. + """ + _pb_options = {'allow_alias': True} + CODE_UNSPECIFIED = 0 + OK = 0 + INTERNAL_ERROR = 1 + APPENGINE_API_BACKEND_ERROR = 2 + APPENGINE_API_NOT_ACCESSIBLE = 3 + APPENGINE_DEFAULT_HOST_MISSING = 4 + CANNOT_USE_GOOGLE_COM_ACCOUNT = 6 + CANNOT_USE_OWNER_ACCOUNT = 7 + COMPUTE_API_BACKEND_ERROR = 8 + COMPUTE_API_NOT_ACCESSIBLE = 9 + CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 10 + CUSTOM_LOGIN_URL_MALFORMED = 11 + CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 12 + CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS = 13 + CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 14 + CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS = 15 + DUPLICATE_SCAN_NAME = 16 + INVALID_FIELD_VALUE = 18 + FAILED_TO_AUTHENTICATE_TO_TARGET = 19 + FINDING_TYPE_UNSPECIFIED = 20 + FORBIDDEN_TO_SCAN_COMPUTE = 21 + FORBIDDEN_UPDATE_TO_MANAGED_SCAN = 43 + MALFORMED_FILTER = 22 + MALFORMED_RESOURCE_NAME = 23 + PROJECT_INACTIVE = 24 + REQUIRED_FIELD = 25 + RESOURCE_NAME_INCONSISTENT = 26 + SCAN_ALREADY_RUNNING = 27 + SCAN_NOT_RUNNING = 28 + SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 29 + SEED_URL_MALFORMED = 30 + SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 31 + SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS = 32 + SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 33 + SEED_URL_HAS_UNRESERVED_IP_ADDRESS = 35 + SERVICE_ACCOUNT_NOT_CONFIGURED = 36 + TOO_MANY_SCANS = 37 + UNABLE_TO_RESOLVE_PROJECT_INFO = 38 + UNSUPPORTED_BLACKLIST_PATTERN_FORMAT = 39 + UNSUPPORTED_FILTER = 40 + UNSUPPORTED_FINDING_TYPE = 41 + UNSUPPORTED_URL_SCHEME = 42 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + field_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run.py new file mode 100644 index 000000000000..9b0aff3df801 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner_v1.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'ScanRun', + }, +) + + +class ScanRun(proto.Message): + r"""A ScanRun is a output-only resource representing an actual + run of the scan. Next id: 12 + + Attributes: + name (str): + Output only. The resource name of the + ScanRun. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + The ScanRun IDs are generated by the system. + execution_state (google.cloud.websecurityscanner_v1.types.ScanRun.ExecutionState): + Output only. The execution state of the + ScanRun. + result_state (google.cloud.websecurityscanner_v1.types.ScanRun.ResultState): + Output only. The result state of the ScanRun. + This field is only available after the execution + state reaches "FINISHED". + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the ScanRun + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the ScanRun + reached termination state - that the ScanRun is + either finished or stopped by user. + urls_crawled_count (int): + Output only. The number of URLs crawled + during this ScanRun. If the scan is in progress, + the value represents the number of URLs crawled + up to now. + urls_tested_count (int): + Output only. The number of URLs tested during + this ScanRun. If the scan is in progress, the + value represents the number of URLs tested up to + now. The number of URLs tested is usually larger + than the number URLS crawled because typically a + crawled URL is tested with multiple test + payloads. + has_vulnerabilities (bool): + Output only. Whether the scan run has found + any vulnerabilities. + progress_percent (int): + Output only. The percentage of total + completion ranging from 0 to 100. If the scan is + in queue, the value is 0. If the scan is + running, the value ranges from 0 to 100. If the + scan is finished, the value is 100. + error_trace (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace): + Output only. If result_state is an ERROR, this field + provides the primary reason for scan's termination and more + details, if such are available. + warning_traces (MutableSequence[google.cloud.websecurityscanner_v1.types.ScanRunWarningTrace]): + Output only. A list of warnings, if such are + encountered during this scan run. + """ + class ExecutionState(proto.Enum): + r"""Types of ScanRun execution state. + + Values: + EXECUTION_STATE_UNSPECIFIED (0): + Represents an invalid state caused by + internal server error. This value should never + be returned. + QUEUED (1): + The scan is waiting in the queue. + SCANNING (2): + The scan is in progress. + FINISHED (3): + The scan is either finished or stopped by + user. + """ + EXECUTION_STATE_UNSPECIFIED = 0 + QUEUED = 1 + SCANNING = 2 + FINISHED = 3 + + class ResultState(proto.Enum): + r"""Types of ScanRun result state. + + Values: + RESULT_STATE_UNSPECIFIED (0): + Default value. This value is returned when + the ScanRun is not yet finished. + SUCCESS (1): + The scan finished without errors. + ERROR (2): + The scan finished with errors. + KILLED (3): + The scan was terminated by user. + """ + RESULT_STATE_UNSPECIFIED = 0 + SUCCESS = 1 + ERROR = 2 + KILLED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + execution_state: ExecutionState = proto.Field( + proto.ENUM, + number=2, + enum=ExecutionState, + ) + result_state: ResultState = proto.Field( + proto.ENUM, + number=3, + enum=ResultState, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + urls_crawled_count: int = proto.Field( + proto.INT64, + number=6, + ) + urls_tested_count: int = proto.Field( + proto.INT64, + number=7, + ) + has_vulnerabilities: bool = proto.Field( + proto.BOOL, + number=8, + ) + progress_percent: int = proto.Field( + proto.INT32, + number=9, + ) + error_trace: scan_run_error_trace.ScanRunErrorTrace = proto.Field( + proto.MESSAGE, + number=10, + message=scan_run_error_trace.ScanRunErrorTrace, + ) + warning_traces: MutableSequence[scan_run_warning_trace.ScanRunWarningTrace] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=scan_run_warning_trace.ScanRunWarningTrace, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py new file mode 100644 index 000000000000..4b95f35270df --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner_v1.types import scan_config_error as gcw_scan_config_error + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'ScanRunErrorTrace', + }, +) + + +class ScanRunErrorTrace(proto.Message): + r"""Output only. + Defines an error trace message for a ScanRun. + + Attributes: + code (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace.Code): + Output only. Indicates the error reason code. + scan_config_error (google.cloud.websecurityscanner_v1.types.ScanConfigError): + Output only. If the scan encounters SCAN_CONFIG_ISSUE error, + this field has the error message encountered during scan + configuration validation that is performed before each scan + run. + most_common_http_error_code (int): + Output only. If the scan encounters TOO_MANY_HTTP_ERRORS, + this field indicates the most common HTTP error code, if + such is available. For example, if this code is 404, the + scan has encountered too many NOT_FOUND responses. + """ + class Code(proto.Enum): + r"""Output only. + Defines an error reason code. + Next id: 8 + + Values: + CODE_UNSPECIFIED (0): + Default value is never used. + INTERNAL_ERROR (1): + Indicates that the scan run failed due to an + internal server error. + SCAN_CONFIG_ISSUE (2): + Indicates a scan configuration error, usually due to + outdated ScanConfig settings, such as starting_urls or the + DNS configuration. + AUTHENTICATION_CONFIG_ISSUE (3): + Indicates an authentication error, usually + due to outdated ScanConfig authentication + settings. + TIMED_OUT_WHILE_SCANNING (4): + Indicates a scan operation timeout, usually + caused by a very large site. + TOO_MANY_REDIRECTS (5): + Indicates that a scan encountered excessive + redirects, either to authentication or some + other page outside of the scan scope. + TOO_MANY_HTTP_ERRORS (6): + Indicates that a scan encountered numerous errors from the + web site pages. When available, most_common_http_error_code + field indicates the most common HTTP error code encountered + during the scan. + """ + CODE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + SCAN_CONFIG_ISSUE = 2 + AUTHENTICATION_CONFIG_ISSUE = 3 + TIMED_OUT_WHILE_SCANNING = 4 + TOO_MANY_REDIRECTS = 5 + TOO_MANY_HTTP_ERRORS = 6 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + scan_config_error: gcw_scan_config_error.ScanConfigError = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config_error.ScanConfigError, + ) + most_common_http_error_code: int = proto.Field( + proto.INT32, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_log.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_log.py new file mode 100644 index 000000000000..d7a72ad4a6f9 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_log.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.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import scan_run_error_trace + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'ScanRunLog', + }, +) + + +class ScanRunLog(proto.Message): + r"""A ScanRunLog is an output-only proto used for Stackdriver + customer logging. It is used for logs covering the start and end + of scan pipelines. Other than an added summary, this is a subset + of the ScanRun. Representation in logs is either a proto Struct, + or converted to JSON. Next id: 9 + + Attributes: + summary (str): + Human friendly message about the event. + name (str): + The resource name of the ScanRun being + logged. + execution_state (google.cloud.websecurityscanner_v1.types.ScanRun.ExecutionState): + The execution state of the ScanRun. + result_state (google.cloud.websecurityscanner_v1.types.ScanRun.ResultState): + The result state of the ScanRun. + urls_crawled_count (int): + + urls_tested_count (int): + + has_findings (bool): + + error_trace (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace): + + """ + + summary: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + execution_state: scan_run.ScanRun.ExecutionState = proto.Field( + proto.ENUM, + number=3, + enum=scan_run.ScanRun.ExecutionState, + ) + result_state: scan_run.ScanRun.ResultState = proto.Field( + proto.ENUM, + number=4, + enum=scan_run.ScanRun.ResultState, + ) + urls_crawled_count: int = proto.Field( + proto.INT64, + number=5, + ) + urls_tested_count: int = proto.Field( + proto.INT64, + number=6, + ) + has_findings: bool = proto.Field( + proto.BOOL, + number=7, + ) + error_trace: scan_run_error_trace.ScanRunErrorTrace = proto.Field( + proto.MESSAGE, + number=8, + message=scan_run_error_trace.ScanRunErrorTrace, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py new file mode 100644 index 000000000000..18de95d60dd3 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'ScanRunWarningTrace', + }, +) + + +class ScanRunWarningTrace(proto.Message): + r"""Output only. + Defines a warning trace message for ScanRun. Warning traces + provide customers with useful information that helps make the + scanning process more effective. + + Attributes: + code (google.cloud.websecurityscanner_v1.types.ScanRunWarningTrace.Code): + Output only. Indicates the warning code. + """ + class Code(proto.Enum): + r"""Output only. + Defines a warning message code. + Next id: 6 + + Values: + CODE_UNSPECIFIED (0): + Default value is never used. + INSUFFICIENT_CRAWL_RESULTS (1): + Indicates that a scan discovered an + unexpectedly low number of URLs. This is + sometimes caused by complex navigation features + or by using a single URL for numerous pages. + TOO_MANY_CRAWL_RESULTS (2): + Indicates that a scan discovered too many + URLs to test, or excessive redundant URLs. + TOO_MANY_FUZZ_TASKS (3): + Indicates that too many tests have been + generated for the scan. Customer should try + reducing the number of starting URLs, increasing + the QPS rate, or narrowing down the scope of the + scan using the excluded patterns. + BLOCKED_BY_IAP (4): + Indicates that a scan is blocked by IAP. + NO_STARTING_URL_FOUND_FOR_MANAGED_SCAN (5): + Indicates that no seeds is found for a scan + """ + CODE_UNSPECIFIED = 0 + INSUFFICIENT_CRAWL_RESULTS = 1 + TOO_MANY_CRAWL_RESULTS = 2 + TOO_MANY_FUZZ_TASKS = 3 + BLOCKED_BY_IAP = 4 + NO_STARTING_URL_FOUND_FOR_MANAGED_SCAN = 5 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py new file mode 100644 index 000000000000..ebe221ec6b5f --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.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.cloud.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import finding_type_stats as gcw_finding_type_stats +from google.cloud.websecurityscanner_v1.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetScanConfigRequest', + 'ListScanConfigsRequest', + 'UpdateScanConfigRequest', + 'ListScanConfigsResponse', + 'StartScanRunRequest', + 'GetScanRunRequest', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StopScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'GetFindingRequest', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + }, +) + + +class CreateScanConfigRequest(proto.Message): + r"""Request for the ``CreateScanConfig`` method. + + Attributes: + parent (str): + Required. The parent resource name where the + scan is created, which should be a project + resource name in the format + 'projects/{projectId}'. + scan_config (google.cloud.websecurityscanner_v1.types.ScanConfig): + Required. The ScanConfig to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + scan_config: gcw_scan_config.ScanConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + + +class DeleteScanConfigRequest(proto.Message): + r"""Request for the ``DeleteScanConfig`` method. + + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be deleted. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanConfigRequest(proto.Message): + r"""Request for the ``GetScanConfig`` method. + + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanConfigsRequest(proto.Message): + r"""Request for the ``ListScanConfigs`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a project resource name in the format + 'projects/{projectId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanConfigs to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class UpdateScanConfigRequest(proto.Message): + r"""Request for the ``UpdateScanConfigRequest`` method. + + Attributes: + scan_config (google.cloud.websecurityscanner_v1.types.ScanConfig): + Required. The ScanConfig to be updated. The + name field must be set to identify the resource + to be updated. The values of fields not covered + by the mask will be ignored. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For the + ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + """ + + scan_config: gcw_scan_config.ScanConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ListScanConfigsResponse(proto.Message): + r"""Response for the ``ListScanConfigs`` method. + + Attributes: + scan_configs (MutableSequence[google.cloud.websecurityscanner_v1.types.ScanConfig]): + The list of ScanConfigs returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_configs: MutableSequence[gcw_scan_config.ScanConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_scan_config.ScanConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class StartScanRunRequest(proto.Message): + r"""Request for the ``StartScanRun`` method. + + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be used. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanRunRequest(proto.Message): + r"""Request for the ``GetScanRun`` method. + + Attributes: + name (str): + Required. The resource name of the ScanRun to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanRunsRequest(proto.Message): + r"""Request for the ``ListScanRuns`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanRuns to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListScanRunsResponse(proto.Message): + r"""Response for the ``ListScanRuns`` method. + + Attributes: + scan_runs (MutableSequence[google.cloud.websecurityscanner_v1.types.ScanRun]): + The list of ScanRuns returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_runs: MutableSequence[scan_run.ScanRun] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=scan_run.ScanRun, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class StopScanRunRequest(proto.Message): + r"""Request for the ``StopScanRun`` method. + + Attributes: + name (str): + Required. The resource name of the ScanRun to + be stopped. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCrawledUrlsRequest(proto.Message): + r"""Request for the ``ListCrawledUrls`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of CrawledUrls to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCrawledUrlsResponse(proto.Message): + r"""Response for the ``ListCrawledUrls`` method. + + Attributes: + crawled_urls (MutableSequence[google.cloud.websecurityscanner_v1.types.CrawledUrl]): + The list of CrawledUrls returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + crawled_urls: MutableSequence[crawled_url.CrawledUrl] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=crawled_url.CrawledUrl, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFindingRequest(proto.Message): + r"""Request for the ``GetFinding`` method. + + Attributes: + name (str): + Required. The resource name of the Finding to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request for the ``ListFindings`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + filter (str): + The filter expression. The expression must be in the format: + . Supported field: 'finding_type'. Supported operator: '='. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of Findings to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response for the ``ListFindings`` method. + + Attributes: + findings (MutableSequence[google.cloud.websecurityscanner_v1.types.Finding]): + The list of Findings returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + findings: MutableSequence[finding.Finding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=finding.Finding, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFindingTypeStatsRequest(proto.Message): + r"""Request for the ``ListFindingTypeStats`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingTypeStatsResponse(proto.Message): + r"""Response for the ``ListFindingTypeStats`` method. + + Attributes: + finding_type_stats (MutableSequence[google.cloud.websecurityscanner_v1.types.FindingTypeStats]): + The list of FindingTypeStats returned. + """ + + finding_type_stats: MutableSequence[gcw_finding_type_stats.FindingTypeStats] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_finding_type_stats.FindingTypeStats, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/mypy.ini b/owl-bot-staging/google-cloud-websecurityscanner/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/noxfile.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/noxfile.py new file mode 100644 index 000000000000..a68dcccfef3f --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner' + +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/cloud/websecurityscanner_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/cloud/websecurityscanner_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-cloud-websecurityscanner/v1/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json new file mode 100644 index 000000000000..030ea8082797 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json @@ -0,0 +1,1998 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.websecurityscanner.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-websecurityscanner", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.create_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.CreateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "CreateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", + "shortName": "create_scan_config" + }, + "description": "Sample for CreateScanConfig", + "file": "websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.create_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.CreateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "CreateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", + "shortName": "create_scan_config" + }, + "description": "Sample for CreateScanConfig", + "file": "websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.delete_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.DeleteScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "DeleteScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_scan_config" + }, + "description": "Sample for DeleteScanConfig", + "file": "websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.delete_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.DeleteScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "DeleteScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_scan_config" + }, + "description": "Sample for DeleteScanConfig", + "file": "websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.get_finding", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetFinding", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.GetFindingRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.Finding", + "shortName": "get_finding" + }, + "description": "Sample for GetFinding", + "file": "websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.get_finding", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetFinding", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.GetFindingRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.Finding", + "shortName": "get_finding" + }, + "description": "Sample for GetFinding", + "file": "websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.get_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.GetScanConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", + "shortName": "get_scan_config" + }, + "description": "Sample for GetScanConfig", + "file": "websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.get_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.GetScanConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", + "shortName": "get_scan_config" + }, + "description": "Sample for GetScanConfig", + "file": "websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.get_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.GetScanRunRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", + "shortName": "get_scan_run" + }, + "description": "Sample for GetScanRun", + "file": "websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.get_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.GetScanRunRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", + "shortName": "get_scan_run" + }, + "description": "Sample for GetScanRun", + "file": "websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_crawled_urls", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListCrawledUrls", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListCrawledUrls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager", + "shortName": "list_crawled_urls" + }, + "description": "Sample for ListCrawledUrls", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_crawled_urls", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListCrawledUrls", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListCrawledUrls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsPager", + "shortName": "list_crawled_urls" + }, + "description": "Sample for ListCrawledUrls", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_finding_type_stats", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListFindingTypeStats", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindingTypeStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse", + "shortName": "list_finding_type_stats" + }, + "description": "Sample for ListFindingTypeStats", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_finding_type_stats", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListFindingTypeStats", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindingTypeStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse", + "shortName": "list_finding_type_stats" + }, + "description": "Sample for ListFindingTypeStats", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListFindings", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListFindingsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_findings", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListFindings", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListFindingsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_scan_configs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListScanConfigs", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsAsyncPager", + "shortName": "list_scan_configs" + }, + "description": "Sample for ListScanConfigs", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_scan_configs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListScanConfigs", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsPager", + "shortName": "list_scan_configs" + }, + "description": "Sample for ListScanConfigs", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_scan_runs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListScanRuns", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListScanRunsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsAsyncPager", + "shortName": "list_scan_runs" + }, + "description": "Sample for ListScanRuns", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_scan_runs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListScanRuns", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.ListScanRunsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsPager", + "shortName": "list_scan_runs" + }, + "description": "Sample for ListScanRuns", + "file": "websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.start_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.StartScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StartScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.StartScanRunRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", + "shortName": "start_scan_run" + }, + "description": "Sample for StartScanRun", + "file": "websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.start_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.StartScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StartScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.StartScanRunRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", + "shortName": "start_scan_run" + }, + "description": "Sample for StartScanRun", + "file": "websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.stop_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.StopScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StopScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.StopScanRunRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", + "shortName": "stop_scan_run" + }, + "description": "Sample for StopScanRun", + "file": "websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.stop_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.StopScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StopScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.StopScanRunRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", + "shortName": "stop_scan_run" + }, + "description": "Sample for StopScanRun", + "file": "websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.update_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.UpdateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "UpdateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", + "shortName": "update_scan_config" + }, + "description": "Sample for UpdateScanConfig", + "file": "websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.update_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.UpdateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "UpdateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", + "shortName": "update_scan_config" + }, + "description": "Sample for UpdateScanConfig", + "file": "websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py new file mode 100644 index 000000000000..92e4d2fef54c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_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 CreateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.CreateScanConfigRequest( + ) + + # Make the request + response = await client.create_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py new file mode 100644 index 000000000000..b11d384eb0ce --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_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 CreateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.CreateScanConfigRequest( + ) + + # Make the request + response = client.create_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py new file mode 100644 index 000000000000..628a5f9ff1ba --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.DeleteScanConfigRequest( + ) + + # Make the request + await client.delete_scan_config(request=request) + + +# [END websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py new file mode 100644 index 000000000000..a234124ec93b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.DeleteScanConfigRequest( + ) + + # Make the request + client.delete_scan_config(request=request) + + +# [END websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py new file mode 100644 index 000000000000..94a5ab16ed40 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_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 GetFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_get_finding(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetFindingRequest( + ) + + # Make the request + response = await client.get_finding(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py new file mode 100644 index 000000000000..a48e371ca205 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_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 GetFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_get_finding(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetFindingRequest( + ) + + # Make the request + response = client.get_finding(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py new file mode 100644 index 000000000000..83ed87c87183 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_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 GetScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetScanConfigRequest( + ) + + # Make the request + response = await client.get_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py new file mode 100644 index 000000000000..c632fb367432 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_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 GetScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetScanConfigRequest( + ) + + # Make the request + response = client.get_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py new file mode 100644 index 000000000000..a9c9137dd3ea --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_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 GetScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetScanRunRequest( + ) + + # Make the request + response = await client.get_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py new file mode 100644 index 000000000000..53c1024650f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_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 GetScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.GetScanRunRequest( + ) + + # Make the request + response = client.get_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py new file mode 100644 index 000000000000..55e2566d061d --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListCrawledUrlsRequest( + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py new file mode 100644 index 000000000000..859e162a3114 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListCrawledUrlsRequest( + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py new file mode 100644 index 000000000000..05b6814cd287 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListFindingTypeStatsRequest( + ) + + # Make the request + response = await client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py new file mode 100644 index 000000000000..f9f18e708cfa --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListFindingTypeStatsRequest( + ) + + # Make the request + response = client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py new file mode 100644 index 000000000000..b8265b419552 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_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 ListFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_list_findings(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListFindingsRequest( + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py new file mode 100644 index 000000000000..b8cc02d833da --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_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 ListFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_list_findings(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListFindingsRequest( + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py new file mode 100644 index 000000000000..101dfc951439 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListScanConfigsRequest( + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py new file mode 100644 index 000000000000..5e0fda7c9a2a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListScanConfigsRequest( + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py new file mode 100644 index 000000000000..956ff8dd2184 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_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 ListScanRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListScanRunsRequest( + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py new file mode 100644 index 000000000000..e8bb370fde0a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_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 ListScanRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.ListScanRunsRequest( + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py new file mode 100644 index 000000000000..adb10291e355 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_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 StartScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.StartScanRunRequest( + ) + + # Make the request + response = await client.start_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py new file mode 100644 index 000000000000..cd9c213b7662 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_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 StartScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.StartScanRunRequest( + ) + + # Make the request + response = client.start_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py new file mode 100644 index 000000000000..eff91cdab7c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_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 StopScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.StopScanRunRequest( + ) + + # Make the request + response = await client.stop_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py new file mode 100644 index 000000000000..1fa670433efe --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_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 StopScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.StopScanRunRequest( + ) + + # Make the request + response = client.stop_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py new file mode 100644 index 000000000000..54ec11cdc2c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +async def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.UpdateScanConfigRequest( + ) + + # Make the request + response = await client.update_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py new file mode 100644 index 000000000000..ad647d84e05a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1 + + +def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1.UpdateScanConfigRequest( + ) + + # Make the request + response = client.update_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/scripts/fixup_websecurityscanner_v1_keywords.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/scripts/fixup_websecurityscanner_v1_keywords.py new file mode 100644 index 000000000000..cbe5261ddc2a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/scripts/fixup_websecurityscanner_v1_keywords.py @@ -0,0 +1,188 @@ +#! /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 websecurityscannerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_scan_config': ('parent', 'scan_config', ), + 'delete_scan_config': ('name', ), + 'get_finding': ('name', ), + 'get_scan_config': ('name', ), + 'get_scan_run': ('name', ), + 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_finding_type_stats': ('parent', ), + 'list_scan_configs': ('parent', 'page_token', 'page_size', ), + 'list_scan_runs': ('parent', 'page_token', 'page_size', ), + 'start_scan_run': ('name', ), + 'stop_scan_run': ('name', ), + 'update_scan_config': ('scan_config', '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=websecurityscannerCallTransformer(), +): + """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 websecurityscanner 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-cloud-websecurityscanner/v1/setup.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/setup.py new file mode 100644 index 000000000000..b89eea40fd8f --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner' + + +description = "Google Cloud Websecurityscanner API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/websecurityscanner/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-cloud-websecurityscanner" + +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-cloud-websecurityscanner/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/tests/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_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-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py new file mode 100644 index 000000000000..7c61a0f842c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py @@ -0,0 +1,8720 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1.services.web_security_scanner import WebSecurityScannerAsyncClient +from google.cloud.websecurityscanner_v1.services.web_security_scanner import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1.services.web_security_scanner import transports +from google.cloud.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import finding_addon +from google.cloud.websecurityscanner_v1.types import finding_type_stats +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_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 WebSecurityScannerClient._get_default_mtls_endpoint(None) is None + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WebSecurityScannerClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + WebSecurityScannerClient._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 WebSecurityScannerClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WebSecurityScannerClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WebSecurityScannerClient._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 WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, False) is None + assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, True) is mock_default_cert_source + assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE + default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert WebSecurityScannerClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + assert WebSecurityScannerClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + WebSecurityScannerClient._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 WebSecurityScannerClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert WebSecurityScannerClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert WebSecurityScannerClient._get_universe_domain(None, None) == WebSecurityScannerClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + WebSecurityScannerClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WebSecurityScannerClient, "grpc"), + (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), +]) +def test_web_security_scanner_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 == ( + 'websecurityscanner.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://websecurityscanner.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WebSecurityScannerGrpcTransport, "grpc"), + (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WebSecurityScannerRestTransport, "rest"), +]) +def test_web_security_scanner_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", [ + (WebSecurityScannerClient, "grpc"), + (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), +]) +def test_web_security_scanner_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 == ( + 'websecurityscanner.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://websecurityscanner.googleapis.com' + ) + + +def test_web_security_scanner_client_get_transport_class(): + transport = WebSecurityScannerClient.get_transport_class() + available_transports = [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerRestTransport, + ] + assert transport in available_transports + + transport = WebSecurityScannerClient.get_transport_class("grpc") + assert transport == transports.WebSecurityScannerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), +]) +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_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(WebSecurityScannerClient, '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(WebSecurityScannerClient, '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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "true"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "false"), +]) +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_web_security_scanner_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", [ + WebSecurityScannerClient, WebSecurityScannerAsyncClient +]) +@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_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", [ + WebSecurityScannerClient, WebSecurityScannerAsyncClient +]) +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE + default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WebSecurityScannerClient._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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), +]) +def test_web_security_scanner_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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", None), +]) +def test_web_security_scanner_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_web_security_scanner_client_client_options_from_dict(): + with mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WebSecurityScannerClient( + 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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_web_security_scanner_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( + "websecurityscanner.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="websecurityscanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.CreateScanConfigRequest, + dict, +]) +def test_create_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + ) + response = client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.CreateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +def test_create_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.CreateScanConfigRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.CreateScanConfigRequest( + parent='parent_value', + ) + +def test_create_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + request = {} + client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + )) + response = await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.CreateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +@pytest.mark.asyncio +async def test_create_scan_config_async_from_dict(): + await test_create_scan_config_async(request_type=dict) + +def test_create_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + web_security_scanner.DeleteScanConfigRequest, + dict, +]) +def test_delete_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.DeleteScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.DeleteScanConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.DeleteScanConfigRequest( + name='name_value', + ) + +def test_delete_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + request = {} + client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.DeleteScanConfigRequest() + 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_scan_config_async_from_dict(): + await test_delete_scan_config_async(request_type=dict) + +def test_delete_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = None + client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + web_security_scanner.GetScanConfigRequest, + dict, +]) +def test_get_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + ) + response = client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +def test_get_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.GetScanConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanConfigRequest( + name='name_value', + ) + +def test_get_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc + request = {} + client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + )) + response = await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +@pytest.mark.asyncio +async def test_get_scan_config_async_from_dict(): + await test_get_scan_config_async(request_type=dict) + +def test_get_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + web_security_scanner.ListScanConfigsRequest, + dict, +]) +def test_list_scan_configs(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListScanConfigsRequest( + 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_scan_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_scan_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_scan_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_configs] = mock_rpc + request = {} + client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_configs(request) + + # Establish that a new wrapper 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_scan_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_configs in client._client._transport._wrapped_methods + + # 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_scan_configs] = mock_rpc + + request = {} + await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scan_configs(request) + + # Establish that a new wrapper 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_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_configs_async_from_dict(): + await test_list_scan_configs_async(request_type=dict) + +def test_list_scan_configs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanConfigsResponse() + client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_configs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_configs_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_configs(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, scan_config.ScanConfig) + for i in results) +def test_list_scan_configs_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_configs(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_scan_configs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_configs(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, scan_config.ScanConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_scan_configs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + 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_scan_configs(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", [ + web_security_scanner.UpdateScanConfigRequest, + dict, +]) +def test_update_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + ) + response = client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.UpdateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +def test_update_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.UpdateScanConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.UpdateScanConfigRequest( + ) + +def test_update_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + request = {} + client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + )) + response = await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.UpdateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +@pytest.mark.asyncio +async def test_update_scan_config_async_from_dict(): + await test_update_scan_config_async(request_type=dict) + +def test_update_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'scan_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'scan_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.StartScanRunRequest, + dict, +]) +def test_start_scan_run(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StartScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_start_scan_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.StartScanRunRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.start_scan_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest( + name='name_value', + ) + +def test_start_scan_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc + request = {} + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.start_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.start_scan_run in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.start_scan_run] = mock_rpc + + request = {} + await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.start_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StartScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_start_scan_run_async_from_dict(): + await test_start_scan_run_async(request_type=dict) + +def test_start_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + web_security_scanner.GetScanRunRequest, + dict, +]) +def test_get_scan_run(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_get_scan_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.GetScanRunRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_scan_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest( + name='name_value', + ) + +def test_get_scan_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc + request = {} + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_run(request) + + # Establish that a new wrapper 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_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_run in client._client._transport._wrapped_methods + + # 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_scan_run] = mock_rpc + + request = {} + await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scan_run(request) + + # Establish that a new wrapper 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_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_get_scan_run_async_from_dict(): + await test_get_scan_run_async(request_type=dict) + +def test_get_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + web_security_scanner.ListScanRunsRequest, + dict, +]) +def test_list_scan_runs(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_runs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListScanRunsRequest( + 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_scan_runs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_scan_runs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_scan_runs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_runs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_runs] = mock_rpc + request = {} + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_runs(request) + + # Establish that a new wrapper 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_scan_runs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_runs in client._client._transport._wrapped_methods + + # 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_scan_runs] = mock_rpc + + request = {} + await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scan_runs(request) + + # Establish that a new wrapper 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_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_runs_async_from_dict(): + await test_list_scan_runs_async(request_type=dict) + +def test_list_scan_runs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanRunsResponse() + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_runs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_runs_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_runs(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, scan_run.ScanRun) + for i in results) +def test_list_scan_runs_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_runs(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_scan_runs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_runs(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, scan_run.ScanRun) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_scan_runs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + 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_scan_runs(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", [ + web_security_scanner.StopScanRunRequest, + dict, +]) +def test_stop_scan_run(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StopScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_stop_scan_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.StopScanRunRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.stop_scan_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest( + name='name_value', + ) + +def test_stop_scan_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc + request = {} + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.stop_scan_run in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.stop_scan_run] = mock_rpc + + request = {} + await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.stop_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StopScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_stop_scan_run_async_from_dict(): + await test_stop_scan_run_async(request_type=dict) + +def test_stop_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + web_security_scanner.ListCrawledUrlsRequest, + dict, +]) +def test_list_crawled_urls(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListCrawledUrlsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_crawled_urls_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListCrawledUrlsRequest( + 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_crawled_urls), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_crawled_urls(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_crawled_urls_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_crawled_urls in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_crawled_urls] = mock_rpc + request = {} + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crawled_urls(request) + + # Establish that a new wrapper 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_crawled_urls_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_crawled_urls in client._client._transport._wrapped_methods + + # 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_crawled_urls] = mock_rpc + + request = {} + await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_crawled_urls(request) + + # Establish that a new wrapper 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_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListCrawledUrlsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_from_dict(): + await test_list_crawled_urls_async(request_type=dict) + +def test_list_crawled_urls_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crawled_urls_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crawled_urls_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crawled_urls(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, crawled_url.CrawledUrl) + for i in results) +def test_list_crawled_urls_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + 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_crawled_urls(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", [ + web_security_scanner.GetFindingRequest, + dict, +]) +def test_get_finding(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + finding_type='finding_type_value', + severity=finding.Finding.Severity.CRITICAL, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + ) + response = client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +def test_get_finding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.GetFindingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetFindingRequest( + name='name_value', + ) + +def test_get_finding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_finding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc + request = {} + client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_finding(request) + + # Establish that a new wrapper 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_finding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # 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_finding] = mock_rpc + + request = {} + await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_finding(request) + + # Establish that a new wrapper 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_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + finding_type='finding_type_value', + severity=finding.Finding.Severity.CRITICAL, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + )) + response = await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +@pytest.mark.asyncio +async def test_get_finding_async_from_dict(): + await test_get_finding_async(request_type=dict) + +def test_get_finding_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = finding.Finding() + client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + web_security_scanner.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_findings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListFindingsRequest( + 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_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_findings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_findings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_findings] = mock_rpc + request = {} + client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_findings(request) + + # Establish that a new wrapper 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_findings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_findings in client._client._transport._wrapped_methods + + # 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_findings] = mock_rpc + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_findings(request) + + # Establish that a new wrapper 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_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + +def test_list_findings_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingsResponse() + client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_findings_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_findings_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_findings(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, finding.Finding) + for i in results) +def test_list_findings_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_findings(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_findings_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_findings(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, finding.Finding) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + 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_findings(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", [ + web_security_scanner.ListFindingTypeStatsRequest, + dict, +]) +def test_list_finding_type_stats(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse( + ) + response = client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingTypeStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +def test_list_finding_type_stats_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListFindingTypeStatsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_finding_type_stats(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest( + parent='parent_value', + ) + +def test_list_finding_type_stats_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_finding_type_stats in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_finding_type_stats] = mock_rpc + request = {} + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_finding_type_stats(request) + + # Establish that a new wrapper 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_finding_type_stats_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_finding_type_stats in client._client._transport._wrapped_methods + + # 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_finding_type_stats] = mock_rpc + + request = {} + await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_finding_type_stats(request) + + # Establish that a new wrapper 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_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( + )) + response = await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingTypeStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_async_from_dict(): + await test_list_finding_type_stats_async(request_type=dict) + +def test_list_finding_type_stats_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_type_stats_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + + request = {} + client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_scan_config(request) + + # Establish 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_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + + request = {} + client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_scan_config(request) + + # Establish 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_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc + + request = {} + client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_config(request) + + # Establish 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_scan_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_configs] = mock_rpc + + request = {} + client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_configs(request) + + # Establish 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_scan_configs_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListScanConfigsResponse.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_scan_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_config.ScanConfig) + for i in results) + + pages = list(client.list_scan_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + + request = {} + client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_scan_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_start_scan_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc + + request = {} + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.start_scan_run(request) + + # Establish 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_scan_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc + + request = {} + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_run(request) + + # Establish 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_scan_runs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_runs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_runs] = mock_rpc + + request = {} + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_runs(request) + + # Establish 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_scan_runs_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListScanRunsResponse.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/scanConfigs/sample2'} + + pager = client.list_scan_runs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_run.ScanRun) + for i in results) + + pages = list(client.list_scan_runs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_stop_scan_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc + + request = {} + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_scan_run(request) + + # Establish 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_crawled_urls_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_crawled_urls in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_crawled_urls] = mock_rpc + + request = {} + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crawled_urls(request) + + # Establish 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_crawled_urls_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListCrawledUrlsResponse.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/scanConfigs/sample2/scanRuns/sample3'} + + pager = client.list_crawled_urls(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, crawled_url.CrawledUrl) + for i in results) + + pages = list(client.list_crawled_urls(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_finding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_finding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc + + request = {} + client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_finding(request) + + # Establish 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_findings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_findings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_findings] = mock_rpc + + request = {} + client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_findings(request) + + # Establish 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_findings_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListFindingsResponse.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/scanConfigs/sample2/scanRuns/sample3'} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, finding.Finding) + for i in results) + + pages = list(client.list_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_finding_type_stats_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_finding_type_stats in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_finding_type_stats] = mock_rpc + + request = {} + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_finding_type_stats(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + 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 = WebSecurityScannerClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebSecurityScannerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, +]) +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 = WebSecurityScannerClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = WebSecurityScannerClient( + 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.create_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.CreateScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = None + client.delete_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.DeleteScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.get_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_configs_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanConfigsResponse() + client.list_scan_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanConfigsRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.update_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.UpdateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_scan_run_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.start_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StartScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_run_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.get_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_runs_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanRunsResponse() + client.list_scan_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_scan_run_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.stop_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StopScanRunRequest() + + assert args[0] == request_msg + + +# This 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_crawled_urls_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + client.list_crawled_urls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListCrawledUrlsRequest() + + assert args[0] == request_msg + + +# This 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_finding_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = finding.Finding() + client.get_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetFindingRequest() + + assert args[0] == request_msg + + +# This 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_findings_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingsResponse() + client.list_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingsRequest() + + assert args[0] == request_msg + + +# This 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_finding_type_stats_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + client.list_finding_type_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingTypeStatsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = WebSecurityScannerAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + )) + await client.create_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.CreateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.DeleteScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + )) + await client.get_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_configs_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + )) + await client.list_scan_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + )) + await client.update_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.UpdateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_start_scan_run_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + await client.start_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StartScanRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_run_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + await client.get_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_runs_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + )) + await client.list_scan_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_stop_scan_run_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + await client.stop_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StopScanRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_crawled_urls_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + )) + await client.list_crawled_urls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListCrawledUrlsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_finding_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + finding_type='finding_type_value', + severity=finding.Finding.Severity.CRITICAL, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + )) + await client.get_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetFindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_findings_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + )) + await client.list_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_finding_type_stats_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( + )) + await client.list_finding_type_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingTypeStatsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = WebSecurityScannerClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_scan_config_rest_bad_request(request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerClient( + 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 + client.create_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.CreateScanConfigRequest, + dict, +]) +def test_create_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request_init["scan_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}, 'iap_credential': {'iap_test_service_account_info': {'target_audience_client_id': 'target_audience_client_id_value'}}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'export_to_security_command_center': 1, 'risk_level': 1, 'managed_scan': True, 'static_ip_scan': True, 'ignore_http_status_errors': 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 = web_security_scanner.CreateScanConfigRequest.meta.fields["scan_config"] + + 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["scan_config"].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["scan_config"][field])): + del request_init["scan_config"][field][i][subfield] + else: + del request_init["scan_config"][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 = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=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 = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_create_scan_config") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_create_scan_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.CreateScanConfigRequest.pb(web_security_scanner.CreateScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) + req.return_value.content = return_value + + request = web_security_scanner.CreateScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.create_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_scan_config_rest_bad_request(request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + client.delete_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.DeleteScanConfigRequest, + dict, +]) +def test_delete_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + response = client.delete_scan_config(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_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_delete_scan_config") as pre: + pre.assert_not_called() + pb_message = web_security_scanner.DeleteScanConfigRequest.pb(web_security_scanner.DeleteScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = web_security_scanner.DeleteScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_get_scan_config_rest_bad_request(request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + client.get_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanConfigRequest, + dict, +]) +def test_get_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=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 = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_config") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanConfigRequest.pb(web_security_scanner.GetScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) + req.return_value.content = return_value + + request = web_security_scanner.GetScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.get_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_configs_rest_bad_request(request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerClient( + 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 + client.list_scan_configs(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanConfigsRequest, + dict, +]) +def test_list_scan_configs_rest_call_success(request_type): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanConfigsResponse( + 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_scan_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_configs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_configs") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanConfigsRequest.pb(web_security_scanner.ListScanConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListScanConfigsResponse.to_json(web_security_scanner.ListScanConfigsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListScanConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanConfigsResponse() + + client.list_scan_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_scan_config_rest_bad_request(request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/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 + client.update_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.UpdateScanConfigRequest, + dict, +]) +def test_update_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} + request_init["scan_config"] = {'name': 'projects/sample1/scanConfigs/sample2', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}, 'iap_credential': {'iap_test_service_account_info': {'target_audience_client_id': 'target_audience_client_id_value'}}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'export_to_security_command_center': 1, 'risk_level': 1, 'managed_scan': True, 'static_ip_scan': True, 'ignore_http_status_errors': 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 = web_security_scanner.UpdateScanConfigRequest.meta.fields["scan_config"] + + 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["scan_config"].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["scan_config"][field])): + del request_init["scan_config"][field][i][subfield] + else: + del request_init["scan_config"][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 = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=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 = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_update_scan_config") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_update_scan_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.UpdateScanConfigRequest.pb(web_security_scanner.UpdateScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) + req.return_value.content = return_value + + request = web_security_scanner.UpdateScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.update_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_scan_run_rest_bad_request(request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + client.start_scan_run(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.StartScanRunRequest, + dict, +]) +def test_start_scan_run_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.start_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_start_scan_run") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_start_scan_run") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StartScanRunRequest.pb(web_security_scanner.StartScanRunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) + req.return_value.content = return_value + + request = web_security_scanner.StartScanRunRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.start_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_scan_run_rest_bad_request(request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.get_scan_run(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanRunRequest, + dict, +]) +def test_get_scan_run_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_run") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_run") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanRunRequest.pb(web_security_scanner.GetScanRunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) + req.return_value.content = return_value + + request = web_security_scanner.GetScanRunRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.get_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_runs_rest_bad_request(request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/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 + client.list_scan_runs(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanRunsRequest, + dict, +]) +def test_list_scan_runs_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse( + 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_scan_runs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_runs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_runs") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_runs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanRunsRequest.pb(web_security_scanner.ListScanRunsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListScanRunsResponse.to_json(web_security_scanner.ListScanRunsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListScanRunsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanRunsResponse() + + client.list_scan_runs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_scan_run_rest_bad_request(request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.stop_scan_run(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.StopScanRunRequest, + dict, +]) +def test_stop_scan_run_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.stop_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_stop_scan_run") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_stop_scan_run") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StopScanRunRequest.pb(web_security_scanner.StopScanRunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) + req.return_value.content = return_value + + request = web_security_scanner.StopScanRunRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.stop_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_crawled_urls_rest_bad_request(request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.list_crawled_urls(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListCrawledUrlsRequest, + dict, +]) +def test_list_crawled_urls_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListCrawledUrlsResponse( + 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_crawled_urls(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crawled_urls_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_crawled_urls") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_crawled_urls") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListCrawledUrlsRequest.pb(web_security_scanner.ListCrawledUrlsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListCrawledUrlsResponse.to_json(web_security_scanner.ListCrawledUrlsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListCrawledUrlsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListCrawledUrlsResponse() + + client.list_crawled_urls(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_finding_rest_bad_request(request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_finding(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetFindingRequest, + dict, +]) +def test_get_finding_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = finding.Finding( + name='name_value', + finding_type='finding_type_value', + severity=finding.Finding.Severity.CRITICAL, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = finding.Finding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_finding_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_finding") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetFindingRequest.pb(web_security_scanner.GetFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = finding.Finding.to_json(finding.Finding()) + req.return_value.content = return_value + + request = web_security_scanner.GetFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.get_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.list_findings(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListFindingsRequest, + dict, +]) +def test_list_findings_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingsResponse( + 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 = web_security_scanner.ListFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingsRequest.pb(web_security_scanner.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListFindingsResponse.to_json(web_security_scanner.ListFindingsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_finding_type_stats_rest_bad_request(request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.list_finding_type_stats(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListFindingTypeStatsRequest, + dict, +]) +def test_list_finding_type_stats_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingTypeStatsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_finding_type_stats(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_finding_type_stats_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_finding_type_stats") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_finding_type_stats") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingTypeStatsRequest.pb(web_security_scanner.ListFindingTypeStatsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListFindingTypeStatsResponse.to_json(web_security_scanner.ListFindingTypeStatsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListFindingTypeStatsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + client.list_finding_type_stats(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = WebSecurityScannerClient( + 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + client.create_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.CreateScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + client.delete_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.DeleteScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + client.get_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_configs_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + client.list_scan_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanConfigsRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + client.update_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.UpdateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_scan_run_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + client.start_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StartScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_run_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + client.get_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_runs_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + client.list_scan_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_scan_run_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + client.stop_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StopScanRunRequest() + + assert args[0] == request_msg + + +# This 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_crawled_urls_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + client.list_crawled_urls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListCrawledUrlsRequest() + + assert args[0] == request_msg + + +# This 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_finding_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + client.get_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetFindingRequest() + + assert args[0] == request_msg + + +# This 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_findings_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + client.list_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingsRequest() + + assert args[0] == request_msg + + +# This 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_finding_type_stats_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + client.list_finding_type_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingTypeStatsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebSecurityScannerGrpcTransport, + ) + +def test_web_security_scanner_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_web_security_scanner_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_scan_config', + 'delete_scan_config', + 'get_scan_config', + 'list_scan_configs', + 'update_scan_config', + 'start_scan_run', + 'get_scan_run', + 'list_scan_runs', + 'stop_scan_run', + 'list_crawled_urls', + 'get_finding', + 'list_findings', + 'list_finding_type_stats', + ) + 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_web_security_scanner_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + 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_web_security_scanner_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport() + adc.assert_called_once() + + +def test_web_security_scanner_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) + WebSecurityScannerClient() + 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.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + ], +) +def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, + ], +) +def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, grpc_helpers), + (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_web_security_scanner_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( + "websecurityscanner.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="websecurityscanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_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_web_security_scanner_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.WebSecurityScannerRestTransport ( + 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_web_security_scanner_host_no_port(transport_name): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'websecurityscanner.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://websecurityscanner.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_web_security_scanner_host_with_port(transport_name): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'websecurityscanner.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://websecurityscanner.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_web_security_scanner_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WebSecurityScannerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WebSecurityScannerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_scan_config._session + session2 = client2.transport.create_scan_config._session + assert session1 != session2 + session1 = client1.transport.delete_scan_config._session + session2 = client2.transport.delete_scan_config._session + assert session1 != session2 + session1 = client1.transport.get_scan_config._session + session2 = client2.transport.get_scan_config._session + assert session1 != session2 + session1 = client1.transport.list_scan_configs._session + session2 = client2.transport.list_scan_configs._session + assert session1 != session2 + session1 = client1.transport.update_scan_config._session + session2 = client2.transport.update_scan_config._session + assert session1 != session2 + session1 = client1.transport.start_scan_run._session + session2 = client2.transport.start_scan_run._session + assert session1 != session2 + session1 = client1.transport.get_scan_run._session + session2 = client2.transport.get_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_scan_runs._session + session2 = client2.transport.list_scan_runs._session + assert session1 != session2 + session1 = client1.transport.stop_scan_run._session + session2 = client2.transport.stop_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_crawled_urls._session + session2 = client2.transport.list_crawled_urls._session + assert session1 != session2 + session1 = client1.transport.get_finding._session + session2 = client2.transport.get_finding._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_finding_type_stats._session + session2 = client2.transport.list_finding_type_stats._session + assert session1 != session2 +def test_web_security_scanner_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcTransport( + 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_web_security_scanner_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + 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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_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_finding_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + finding = "octopus" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "project": "oyster", + "scan_config": "nudibranch", + "scan_run": "cuttlefish", + "finding": "mussel", + } + path = WebSecurityScannerClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_finding_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WebSecurityScannerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = WebSecurityScannerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = WebSecurityScannerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = WebSecurityScannerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WebSecurityScannerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = WebSecurityScannerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = WebSecurityScannerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = WebSecurityScannerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.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 = WebSecurityScannerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = WebSecurityScannerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.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.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + transport_class = WebSecurityScannerClient.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 = WebSecurityScannerClient( + 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 = WebSecurityScannerAsyncClient( + 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 = WebSecurityScannerClient( + 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 = WebSecurityScannerClient( + 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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport), +]) +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-cloud-websecurityscanner/v1alpha/.coveragerc b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.coveragerc new file mode 100644 index 000000000000..085a92b30288 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/websecurityscanner/__init__.py + google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1alpha/.flake8 b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.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-cloud-websecurityscanner/v1alpha/MANIFEST.in b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/MANIFEST.in new file mode 100644 index 000000000000..984c53e3603b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/websecurityscanner *.py +recursive-include google/cloud/websecurityscanner_v1alpha *.py diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/README.rst new file mode 100644 index 000000000000..4de4c103eee6 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Websecurityscanner 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 Cloud Websecurityscanner 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-cloud-websecurityscanner/v1alpha/docs/_static/custom.css b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/conf.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/conf.py new file mode 100644 index 000000000000..40ff11b301ef --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner 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-cloud-websecurityscanner" +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 Cloud 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-cloud-websecurityscanner-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-cloud-websecurityscanner.tex", + u"google-cloud-websecurityscanner 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-cloud-websecurityscanner", + u"Google Cloud Websecurityscanner 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-cloud-websecurityscanner", + u"google-cloud-websecurityscanner Documentation", + author, + "google-cloud-websecurityscanner", + "GAPIC library for Google Cloud Websecurityscanner 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-cloud-websecurityscanner/v1alpha/docs/index.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/index.rst new file mode 100644 index 000000000000..f694969992f5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + websecurityscanner_v1alpha/services_ + websecurityscanner_v1alpha/types_ diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/services_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/services_.rst new file mode 100644 index 000000000000..a4ad4137e1d9 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Websecurityscanner v1alpha API +======================================================== +.. toctree:: + :maxdepth: 2 + + web_security_scanner diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/types_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/types_.rst new file mode 100644 index 000000000000..a465d17792b3 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Websecurityscanner v1alpha API +===================================================== + +.. automodule:: google.cloud.websecurityscanner_v1alpha.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst new file mode 100644 index 000000000000..1bb56883bd40 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst @@ -0,0 +1,10 @@ +WebSecurityScanner +------------------------------------ + +.. automodule:: google.cloud.websecurityscanner_v1alpha.services.web_security_scanner + :members: + :inherited-members: + +.. automodule:: google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/__init__.py new file mode 100644 index 000000000000..9782642f052f --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/__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.cloud.websecurityscanner import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.client import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient + +from google.cloud.websecurityscanner_v1alpha.types.crawled_url import CrawledUrl +from google.cloud.websecurityscanner_v1alpha.types.finding import Finding +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import OutdatedLibrary +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import ViolatingResource +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import VulnerableHeaders +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import VulnerableParameters +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import Xss +from google.cloud.websecurityscanner_v1alpha.types.finding_type_stats import FindingTypeStats +from google.cloud.websecurityscanner_v1alpha.types.scan_config import ScanConfig +from google.cloud.websecurityscanner_v1alpha.types.scan_run import ScanRun +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import CreateScanConfigRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import DeleteScanConfigRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetFindingRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetScanConfigRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetScanRunRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListCrawledUrlsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListCrawledUrlsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingTypeStatsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingTypeStatsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanConfigsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanConfigsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanRunsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanRunsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import StartScanRunRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import StopScanRunRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ('WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', + 'CrawledUrl', + 'Finding', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanRun', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/py.typed new file mode 100644 index 000000000000..8cfb5d256398 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py new file mode 100644 index 000000000000..69db5396a6ab --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/__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.cloud.websecurityscanner_v1alpha import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.web_security_scanner import WebSecurityScannerClient +from .services.web_security_scanner import WebSecurityScannerAsyncClient + +from .types.crawled_url import CrawledUrl +from .types.finding import Finding +from .types.finding_addon import OutdatedLibrary +from .types.finding_addon import ViolatingResource +from .types.finding_addon import VulnerableHeaders +from .types.finding_addon import VulnerableParameters +from .types.finding_addon import Xss +from .types.finding_type_stats import FindingTypeStats +from .types.scan_config import ScanConfig +from .types.scan_run import ScanRun +from .types.web_security_scanner import CreateScanConfigRequest +from .types.web_security_scanner import DeleteScanConfigRequest +from .types.web_security_scanner import GetFindingRequest +from .types.web_security_scanner import GetScanConfigRequest +from .types.web_security_scanner import GetScanRunRequest +from .types.web_security_scanner import ListCrawledUrlsRequest +from .types.web_security_scanner import ListCrawledUrlsResponse +from .types.web_security_scanner import ListFindingsRequest +from .types.web_security_scanner import ListFindingsResponse +from .types.web_security_scanner import ListFindingTypeStatsRequest +from .types.web_security_scanner import ListFindingTypeStatsResponse +from .types.web_security_scanner import ListScanConfigsRequest +from .types.web_security_scanner import ListScanConfigsResponse +from .types.web_security_scanner import ListScanRunsRequest +from .types.web_security_scanner import ListScanRunsResponse +from .types.web_security_scanner import StartScanRunRequest +from .types.web_security_scanner import StopScanRunRequest +from .types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ( + 'WebSecurityScannerAsyncClient', +'CrawledUrl', +'CreateScanConfigRequest', +'DeleteScanConfigRequest', +'Finding', +'FindingTypeStats', +'GetFindingRequest', +'GetScanConfigRequest', +'GetScanRunRequest', +'ListCrawledUrlsRequest', +'ListCrawledUrlsResponse', +'ListFindingTypeStatsRequest', +'ListFindingTypeStatsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListScanConfigsRequest', +'ListScanConfigsResponse', +'ListScanRunsRequest', +'ListScanRunsResponse', +'OutdatedLibrary', +'ScanConfig', +'ScanRun', +'StartScanRunRequest', +'StopScanRunRequest', +'UpdateScanConfigRequest', +'ViolatingResource', +'VulnerableHeaders', +'VulnerableParameters', +'WebSecurityScannerClient', +'Xss', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json new file mode 100644 index 000000000000..a7c87fd4f50f --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json @@ -0,0 +1,223 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.websecurityscanner_v1alpha", + "protoPackage": "google.cloud.websecurityscanner.v1alpha", + "schema": "1.0", + "services": { + "WebSecurityScanner": { + "clients": { + "grpc": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebSecurityScannerAsyncClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + }, + "rest": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed new file mode 100644 index 000000000000..8cfb5d256398 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py new file mode 100644 index 000000000000..3aeec5e07d95 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__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 WebSecurityScannerClient +from .async_client import WebSecurityScannerAsyncClient + +__all__ = ( + 'WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py new file mode 100644 index 000000000000..ee50e7769af3 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py @@ -0,0 +1,1698 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.websecurityscanner_v1alpha 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.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import finding_addon +from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .client import WebSecurityScannerClient + + +class WebSecurityScannerAsyncClient: + """Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + """ + + _client: WebSecurityScannerClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WebSecurityScannerClient._DEFAULT_UNIVERSE + + finding_path = staticmethod(WebSecurityScannerClient.finding_path) + parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) + scan_config_path = staticmethod(WebSecurityScannerClient.scan_config_path) + parse_scan_config_path = staticmethod(WebSecurityScannerClient.parse_scan_config_path) + scan_run_path = staticmethod(WebSecurityScannerClient.scan_run_path) + parse_scan_run_path = staticmethod(WebSecurityScannerClient.parse_scan_run_path) + common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) + parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) + common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) + parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) + common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) + parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) + common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) + parse_common_location_path = staticmethod(WebSecurityScannerClient.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: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, 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: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, 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 WebSecurityScannerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: 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 = WebSecurityScannerClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner 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,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): + 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 WebSecurityScannerTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WebSecurityScannerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_scan_config(self, + request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + scan_config: Optional[gcw_scan_config.ScanConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1alpha.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1alpha.CreateScanConfigRequest( + parent="parent_value", + scan_config=scan_config, + ) + + # Make the request + response = await client.create_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest, dict]]): + The request object. Request for the ``CreateScanConfig`` method. + parent (:class:`str`): + Required. The parent resource name + where the scan is created, which should + be a project resource name in the format + 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scan_config (:class:`google.cloud.websecurityscanner_v1alpha.types.ScanConfig`): + Required. The ScanConfig to be + created. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_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. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, scan_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, web_security_scanner.CreateScanConfigRequest): + request = web_security_scanner.CreateScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scan_config is not None: + request.scan_config = scan_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_scan_config] + + # Certain fields should be provided within 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_scan_config(self, + request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.DeleteScanConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_scan_config(request=request) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest, dict]]): + The request object. Request for the ``DeleteScanConfig`` method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be deleted. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.DeleteScanConfigRequest): + request = web_security_scanner.DeleteScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_config] + + # Certain fields should be provided within 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 get_scan_config(self, + request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetScanConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest, dict]]): + The request object. Request for the ``GetScanConfig`` method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be returned. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetScanConfigRequest): + request = web_security_scanner.GetScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_config] + + # Certain fields should be provided within 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_scan_configs(self, + request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsAsyncPager: + r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1alpha + + async def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListScanConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest, dict]]): + The request object. Request for the ``ListScanConfigs`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a project resource name + in the format 'projects/{projectId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: + Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): + request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] + + # Certain fields should be provided within 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.ListScanConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_scan_config(self, + request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, + *, + scan_config: Optional[gcw_scan_config.ScanConfig] = 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, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1alpha.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1alpha.UpdateScanConfigRequest( + scan_config=scan_config, + ) + + # Make the request + response = await client.update_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest, dict]]): + The request object. Request for the ``UpdateScanConfigRequest`` method. + scan_config (:class:`google.cloud.websecurityscanner_v1alpha.types.ScanConfig`): + Required. The ScanConfig to be + updated. The name field must be set to + identify the resource to be updated. The + values of fields not covered by the mask + will be ignored. + + This corresponds to the ``scan_config`` 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 update mask applies to the resource. For + the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scan_config, 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, web_security_scanner.UpdateScanConfigRequest): + request = web_security_scanner.UpdateScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scan_config is not None: + request.scan_config = scan_config + 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_scan_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.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 start_scan_run(self, + request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.StartScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.start_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest, dict]]): + The request object. Request for the ``StartScanRun`` method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be used. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.StartScanRunRequest): + request = web_security_scanner.StartScanRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.start_scan_run] + + # Certain fields should be provided within 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_scan_run(self, + request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest, dict]]): + The request object. Request for the ``GetScanRun`` method. + name (:class:`str`): + Required. The resource name of the + ScanRun to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetScanRunRequest): + request = web_security_scanner.GetScanRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_run] + + # Certain fields should be provided within 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_scan_runs(self, + request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsAsyncPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListScanRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest, dict]]): + The request object. Request for the ``ListScanRuns`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan resource name in + the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsAsyncPager: + Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): + request = web_security_scanner.ListScanRunsRequest(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_scan_runs] + + # Certain fields should be provided within 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.ListScanRunsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def stop_scan_run(self, + request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.StopScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.stop_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest, dict]]): + The request object. Request for the ``StopScanRun`` method. + name (:class:`str`): + Required. The resource name of the + ScanRun to be stopped. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.StopScanRunRequest): + request = web_security_scanner.StopScanRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.stop_scan_run] + + # Certain fields should be provided within 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_crawled_urls(self, + request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsAsyncPager: + r"""List CrawledUrls under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListCrawledUrlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest, dict]]): + The request object. Request for the ``ListCrawledUrls`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: + Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] + + # Certain fields should be provided within 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.ListCrawledUrlsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_finding(self, + request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_get_finding(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetFindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest, dict]]): + The request object. Request for the ``GetFinding`` method. + name (:class:`str`): + Required. The resource name of the + Finding to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetFindingRequest): + request = web_security_scanner.GetFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_finding] + + # Certain fields should be provided within 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_findings(self, + request: Optional[Union[web_security_scanner.ListFindingsRequest, 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, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""List Findings under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_list_findings(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListFindingsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest, dict]]): + The request object. Request for the ``ListFindings`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Required. The filter expression. The expression must be + in the format: . Supported field: 'finding_type'. + Supported operator: '='. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsAsyncPager: + Response for the ListFindings 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, 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, web_security_scanner.ListFindingsRequest): + request = web_security_scanner.ListFindingsRequest(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_findings] + + # Certain fields should be provided within 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.ListFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_finding_type_stats(self, + request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + async def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListFindingTypeStatsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest, dict]]): + The request object. Request for the ``ListFindingTypeStats`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + 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, web_security_scanner.ListFindingTypeStatsRequest): + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] + + # Certain fields should be provided within 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) -> "WebSecurityScannerAsyncClient": + 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__ = ( + "WebSecurityScannerAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py new file mode 100644 index 000000000000..7edee84eaf0a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py @@ -0,0 +1,2060 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.websecurityscanner_v1alpha 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 + +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import finding_addon +from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WebSecurityScannerGrpcTransport +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .transports.rest import WebSecurityScannerRestTransport + + +class WebSecurityScannerClientMeta(type): + """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] + _transport_registry["grpc"] = WebSecurityScannerGrpcTransport + _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport + _transport_registry["rest"] = WebSecurityScannerRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WebSecurityScannerTransport]: + """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 WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): + """Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + """ + + @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 = "websecurityscanner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "websecurityscanner.{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: + WebSecurityScannerClient: 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: + WebSecurityScannerClient: 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) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def scan_config_path(project: str,scan_config: str,) -> str: + """Returns a fully-qualified scan_config string.""" + return "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) + + @staticmethod + def parse_scan_config_path(path: str) -> Dict[str,str]: + """Parses a scan_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def scan_run_path(project: str,scan_config: str,scan_run: str,) -> str: + """Returns a fully-qualified scan_run string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) + + @staticmethod + def parse_scan_run_path(path: str) -> Dict[str,str]: + """Parses a scan_run path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?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 = WebSecurityScannerClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WebSecurityScannerClient._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 = WebSecurityScannerClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + WebSecurityScannerClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): + 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 WebSecurityScannerTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WebSecurityScannerClient._read_environment_variables() + self._client_cert_source = WebSecurityScannerClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = WebSecurityScannerClient._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 + + 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, WebSecurityScannerTransport) + if transport_provided: + # transport is a WebSecurityScannerTransport 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(WebSecurityScannerTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + WebSecurityScannerClient._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[WebSecurityScannerTransport], Callable[..., WebSecurityScannerTransport]] = ( + WebSecurityScannerClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WebSecurityScannerTransport], 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, + ) + + def create_scan_config(self, + request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + scan_config: Optional[gcw_scan_config.ScanConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1alpha.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1alpha.CreateScanConfigRequest( + parent="parent_value", + scan_config=scan_config, + ) + + # Make the request + response = client.create_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest, dict]): + The request object. Request for the ``CreateScanConfig`` method. + parent (str): + Required. The parent resource name + where the scan is created, which should + be a project resource name in the format + 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): + Required. The ScanConfig to be + created. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, scan_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, web_security_scanner.CreateScanConfigRequest): + request = web_security_scanner.CreateScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scan_config is not None: + request.scan_config = scan_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_scan_config] + + # Certain fields should be provided within 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_scan_config(self, + request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.DeleteScanConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_scan_config(request=request) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest, dict]): + The request object. Request for the ``DeleteScanConfig`` method. + name (str): + Required. The resource name of the + ScanConfig to be deleted. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.DeleteScanConfigRequest): + request = web_security_scanner.DeleteScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_config] + + # Certain fields should be provided within 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 get_scan_config(self, + request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetScanConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest, dict]): + The request object. Request for the ``GetScanConfig`` method. + name (str): + Required. The resource name of the + ScanConfig to be returned. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetScanConfigRequest): + request = web_security_scanner.GetScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_config] + + # Certain fields should be provided within 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_scan_configs(self, + request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsPager: + r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1alpha + + def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListScanConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest, dict]): + The request object. Request for the ``ListScanConfigs`` method. + parent (str): + Required. The parent resource name, + which should be a project resource name + in the format 'projects/{projectId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsPager: + Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): + request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] + + # Certain fields should be provided within 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.ListScanConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_scan_config(self, + request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, + *, + scan_config: Optional[gcw_scan_config.ScanConfig] = 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, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1alpha.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1alpha.UpdateScanConfigRequest( + scan_config=scan_config, + ) + + # Make the request + response = client.update_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest, dict]): + The request object. Request for the ``UpdateScanConfigRequest`` method. + scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): + Required. The ScanConfig to be + updated. The name field must be set to + identify the resource to be updated. The + values of fields not covered by the mask + will be ignored. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For + the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scan_config, 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, web_security_scanner.UpdateScanConfigRequest): + request = web_security_scanner.UpdateScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scan_config is not None: + request.scan_config = scan_config + 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_scan_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.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 start_scan_run(self, + request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.StartScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.start_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest, dict]): + The request object. Request for the ``StartScanRun`` method. + name (str): + Required. The resource name of the + ScanConfig to be used. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.StartScanRunRequest): + request = web_security_scanner.StartScanRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.start_scan_run] + + # Certain fields should be provided within 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_scan_run(self, + request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.get_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest, dict]): + The request object. Request for the ``GetScanRun`` method. + name (str): + Required. The resource name of the + ScanRun to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetScanRunRequest): + request = web_security_scanner.GetScanRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_run] + + # Certain fields should be provided within 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_scan_runs(self, + request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListScanRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest, dict]): + The request object. Request for the ``ListScanRuns`` method. + parent (str): + Required. The parent resource name, + which should be a scan resource name in + the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsPager: + Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): + request = web_security_scanner.ListScanRunsRequest(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_scan_runs] + + # Certain fields should be provided within 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.ListScanRunsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stop_scan_run(self, + request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.StopScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.stop_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest, dict]): + The request object. Request for the ``StopScanRun`` method. + name (str): + Required. The resource name of the + ScanRun to be stopped. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.StopScanRunRequest): + request = web_security_scanner.StopScanRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.stop_scan_run] + + # Certain fields should be provided within 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_crawled_urls(self, + request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsPager: + r"""List CrawledUrls under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListCrawledUrlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest, dict]): + The request object. Request for the ``ListCrawledUrls`` method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsPager: + Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] + + # Certain fields should be provided within 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.ListCrawledUrlsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_finding(self, + request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_get_finding(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetFindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest, dict]): + The request object. Request for the ``GetFinding`` method. + name (str): + Required. The resource name of the + Finding to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetFindingRequest): + request = web_security_scanner.GetFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_finding] + + # Certain fields should be provided within 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_findings(self, + request: Optional[Union[web_security_scanner.ListFindingsRequest, 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, str]] = (), + ) -> pagers.ListFindingsPager: + r"""List Findings under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_list_findings(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListFindingsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest, dict]): + The request object. Request for the ``ListFindings`` method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Required. The filter expression. The expression must be + in the format: . Supported field: 'finding_type'. + Supported operator: '='. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsPager: + Response for the ListFindings 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, 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, web_security_scanner.ListFindingsRequest): + request = web_security_scanner.ListFindingsRequest(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_findings] + + # Certain fields should be provided within 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.ListFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_finding_type_stats(self, + request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1alpha + + def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListFindingTypeStatsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest, dict]): + The request object. Request for the ``ListFindingTypeStats`` method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + 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, web_security_scanner.ListFindingTypeStatsRequest): + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] + + # Certain fields should be provided within 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) -> "WebSecurityScannerClient": + 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__ = ( + "WebSecurityScannerClient", +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py new file mode 100644 index 000000000000..055868c3ae3a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py @@ -0,0 +1,571 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner + + +class ListScanConfigsPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListScanConfigsResponse], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + for page in self.pages: + yield from page.scan_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanConfigsAsyncPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` + attributes are available on the 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[web_security_scanner.ListScanConfigsResponse]], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListScanRunsResponse], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + for page in self.pages: + yield from page.scan_runs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsAsyncPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` + attributes are available on the 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[web_security_scanner.ListScanRunsResponse]], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_runs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListCrawledUrlsResponse], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + for page in self.pages: + yield from page.crawled_urls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsAsyncPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` + attributes are available on the 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[web_security_scanner.ListCrawledUrlsResponse]], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + async def async_generator(): + async for page in self.pages: + for response in page.crawled_urls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListFindingsResponse], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: + 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[finding.Finding]: + for page in self.pages: + yield from page.findings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` + attributes are available on the 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[web_security_scanner.ListFindingsResponse]], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: + 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[finding.Finding]: + async def async_generator(): + async for page in self.pages: + for response in page.findings: + 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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/README.rst new file mode 100644 index 000000000000..3479ee767648 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`WebSecurityScannerTransport` is the ABC for all transports. +- public child `WebSecurityScannerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `WebSecurityScannerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseWebSecurityScannerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `WebSecurityScannerRestTransport` 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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py new file mode 100644 index 000000000000..e24819a4ee07 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/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 WebSecurityScannerTransport +from .grpc import WebSecurityScannerGrpcTransport +from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .rest import WebSecurityScannerRestTransport +from .rest import WebSecurityScannerRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] +_transport_registry['grpc'] = WebSecurityScannerGrpcTransport +_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport +_transport_registry['rest'] = WebSecurityScannerRestTransport + +__all__ = ( + 'WebSecurityScannerTransport', + 'WebSecurityScannerGrpcTransport', + 'WebSecurityScannerGrpcAsyncIOTransport', + 'WebSecurityScannerRestTransport', + 'WebSecurityScannerRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py new file mode 100644 index 000000000000..8adb5f158796 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1alpha 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.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WebSecurityScannerTransport(abc.ABC): + """Abstract transport class for WebSecurityScanner.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_scan_config: gapic_v1.method.wrap_method( + self.create_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.delete_scan_config: gapic_v1.method.wrap_method( + self.delete_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_config: gapic_v1.method.wrap_method( + self.get_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_configs: gapic_v1.method.wrap_method( + self.list_scan_configs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_scan_config: gapic_v1.method.wrap_method( + self.update_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.start_scan_run: gapic_v1.method.wrap_method( + self.start_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_run: gapic_v1.method.wrap_method( + self.get_scan_run, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_runs: gapic_v1.method.wrap_method( + self.list_scan_runs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.stop_scan_run: gapic_v1.method.wrap_method( + self.stop_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.list_crawled_urls: gapic_v1.method.wrap_method( + self.list_crawled_urls, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_finding: gapic_v1.method.wrap_method( + self.get_finding, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_finding_type_stats: gapic_v1.method.wrap_method( + self.list_finding_type_stats, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Union[ + gcw_scan_config.ScanConfig, + Awaitable[gcw_scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Union[ + web_security_scanner.ListScanConfigsResponse, + Awaitable[web_security_scanner.ListScanConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Union[ + gcw_scan_config.ScanConfig, + Awaitable[gcw_scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Union[ + web_security_scanner.ListScanRunsResponse, + Awaitable[web_security_scanner.ListScanRunsResponse] + ]]: + raise NotImplementedError() + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Union[ + web_security_scanner.ListCrawledUrlsResponse, + Awaitable[web_security_scanner.ListCrawledUrlsResponse] + ]]: + raise NotImplementedError() + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Union[ + web_security_scanner.ListFindingsResponse, + Awaitable[web_security_scanner.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Union[ + web_security_scanner.ListFindingTypeStatsResponse, + Awaitable[web_security_scanner.ListFindingTypeStatsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WebSecurityScannerTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py new file mode 100644 index 000000000000..de43b70f1f09 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO + + +class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): + """gRPC backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'websecurityscanner.googleapis.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_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + gcw_scan_config.ScanConfig]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + ~.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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + ~.ListScanConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + gcw_scan_config.ScanConfig]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + ~.ListScanRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + ~.ListCrawledUrlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + finding.Finding]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + ~.ListFindingTypeStatsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WebSecurityScannerGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py new file mode 100644 index 000000000000..6381e2b7bbf4 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py @@ -0,0 +1,764 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .grpc import WebSecurityScannerGrpcTransport + + +class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): + """gRPC AsyncIO backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'websecurityscanner.googleapis.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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Awaitable[gcw_scan_config.ScanConfig]]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + 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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Awaitable[web_security_scanner.ListScanConfigsResponse]]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + Awaitable[~.ListScanConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Awaitable[gcw_scan_config.ScanConfig]]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Awaitable[web_security_scanner.ListScanRunsResponse]]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + Awaitable[~.ListScanRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + Awaitable[~.ListCrawledUrlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Awaitable[web_security_scanner.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + Awaitable[~.ListFindingTypeStatsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + 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_scan_config: self._wrap_method( + self.create_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.delete_scan_config: self._wrap_method( + self.delete_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_config: self._wrap_method( + self.get_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_configs: self._wrap_method( + self.list_scan_configs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_scan_config: self._wrap_method( + self.update_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.start_scan_run: self._wrap_method( + self.start_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_run: self._wrap_method( + self.get_scan_run, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_runs: self._wrap_method( + self.list_scan_runs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.stop_scan_run: self._wrap_method( + self.stop_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.list_crawled_urls: self._wrap_method( + self.list_crawled_urls, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_finding: self._wrap_method( + self.get_finding, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_findings: self._wrap_method( + self.list_findings, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_finding_type_stats: self._wrap_method( + self.list_finding_type_stats, + 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=600.0, + ), + default_timeout=600.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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'WebSecurityScannerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py new file mode 100644 index 000000000000..0e6858594151 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py @@ -0,0 +1,1533 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + + +from .rest_base import _BaseWebSecurityScannerRestTransport +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 + + +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 WebSecurityScannerRestInterceptor: + """Interceptor for WebSecurityScanner. + + 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 WebSecurityScannerRestTransport. + + .. code-block:: python + class MyCustomWebSecurityScannerInterceptor(WebSecurityScannerRestInterceptor): + def pre_create_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crawled_urls(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crawled_urls(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_finding_type_stats(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_finding_type_stats(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_runs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_runs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WebSecurityScannerRestTransport(interceptor=MyCustomWebSecurityScannerInterceptor()) + client = WebSecurityScannerClient(transport=transport) + + + """ + def pre_create_scan_config(self, request: web_security_scanner.CreateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.CreateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_create_scan_config(self, response: gcw_scan_config.ScanConfig) -> gcw_scan_config.ScanConfig: + """Post-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_delete_scan_config(self, request: web_security_scanner.DeleteScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.DeleteScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def pre_get_finding(self, request: web_security_scanner.GetFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_finding(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for get_finding + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_config(self, request: web_security_scanner.GetScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: + """Post-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_run(self, request: web_security_scanner.GetScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_crawled_urls(self, request: web_security_scanner.ListCrawledUrlsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListCrawledUrlsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_crawled_urls(self, response: web_security_scanner.ListCrawledUrlsResponse) -> web_security_scanner.ListCrawledUrlsResponse: + """Post-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_findings(self, request: web_security_scanner.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_findings(self, response: web_security_scanner.ListFindingsResponse) -> web_security_scanner.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_finding_type_stats(self, request: web_security_scanner.ListFindingTypeStatsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingTypeStatsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_finding_type_stats(self, response: web_security_scanner.ListFindingTypeStatsResponse) -> web_security_scanner.ListFindingTypeStatsResponse: + """Post-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_configs(self, request: web_security_scanner.ListScanConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_configs(self, response: web_security_scanner.ListScanConfigsResponse) -> web_security_scanner.ListScanConfigsResponse: + """Post-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_runs(self, request: web_security_scanner.ListScanRunsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanRunsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_runs(self, response: web_security_scanner.ListScanRunsResponse) -> web_security_scanner.ListScanRunsResponse: + """Post-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_start_scan_run(self, request: web_security_scanner.StartScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StartScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_start_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_stop_scan_run(self, request: web_security_scanner.StopScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StopScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_stop_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_update_scan_config(self, request: web_security_scanner.UpdateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.UpdateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_update_scan_config(self, response: gcw_scan_config.ScanConfig) -> gcw_scan_config.ScanConfig: + """Post-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WebSecurityScannerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WebSecurityScannerRestInterceptor + + +class WebSecurityScannerRestTransport(_BaseWebSecurityScannerRestTransport): + """REST backend synchronous transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'websecurityscanner.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[WebSecurityScannerRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 WebSecurityScannerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateScanConfig(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.CreateScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.CreateScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcw_scan_config.ScanConfig: + r"""Call the create scan config method over HTTP. + + Args: + request (~.web_security_scanner.CreateScanConfigRequest): + The request object. Request for the ``CreateScanConfig`` method. + retry (google.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. + + Returns: + ~.gcw_scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_http_options() + request, metadata = self._interceptor.pre_create_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._CreateScanConfig._get_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 = gcw_scan_config.ScanConfig() + pb_resp = gcw_scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_scan_config(resp) + return resp + + class _DeleteScanConfig(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.DeleteScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.DeleteScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete scan config method over HTTP. + + Args: + request (~.web_security_scanner.DeleteScanConfigRequest): + The request object. Request for the ``DeleteScanConfig`` method. + retry (google.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. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_http_options() + request, metadata = self._interceptor.pre_delete_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._DeleteScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 _GetFinding(_BaseWebSecurityScannerRestTransport._BaseGetFinding, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.GetFinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.GetFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the get finding method over HTTP. + + Args: + request (~.web_security_scanner.GetFindingRequest): + The request object. Request for the ``GetFinding`` method. + retry (google.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. + + Returns: + ~.finding.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_http_options() + request, metadata = self._interceptor.pre_get_finding(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._GetFinding._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = finding.Finding() + pb_resp = finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_finding(resp) + return resp + + class _GetScanConfig(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.GetScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.GetScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_config.ScanConfig: + r"""Call the get scan config method over HTTP. + + Args: + request (~.web_security_scanner.GetScanConfigRequest): + The request object. Request for the ``GetScanConfig`` method. + retry (google.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. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_http_options() + request, metadata = self._interceptor.pre_get_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._GetScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_config(resp) + return resp + + class _GetScanRun(_BaseWebSecurityScannerRestTransport._BaseGetScanRun, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.GetScanRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.GetScanRunRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_run.ScanRun: + r"""Call the get scan run method over HTTP. + + Args: + request (~.web_security_scanner.GetScanRunRequest): + The request object. Request for the ``GetScanRun`` method. + retry (google.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. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_http_options() + request, metadata = self._interceptor.pre_get_scan_run(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._GetScanRun._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_run(resp) + return resp + + class _ListCrawledUrls(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListCrawledUrls") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListCrawledUrlsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListCrawledUrlsResponse: + r"""Call the list crawled urls method over HTTP. + + Args: + request (~.web_security_scanner.ListCrawledUrlsRequest): + The request object. Request for the ``ListCrawledUrls`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListCrawledUrlsResponse: + Response for the ``ListCrawledUrls`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_http_options() + request, metadata = self._interceptor.pre_list_crawled_urls(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListCrawledUrls._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListCrawledUrlsResponse() + pb_resp = web_security_scanner.ListCrawledUrlsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crawled_urls(resp) + return resp + + class _ListFindings(_BaseWebSecurityScannerRestTransport._BaseListFindings, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListFindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingsRequest): + The request object. Request for the ``ListFindings`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListFindingsResponse: + Response for the ``ListFindings`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_http_options() + request, metadata = self._interceptor.pre_list_findings(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListFindings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListFindingsResponse() + pb_resp = web_security_scanner.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListFindingTypeStats(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListFindingTypeStats") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListFindingTypeStatsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""Call the list finding type stats method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingTypeStatsRequest): + The request object. Request for the ``ListFindingTypeStats`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListFindingTypeStatsResponse: + Response for the ``ListFindingTypeStats`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_http_options() + request, metadata = self._interceptor.pre_list_finding_type_stats(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListFindingTypeStats._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListFindingTypeStatsResponse() + pb_resp = web_security_scanner.ListFindingTypeStatsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_finding_type_stats(resp) + return resp + + class _ListScanConfigs(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListScanConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListScanConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListScanConfigsResponse: + r"""Call the list scan configs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanConfigsRequest): + The request object. Request for the ``ListScanConfigs`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListScanConfigsResponse: + Response for the ``ListScanConfigs`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_http_options() + request, metadata = self._interceptor.pre_list_scan_configs(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListScanConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListScanConfigsResponse() + pb_resp = web_security_scanner.ListScanConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_configs(resp) + return resp + + class _ListScanRuns(_BaseWebSecurityScannerRestTransport._BaseListScanRuns, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListScanRuns") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListScanRunsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListScanRunsResponse: + r"""Call the list scan runs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanRunsRequest): + The request object. Request for the ``ListScanRuns`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListScanRunsResponse: + Response for the ``ListScanRuns`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_http_options() + request, metadata = self._interceptor.pre_list_scan_runs(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListScanRuns._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListScanRunsResponse() + pb_resp = web_security_scanner.ListScanRunsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_runs(resp) + return resp + + class _StartScanRun(_BaseWebSecurityScannerRestTransport._BaseStartScanRun, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.StartScanRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.StartScanRunRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_run.ScanRun: + r"""Call the start scan run method over HTTP. + + Args: + request (~.web_security_scanner.StartScanRunRequest): + The request object. Request for the ``StartScanRun`` method. + retry (google.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. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_http_options() + request, metadata = self._interceptor.pre_start_scan_run(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._StartScanRun._get_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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_start_scan_run(resp) + return resp + + class _StopScanRun(_BaseWebSecurityScannerRestTransport._BaseStopScanRun, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.StopScanRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.StopScanRunRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_run.ScanRun: + r"""Call the stop scan run method over HTTP. + + Args: + request (~.web_security_scanner.StopScanRunRequest): + The request object. Request for the ``StopScanRun`` method. + retry (google.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. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_http_options() + request, metadata = self._interceptor.pre_stop_scan_run(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._StopScanRun._get_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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_stop_scan_run(resp) + return resp + + class _UpdateScanConfig(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.UpdateScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.UpdateScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcw_scan_config.ScanConfig: + r"""Call the update scan config method over HTTP. + + Args: + request (~.web_security_scanner.UpdateScanConfigRequest): + The request object. Request for the ``UpdateScanConfigRequest`` method. + retry (google.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. + + Returns: + ~.gcw_scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_http_options() + request, metadata = self._interceptor.pre_update_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._UpdateScanConfig._get_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 = gcw_scan_config.ScanConfig() + pb_resp = gcw_scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_scan_config(resp) + return resp + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + gcw_scan_config.ScanConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + 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._DeleteScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + finding.Finding]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + scan_config.ScanConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + scan_run.ScanRun]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCrawledUrls(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFindingTypeStats(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScanConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScanRuns(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + scan_run.ScanRun]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StartScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + scan_run.ScanRun]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StopScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + gcw_scan_config.ScanConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WebSecurityScannerRestTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest_base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest_base.py new file mode 100644 index 000000000000..43a473271d0c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest_base.py @@ -0,0 +1,617 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 WebSecurityScannerTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + + +class _BaseWebSecurityScannerRestTransport(WebSecurityScannerTransport): + """Base REST backend transport for WebSecurityScanner. + + 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 = 'websecurityscanner.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: 'websecurityscanner.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 _BaseCreateScanConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1alpha/{parent=projects/*}/scanConfigs', + 'body': 'scan_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.CreateScanConfigRequest.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(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteScanConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1alpha/{name=projects/*/scanConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.DeleteScanConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetFinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.GetFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetFinding._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetScanConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/scanConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.GetScanConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetScanRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.GetScanRunRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCrawledUrls: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListCrawledUrlsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListFindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "filter" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListFindings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListFindingTypeStats: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListFindingTypeStatsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListScanConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*}/scanConfigs', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListScanConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListScanRuns: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/scanConfigs/*}/scanRuns', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListScanRunsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStartScanRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1alpha/{name=projects/*/scanConfigs/*}:start', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.StartScanRunRequest.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(_BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStopScanRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}:stop', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.StopScanRunRequest.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(_BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateScanConfig: + 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': '/v1alpha/{scan_config.name=projects/*/scanConfigs/*}', + 'body': 'scan_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.UpdateScanConfigRequest.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(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseWebSecurityScannerRestTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py new file mode 100644 index 000000000000..e83bf17f079c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .crawled_url import ( + CrawledUrl, +) +from .finding import ( + Finding, +) +from .finding_addon import ( + OutdatedLibrary, + ViolatingResource, + VulnerableHeaders, + VulnerableParameters, + Xss, +) +from .finding_type_stats import ( + FindingTypeStats, +) +from .scan_config import ( + ScanConfig, +) +from .scan_run import ( + ScanRun, +) +from .web_security_scanner import ( + CreateScanConfigRequest, + DeleteScanConfigRequest, + GetFindingRequest, + GetScanConfigRequest, + GetScanRunRequest, + ListCrawledUrlsRequest, + ListCrawledUrlsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListFindingTypeStatsRequest, + ListFindingTypeStatsResponse, + ListScanConfigsRequest, + ListScanConfigsResponse, + ListScanRunsRequest, + ListScanRunsResponse, + StartScanRunRequest, + StopScanRunRequest, + UpdateScanConfigRequest, +) + +__all__ = ( + 'CrawledUrl', + 'Finding', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanRun', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py new file mode 100644 index 000000000000..747e60e69d12 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.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.cloud.websecurityscanner.v1alpha', + manifest={ + 'CrawledUrl', + }, +) + + +class CrawledUrl(proto.Message): + r"""A CrawledUrl resource represents a URL that was crawled + during a ScanRun. Web Security Scanner Service crawls the web + applications, following all links within the scope of sites, to + find the URLs to test against. + + Attributes: + http_method (str): + Output only. The http method of the request + that was used to visit the URL, in uppercase. + url (str): + Output only. The URL that was crawled. + body (str): + Output only. The body of the request that was + used to visit the URL. + """ + + http_method: str = proto.Field( + proto.STRING, + number=1, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + body: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py new file mode 100644 index 000000000000..dad7099ea2cb --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner_v1alpha.types import finding_addon + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""A Finding resource represents a vulnerability instance + identified during a ScanRun. + + Attributes: + name (str): + The resource name of the Finding. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. + The finding IDs are generated by the system. + finding_type (google.cloud.websecurityscanner_v1alpha.types.Finding.FindingType): + The type of the Finding. + http_method (str): + The http method of the request that triggered + the vulnerability, in uppercase. + fuzzed_url (str): + The URL produced by the server-side fuzzer + and used in the request that triggered the + vulnerability. + body (str): + The body of the request that triggered the + vulnerability. + description (str): + The description of the vulnerability. + reproduction_url (str): + The URL containing human-readable payload + that user can leverage to reproduce the + vulnerability. + frame_url (str): + If the vulnerability was originated from + nested IFrame, the immediate parent IFrame is + reported. + final_url (str): + The URL where the browser lands when the + vulnerability is detected. + tracking_id (str): + The tracking ID uniquely identifies a + vulnerability instance across multiple ScanRuns. + outdated_library (google.cloud.websecurityscanner_v1alpha.types.OutdatedLibrary): + An addon containing information about + outdated libraries. + violating_resource (google.cloud.websecurityscanner_v1alpha.types.ViolatingResource): + An addon containing detailed information + regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, + etc. + vulnerable_headers (google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders): + An addon containing information about + vulnerable or missing HTTP headers. + vulnerable_parameters (google.cloud.websecurityscanner_v1alpha.types.VulnerableParameters): + An addon containing information about request + parameters which were found to be vulnerable. + xss (google.cloud.websecurityscanner_v1alpha.types.Xss): + An addon containing information reported for + an XSS, if any. + """ + class FindingType(proto.Enum): + r"""Types of Findings. + + Values: + FINDING_TYPE_UNSPECIFIED (0): + The invalid finding type. + MIXED_CONTENT (1): + A page that was served over HTTPS also + resources over HTTP. A man-in-the-middle + attacker could tamper with the HTTP resource and + gain full access to the website that loads the + resource or to monitor the actions taken by the + user. + OUTDATED_LIBRARY (2): + The version of an included library is known + to contain a security issue. The scanner checks + the version of library in use against a known + list of vulnerable libraries. False positives + are possible if the version detection fails or + if the library has been manually patched. + ROSETTA_FLASH (5): + This type of vulnerability occurs when the + value of a request parameter is reflected at the + beginning of the response, for example, in + requests using JSONP. Under certain + circumstances, an attacker may be able to supply + an alphanumeric-only Flash file in the + vulnerable parameter causing the browser to + execute the Flash file as if it originated on + the vulnerable server. + XSS_CALLBACK (3): + A cross-site scripting (XSS) bug is found via + JavaScript callback. For detailed explanations + on XSS, see + https://www.google.com/about/appsecurity/learning/xss/. + XSS_ERROR (4): + A potential cross-site scripting (XSS) bug + due to JavaScript breakage. In some + circumstances, the application under test might + modify the test string before it is parsed by + the browser. When the browser attempts to runs + this modified test string, it will likely break + and throw a JavaScript execution error, thus an + injection issue is occurring. However, it may + not be exploitable. Manual verification is + needed to see if the test string modifications + can be evaded and confirm that the issue is in + fact an XSS vulnerability. For detailed + explanations on XSS, see + https://www.google.com/about/appsecurity/learning/xss/. + CLEAR_TEXT_PASSWORD (6): + An application appears to be transmitting a + password field in clear text. An attacker can + eavesdrop network traffic and sniff the password + field. + INVALID_CONTENT_TYPE (7): + An application returns sensitive content with + an invalid content type, or without an + 'X-Content-Type-Options: nosniff' header. + XSS_ANGULAR_CALLBACK (8): + A cross-site scripting (XSS) vulnerability in + AngularJS module that occurs when a + user-provided string is interpolated by Angular. + INVALID_HEADER (9): + A malformed or invalid valued header. + MISSPELLED_SECURITY_HEADER_NAME (10): + Misspelled security header name. + MISMATCHING_SECURITY_HEADER_VALUES (11): + Mismatching values in a duplicate security + header. + """ + FINDING_TYPE_UNSPECIFIED = 0 + MIXED_CONTENT = 1 + OUTDATED_LIBRARY = 2 + ROSETTA_FLASH = 5 + XSS_CALLBACK = 3 + XSS_ERROR = 4 + CLEAR_TEXT_PASSWORD = 6 + INVALID_CONTENT_TYPE = 7 + XSS_ANGULAR_CALLBACK = 8 + INVALID_HEADER = 9 + MISSPELLED_SECURITY_HEADER_NAME = 10 + MISMATCHING_SECURITY_HEADER_VALUES = 11 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + finding_type: FindingType = proto.Field( + proto.ENUM, + number=2, + enum=FindingType, + ) + http_method: str = proto.Field( + proto.STRING, + number=3, + ) + fuzzed_url: str = proto.Field( + proto.STRING, + number=4, + ) + body: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + reproduction_url: str = proto.Field( + proto.STRING, + number=7, + ) + frame_url: str = proto.Field( + proto.STRING, + number=8, + ) + final_url: str = proto.Field( + proto.STRING, + number=9, + ) + tracking_id: str = proto.Field( + proto.STRING, + number=10, + ) + outdated_library: finding_addon.OutdatedLibrary = proto.Field( + proto.MESSAGE, + number=11, + message=finding_addon.OutdatedLibrary, + ) + violating_resource: finding_addon.ViolatingResource = proto.Field( + proto.MESSAGE, + number=12, + message=finding_addon.ViolatingResource, + ) + vulnerable_headers: finding_addon.VulnerableHeaders = proto.Field( + proto.MESSAGE, + number=15, + message=finding_addon.VulnerableHeaders, + ) + vulnerable_parameters: finding_addon.VulnerableParameters = proto.Field( + proto.MESSAGE, + number=13, + message=finding_addon.VulnerableParameters, + ) + xss: finding_addon.Xss = proto.Field( + proto.MESSAGE, + number=14, + message=finding_addon.Xss, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py new file mode 100644 index 000000000000..ed500844531b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner.v1alpha', + manifest={ + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableParameters', + 'VulnerableHeaders', + 'Xss', + }, +) + + +class OutdatedLibrary(proto.Message): + r"""Information reported for an outdated library. + + Attributes: + library_name (str): + The name of the outdated library. + version (str): + The version number. + learn_more_urls (MutableSequence[str]): + URLs to learn more information about the + vulnerabilities in the library. + """ + + library_name: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + learn_more_urls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ViolatingResource(proto.Message): + r"""Information regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, etc. + + Attributes: + content_type (str): + The MIME type of this resource. + resource_url (str): + URL of this violating resource. + """ + + content_type: str = proto.Field( + proto.STRING, + number=1, + ) + resource_url: str = proto.Field( + proto.STRING, + number=2, + ) + + +class VulnerableParameters(proto.Message): + r"""Information about vulnerable request parameters. + + Attributes: + parameter_names (MutableSequence[str]): + The vulnerable parameter names. + """ + + parameter_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class VulnerableHeaders(proto.Message): + r"""Information about vulnerable or missing HTTP Headers. + + Attributes: + headers (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders.Header]): + List of vulnerable headers. + missing_headers (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders.Header]): + List of missing headers. + """ + + class Header(proto.Message): + r"""Describes a HTTP Header. + + Attributes: + name (str): + Header name. + value (str): + Header value. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + headers: MutableSequence[Header] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Header, + ) + missing_headers: MutableSequence[Header] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Header, + ) + + +class Xss(proto.Message): + r"""Information reported for an XSS. + + Attributes: + stack_traces (MutableSequence[str]): + Stack traces leading to the point where the + XSS occurred. + error_message (str): + An error message generated by a javascript + breakage. + """ + + stack_traces: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py new file mode 100644 index 000000000000..99f4c21be8ba --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.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 + +from google.cloud.websecurityscanner_v1alpha.types import finding + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'FindingTypeStats', + }, +) + + +class FindingTypeStats(proto.Message): + r"""A FindingTypeStats resource represents stats regarding a + specific FindingType of Findings under a given ScanRun. + + Attributes: + finding_type (google.cloud.websecurityscanner_v1alpha.types.Finding.FindingType): + The finding type associated with the stats. + finding_count (int): + The count of findings belonging to this + finding type. + """ + + finding_type: finding.Finding.FindingType = proto.Field( + proto.ENUM, + number=1, + enum=finding.Finding.FindingType, + ) + finding_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py new file mode 100644 index 000000000000..57b9b8dfc9aa --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py @@ -0,0 +1,268 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner_v1alpha.types import scan_run +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'ScanConfig', + }, +) + + +class ScanConfig(proto.Message): + r"""A ScanConfig resource contains the configurations to launch a + scan. next id: 12 + + Attributes: + name (str): + The resource name of the ScanConfig. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + The ScanConfig IDs are generated by the system. + display_name (str): + Required. The user provided display name of + the ScanConfig. + max_qps (int): + The maximum QPS during scanning. A valid value ranges from 5 + to 20 inclusively. If the field is unspecified or its value + is set 0, server will default to 15. Other values outside of + [5, 20] range will be rejected with INVALID_ARGUMENT error. + starting_urls (MutableSequence[str]): + Required. The starting URLs from which the + scanner finds site pages. + authentication (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication): + The authentication configuration. If + specified, service will use the authentication + configuration during scanning. + user_agent (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.UserAgent): + The user agent used during scanning. + blacklist_patterns (MutableSequence[str]): + The blacklist URL patterns as described in + https://cloud.google.com/security-scanner/docs/excluded-urls + schedule (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Schedule): + The schedule of the ScanConfig. + target_platforms (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.ScanConfig.TargetPlatform]): + Set of Cloud Platforms targeted by the scan. If empty, + APP_ENGINE will be used as a default. + latest_run (google.cloud.websecurityscanner_v1alpha.types.ScanRun): + Latest ScanRun if available. + """ + class UserAgent(proto.Enum): + r"""Type of user agents used for scanning. + + Values: + USER_AGENT_UNSPECIFIED (0): + The user agent is unknown. Service will default to + CHROME_LINUX. + CHROME_LINUX (1): + Chrome on Linux. This is the service default + if unspecified. + CHROME_ANDROID (2): + Chrome on Android. + SAFARI_IPHONE (3): + Safari on IPhone. + """ + USER_AGENT_UNSPECIFIED = 0 + CHROME_LINUX = 1 + CHROME_ANDROID = 2 + SAFARI_IPHONE = 3 + + class TargetPlatform(proto.Enum): + r"""Cloud platforms supported by Cloud Web Security Scanner. + + Values: + TARGET_PLATFORM_UNSPECIFIED (0): + The target platform is unknown. Requests with this enum + value will be rejected with INVALID_ARGUMENT error. + APP_ENGINE (1): + Google App Engine service. + COMPUTE (2): + Google Compute Engine service. + """ + TARGET_PLATFORM_UNSPECIFIED = 0 + APP_ENGINE = 1 + COMPUTE = 2 + + class Authentication(proto.Message): + r"""Scan authentication configuration. + + 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_account (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication.GoogleAccount): + Authentication using a Google account. + + This field is a member of `oneof`_ ``authentication``. + custom_account (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication.CustomAccount): + Authentication using a custom account. + + This field is a member of `oneof`_ ``authentication``. + """ + + class GoogleAccount(proto.Message): + r"""Describes authentication configuration that uses a Google + account. + + Attributes: + username (str): + Required. The user name of the Google + account. + password (str): + Required. Input only. The password of the + Google account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + """ + + username: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + + class CustomAccount(proto.Message): + r"""Describes authentication configuration that uses a custom + account. + + Attributes: + username (str): + Required. The user name of the custom + account. + password (str): + Required. Input only. The password of the + custom account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + login_url (str): + Required. The login form URL of the website. + """ + + username: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + login_url: str = proto.Field( + proto.STRING, + number=3, + ) + + google_account: 'ScanConfig.Authentication.GoogleAccount' = proto.Field( + proto.MESSAGE, + number=1, + oneof='authentication', + message='ScanConfig.Authentication.GoogleAccount', + ) + custom_account: 'ScanConfig.Authentication.CustomAccount' = proto.Field( + proto.MESSAGE, + number=2, + oneof='authentication', + message='ScanConfig.Authentication.CustomAccount', + ) + + class Schedule(proto.Message): + r"""Scan schedule configuration. + + Attributes: + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + A timestamp indicates when the next run will + be scheduled. The value is refreshed by the + server after each run. If unspecified, it will + default to current server time, which means the + scan will be scheduled to start immediately. + interval_duration_days (int): + Required. The duration of time between + executions in days. + """ + + schedule_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + interval_duration_days: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + max_qps: int = proto.Field( + proto.INT32, + number=3, + ) + starting_urls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + authentication: Authentication = proto.Field( + proto.MESSAGE, + number=5, + message=Authentication, + ) + user_agent: UserAgent = proto.Field( + proto.ENUM, + number=6, + enum=UserAgent, + ) + blacklist_patterns: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + schedule: Schedule = proto.Field( + proto.MESSAGE, + number=8, + message=Schedule, + ) + target_platforms: MutableSequence[TargetPlatform] = proto.RepeatedField( + proto.ENUM, + number=9, + enum=TargetPlatform, + ) + latest_run: scan_run.ScanRun = proto.Field( + proto.MESSAGE, + number=11, + message=scan_run.ScanRun, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py new file mode 100644 index 000000000000..838665badb35 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py @@ -0,0 +1,159 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner.v1alpha', + manifest={ + 'ScanRun', + }, +) + + +class ScanRun(proto.Message): + r"""A ScanRun is a output-only resource representing an actual + run of the scan. + + Attributes: + name (str): + The resource name of the ScanRun. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + The ScanRun IDs are generated by the system. + execution_state (google.cloud.websecurityscanner_v1alpha.types.ScanRun.ExecutionState): + The execution state of the ScanRun. + result_state (google.cloud.websecurityscanner_v1alpha.types.ScanRun.ResultState): + The result state of the ScanRun. This field + is only available after the execution state + reaches "FINISHED". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the ScanRun started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the ScanRun reached + termination state - that the ScanRun is either + finished or stopped by user. + urls_crawled_count (int): + The number of URLs crawled during this + ScanRun. If the scan is in progress, the value + represents the number of URLs crawled up to now. + urls_tested_count (int): + The number of URLs tested during this + ScanRun. If the scan is in progress, the value + represents the number of URLs tested up to now. + The number of URLs tested is usually larger than + the number URLS crawled because typically a + crawled URL is tested with multiple test + payloads. + has_vulnerabilities (bool): + Whether the scan run has found any + vulnerabilities. + progress_percent (int): + The percentage of total completion ranging + from 0 to 100. If the scan is in queue, the + value is 0. If the scan is running, the value + ranges from 0 to 100. If the scan is finished, + the value is 100. + """ + class ExecutionState(proto.Enum): + r"""Types of ScanRun execution state. + + Values: + EXECUTION_STATE_UNSPECIFIED (0): + Represents an invalid state caused by + internal server error. This value should never + be returned. + QUEUED (1): + The scan is waiting in the queue. + SCANNING (2): + The scan is in progress. + FINISHED (3): + The scan is either finished or stopped by + user. + """ + EXECUTION_STATE_UNSPECIFIED = 0 + QUEUED = 1 + SCANNING = 2 + FINISHED = 3 + + class ResultState(proto.Enum): + r"""Types of ScanRun result state. + + Values: + RESULT_STATE_UNSPECIFIED (0): + Default value. This value is returned when + the ScanRun is not yet finished. + SUCCESS (1): + The scan finished without errors. + ERROR (2): + The scan finished with errors. + KILLED (3): + The scan was terminated by user. + """ + RESULT_STATE_UNSPECIFIED = 0 + SUCCESS = 1 + ERROR = 2 + KILLED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + execution_state: ExecutionState = proto.Field( + proto.ENUM, + number=2, + enum=ExecutionState, + ) + result_state: ResultState = proto.Field( + proto.ENUM, + number=3, + enum=ResultState, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + urls_crawled_count: int = proto.Field( + proto.INT64, + number=6, + ) + urls_tested_count: int = proto.Field( + proto.INT64, + number=7, + ) + has_vulnerabilities: bool = proto.Field( + proto.BOOL, + number=8, + ) + progress_percent: int = proto.Field( + proto.INT32, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py new file mode 100644 index 000000000000..2500ac7896a1 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats as gcw_finding_type_stats +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetScanConfigRequest', + 'ListScanConfigsRequest', + 'UpdateScanConfigRequest', + 'ListScanConfigsResponse', + 'StartScanRunRequest', + 'GetScanRunRequest', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StopScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'GetFindingRequest', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + }, +) + + +class CreateScanConfigRequest(proto.Message): + r"""Request for the ``CreateScanConfig`` method. + + Attributes: + parent (str): + Required. The parent resource name where the + scan is created, which should be a project + resource name in the format + 'projects/{projectId}'. + scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): + Required. The ScanConfig to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + scan_config: gcw_scan_config.ScanConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + + +class DeleteScanConfigRequest(proto.Message): + r"""Request for the ``DeleteScanConfig`` method. + + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be deleted. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanConfigRequest(proto.Message): + r"""Request for the ``GetScanConfig`` method. + + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanConfigsRequest(proto.Message): + r"""Request for the ``ListScanConfigs`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a project resource name in the format + 'projects/{projectId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanConfigs to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class UpdateScanConfigRequest(proto.Message): + r"""Request for the ``UpdateScanConfigRequest`` method. + + Attributes: + scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): + Required. The ScanConfig to be updated. The + name field must be set to identify the resource + to be updated. The values of fields not covered + by the mask will be ignored. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For the + ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + """ + + scan_config: gcw_scan_config.ScanConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ListScanConfigsResponse(proto.Message): + r"""Response for the ``ListScanConfigs`` method. + + Attributes: + scan_configs (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.ScanConfig]): + The list of ScanConfigs returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_configs: MutableSequence[gcw_scan_config.ScanConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_scan_config.ScanConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class StartScanRunRequest(proto.Message): + r"""Request for the ``StartScanRun`` method. + + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be used. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanRunRequest(proto.Message): + r"""Request for the ``GetScanRun`` method. + + Attributes: + name (str): + Required. The resource name of the ScanRun to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanRunsRequest(proto.Message): + r"""Request for the ``ListScanRuns`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanRuns to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListScanRunsResponse(proto.Message): + r"""Response for the ``ListScanRuns`` method. + + Attributes: + scan_runs (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.ScanRun]): + The list of ScanRuns returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_runs: MutableSequence[scan_run.ScanRun] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=scan_run.ScanRun, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class StopScanRunRequest(proto.Message): + r"""Request for the ``StopScanRun`` method. + + Attributes: + name (str): + Required. The resource name of the ScanRun to + be stopped. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCrawledUrlsRequest(proto.Message): + r"""Request for the ``ListCrawledUrls`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of CrawledUrls to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCrawledUrlsResponse(proto.Message): + r"""Response for the ``ListCrawledUrls`` method. + + Attributes: + crawled_urls (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.CrawledUrl]): + The list of CrawledUrls returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + crawled_urls: MutableSequence[crawled_url.CrawledUrl] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=crawled_url.CrawledUrl, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFindingRequest(proto.Message): + r"""Request for the ``GetFinding`` method. + + Attributes: + name (str): + Required. The resource name of the Finding to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request for the ``ListFindings`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + filter (str): + Required. The filter expression. The expression must be in + the format: . Supported field: 'finding_type'. Supported + operator: '='. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of Findings to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response for the ``ListFindings`` method. + + Attributes: + findings (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.Finding]): + The list of Findings returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + findings: MutableSequence[finding.Finding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=finding.Finding, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFindingTypeStatsRequest(proto.Message): + r"""Request for the ``ListFindingTypeStats`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingTypeStatsResponse(proto.Message): + r"""Response for the ``ListFindingTypeStats`` method. + + Attributes: + finding_type_stats (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.FindingTypeStats]): + The list of FindingTypeStats returned. + """ + + finding_type_stats: MutableSequence[gcw_finding_type_stats.FindingTypeStats] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_finding_type_stats.FindingTypeStats, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/mypy.ini b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/noxfile.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/noxfile.py new file mode 100644 index 000000000000..9ddc35ffe522 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner' + +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/cloud/websecurityscanner_v1alpha/', + '--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/cloud/websecurityscanner_v1alpha/', + '--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-cloud-websecurityscanner/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json new file mode 100644 index 000000000000..c87e0efb514b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json @@ -0,0 +1,2126 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.websecurityscanner.v1alpha", + "version": "v1alpha" + } + ], + "language": "PYTHON", + "name": "google-cloud-websecurityscanner", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.create_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.CreateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "CreateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "scan_config", + "type": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", + "shortName": "create_scan_config" + }, + "description": "Sample for CreateScanConfig", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.create_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.CreateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "CreateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "scan_config", + "type": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", + "shortName": "create_scan_config" + }, + "description": "Sample for CreateScanConfig", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.delete_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.DeleteScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "DeleteScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_scan_config" + }, + "description": "Sample for DeleteScanConfig", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.delete_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.DeleteScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "DeleteScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_scan_config" + }, + "description": "Sample for DeleteScanConfig", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.get_finding", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetFinding", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.Finding", + "shortName": "get_finding" + }, + "description": "Sample for GetFinding", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.get_finding", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetFinding", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.Finding", + "shortName": "get_finding" + }, + "description": "Sample for GetFinding", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.get_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", + "shortName": "get_scan_config" + }, + "description": "Sample for GetScanConfig", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.get_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", + "shortName": "get_scan_config" + }, + "description": "Sample for GetScanConfig", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.get_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", + "shortName": "get_scan_run" + }, + "description": "Sample for GetScanRun", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.get_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", + "shortName": "get_scan_run" + }, + "description": "Sample for GetScanRun", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_crawled_urls", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListCrawledUrls", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListCrawledUrls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager", + "shortName": "list_crawled_urls" + }, + "description": "Sample for ListCrawledUrls", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_crawled_urls", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListCrawledUrls", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListCrawledUrls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsPager", + "shortName": "list_crawled_urls" + }, + "description": "Sample for ListCrawledUrls", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_finding_type_stats", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListFindingTypeStats", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindingTypeStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse", + "shortName": "list_finding_type_stats" + }, + "description": "Sample for ListFindingTypeStats", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_finding_type_stats", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListFindingTypeStats", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindingTypeStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse", + "shortName": "list_finding_type_stats" + }, + "description": "Sample for ListFindingTypeStats", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListFindings", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest" + }, + { + "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, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_findings", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListFindings", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest" + }, + { + "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, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_scan_configs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListScanConfigs", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsAsyncPager", + "shortName": "list_scan_configs" + }, + "description": "Sample for ListScanConfigs", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_scan_configs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListScanConfigs", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsPager", + "shortName": "list_scan_configs" + }, + "description": "Sample for ListScanConfigs", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_scan_runs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListScanRuns", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsAsyncPager", + "shortName": "list_scan_runs" + }, + "description": "Sample for ListScanRuns", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_scan_runs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListScanRuns", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsPager", + "shortName": "list_scan_runs" + }, + "description": "Sample for ListScanRuns", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.start_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.StartScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StartScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", + "shortName": "start_scan_run" + }, + "description": "Sample for StartScanRun", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.start_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.StartScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StartScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", + "shortName": "start_scan_run" + }, + "description": "Sample for StartScanRun", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.stop_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.StopScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StopScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", + "shortName": "stop_scan_run" + }, + "description": "Sample for StopScanRun", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.stop_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.StopScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StopScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", + "shortName": "stop_scan_run" + }, + "description": "Sample for StopScanRun", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.update_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.UpdateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "UpdateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest" + }, + { + "name": "scan_config", + "type": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig" + }, + { + "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, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", + "shortName": "update_scan_config" + }, + "description": "Sample for UpdateScanConfig", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.update_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.UpdateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "UpdateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest" + }, + { + "name": "scan_config", + "type": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig" + }, + { + "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, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", + "shortName": "update_scan_config" + }, + "description": "Sample for UpdateScanConfig", + "file": "websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py new file mode 100644 index 000000000000..9e5260326eaf --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_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 CreateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1alpha.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1alpha.CreateScanConfigRequest( + parent="parent_value", + scan_config=scan_config, + ) + + # Make the request + response = await client.create_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py new file mode 100644 index 000000000000..badf5b41523f --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_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 CreateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1alpha.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1alpha.CreateScanConfigRequest( + parent="parent_value", + scan_config=scan_config, + ) + + # Make the request + response = client.create_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py new file mode 100644 index 000000000000..07a1d176387e --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_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 DeleteScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.DeleteScanConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_scan_config(request=request) + + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py new file mode 100644 index 000000000000..e2ddc235ebb3 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_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 DeleteScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.DeleteScanConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_scan_config(request=request) + + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py new file mode 100644 index 000000000000..a74c0e27c557 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_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 GetFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_get_finding(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetFindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_finding(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py new file mode 100644 index 000000000000..04db260be284 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_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 GetFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_get_finding(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetFindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_finding(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py new file mode 100644 index 000000000000..38c2eceaaddf --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_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 GetScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetScanConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py new file mode 100644 index 000000000000..1fb688bf1790 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_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 GetScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetScanConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py new file mode 100644 index 000000000000..e9e81d3d3418 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_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 GetScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py new file mode 100644 index 000000000000..0cb2bb5b111d --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_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 GetScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.GetScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.get_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py new file mode 100644 index 000000000000..f84eb09bc9d9 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListCrawledUrlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py new file mode 100644 index 000000000000..98e151f40d16 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListCrawledUrlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py new file mode 100644 index 000000000000..7ef632849883 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListFindingTypeStatsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py new file mode 100644 index 000000000000..7f041e22abfa --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListFindingTypeStatsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py new file mode 100644 index 000000000000..9325d57de8b3 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_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 ListFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_list_findings(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListFindingsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py new file mode 100644 index 000000000000..1723efb8b714 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_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 ListFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_list_findings(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListFindingsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py new file mode 100644 index 000000000000..1c052cece721 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListScanConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py new file mode 100644 index 000000000000..4388366def42 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListScanConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py new file mode 100644 index 000000000000..84097f7141f9 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_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 ListScanRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListScanRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py new file mode 100644 index 000000000000..918a3d1cf72a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_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 ListScanRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.ListScanRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py new file mode 100644 index 000000000000..f1201405b659 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_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 StartScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.StartScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.start_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py new file mode 100644 index 000000000000..b5b14ef2b99c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_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 StartScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.StartScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.start_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py new file mode 100644 index 000000000000..1f9f34d62eed --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_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 StopScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.StopScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.stop_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py new file mode 100644 index 000000000000..55ae40e93966 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_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 StopScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1alpha.StopScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.stop_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py new file mode 100644 index 000000000000..da3f2a27ba86 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +async def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1alpha.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1alpha.UpdateScanConfigRequest( + scan_config=scan_config, + ) + + # Make the request + response = await client.update_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py new file mode 100644 index 000000000000..d8a2a522e64c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1alpha + + +def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1alpha.WebSecurityScannerClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1alpha.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1alpha.UpdateScanConfigRequest( + scan_config=scan_config, + ) + + # Make the request + response = client.update_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py new file mode 100644 index 000000000000..cbe5261ddc2a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py @@ -0,0 +1,188 @@ +#! /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 websecurityscannerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_scan_config': ('parent', 'scan_config', ), + 'delete_scan_config': ('name', ), + 'get_finding': ('name', ), + 'get_scan_config': ('name', ), + 'get_scan_run': ('name', ), + 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_finding_type_stats': ('parent', ), + 'list_scan_configs': ('parent', 'page_token', 'page_size', ), + 'list_scan_runs': ('parent', 'page_token', 'page_size', ), + 'start_scan_run': ('name', ), + 'stop_scan_run': ('name', ), + 'update_scan_config': ('scan_config', '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=websecurityscannerCallTransformer(), +): + """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 websecurityscanner 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-cloud-websecurityscanner/v1alpha/setup.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/setup.py new file mode 100644 index 000000000000..b89eea40fd8f --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner' + + +description = "Google Cloud Websecurityscanner API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/websecurityscanner/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-cloud-websecurityscanner" + +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-cloud-websecurityscanner/v1alpha/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/tests/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/tests/unit/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__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-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py new file mode 100644 index 000000000000..4d364f713f88 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py @@ -0,0 +1,11488 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1alpha.services.web_security_scanner import WebSecurityScannerAsyncClient +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import transports +from google.cloud.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import finding_addon +from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_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 WebSecurityScannerClient._get_default_mtls_endpoint(None) is None + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WebSecurityScannerClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + WebSecurityScannerClient._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 WebSecurityScannerClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WebSecurityScannerClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WebSecurityScannerClient._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 WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, False) is None + assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, True) is mock_default_cert_source + assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE + default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert WebSecurityScannerClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + assert WebSecurityScannerClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + WebSecurityScannerClient._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 WebSecurityScannerClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert WebSecurityScannerClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert WebSecurityScannerClient._get_universe_domain(None, None) == WebSecurityScannerClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + WebSecurityScannerClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WebSecurityScannerClient, "grpc"), + (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), +]) +def test_web_security_scanner_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 == ( + 'websecurityscanner.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://websecurityscanner.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WebSecurityScannerGrpcTransport, "grpc"), + (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WebSecurityScannerRestTransport, "rest"), +]) +def test_web_security_scanner_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", [ + (WebSecurityScannerClient, "grpc"), + (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), +]) +def test_web_security_scanner_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 == ( + 'websecurityscanner.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://websecurityscanner.googleapis.com' + ) + + +def test_web_security_scanner_client_get_transport_class(): + transport = WebSecurityScannerClient.get_transport_class() + available_transports = [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerRestTransport, + ] + assert transport in available_transports + + transport = WebSecurityScannerClient.get_transport_class("grpc") + assert transport == transports.WebSecurityScannerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), +]) +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_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(WebSecurityScannerClient, '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(WebSecurityScannerClient, '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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "true"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "false"), +]) +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_web_security_scanner_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", [ + WebSecurityScannerClient, WebSecurityScannerAsyncClient +]) +@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_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", [ + WebSecurityScannerClient, WebSecurityScannerAsyncClient +]) +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE + default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WebSecurityScannerClient._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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), +]) +def test_web_security_scanner_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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", None), +]) +def test_web_security_scanner_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_web_security_scanner_client_client_options_from_dict(): + with mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WebSecurityScannerClient( + 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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_web_security_scanner_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( + "websecurityscanner.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="websecurityscanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.CreateScanConfigRequest, + dict, +]) +def test_create_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + response = client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.CreateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +def test_create_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.CreateScanConfigRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.CreateScanConfigRequest( + parent='parent_value', + ) + +def test_create_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + request = {} + client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + )) + response = await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.CreateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +@pytest.mark.asyncio +async def test_create_scan_config_async_from_dict(): + await test_create_scan_config_async(request_type=dict) + +def test_create_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_scan_config( + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(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].scan_config + mock_val = gcw_scan_config.ScanConfig(name='name_value') + assert arg == mock_val + + +def test_create_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_scan_config( + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(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].scan_config + mock_val = gcw_scan_config.ScanConfig(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.DeleteScanConfigRequest, + dict, +]) +def test_delete_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.DeleteScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.DeleteScanConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.DeleteScanConfigRequest( + name='name_value', + ) + +def test_delete_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + request = {} + client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.DeleteScanConfigRequest() + 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_scan_config_async_from_dict(): + await test_delete_scan_config_async(request_type=dict) + +def test_delete_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = None + client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__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_scan_config( + 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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__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_scan_config( + 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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanConfigRequest, + dict, +]) +def test_get_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + response = client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +def test_get_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.GetScanConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanConfigRequest( + name='name_value', + ) + +def test_get_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc + request = {} + client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + )) + response = await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +@pytest.mark.asyncio +async def test_get_scan_config_async_from_dict(): + await test_get_scan_config_async(request_type=dict) + +def test_get_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scan_config( + 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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scan_config( + 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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanConfigsRequest, + dict, +]) +def test_list_scan_configs(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListScanConfigsRequest( + 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_scan_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_scan_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_scan_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_configs] = mock_rpc + request = {} + client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_configs(request) + + # Establish that a new wrapper 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_scan_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_configs in client._client._transport._wrapped_methods + + # 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_scan_configs] = mock_rpc + + request = {} + await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scan_configs(request) + + # Establish that a new wrapper 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_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_configs_async_from_dict(): + await test_list_scan_configs_async(request_type=dict) + +def test_list_scan_configs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanConfigsResponse() + client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_configs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_configs_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scan_configs( + 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_scan_configs_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_scan_configs_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scan_configs( + 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_scan_configs_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + + +def test_list_scan_configs_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_configs(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, scan_config.ScanConfig) + for i in results) +def test_list_scan_configs_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_configs(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_scan_configs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_configs(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, scan_config.ScanConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_scan_configs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + 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_scan_configs(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", [ + web_security_scanner.UpdateScanConfigRequest, + dict, +]) +def test_update_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + response = client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.UpdateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +def test_update_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.UpdateScanConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.UpdateScanConfigRequest( + ) + +def test_update_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + request = {} + client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + )) + response = await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.UpdateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +@pytest.mark.asyncio +async def test_update_scan_config_async_from_dict(): + await test_update_scan_config_async(request_type=dict) + +def test_update_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'scan_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'scan_config.name=name_value', + ) in kw['metadata'] + + +def test_update_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_scan_config( + scan_config=gcw_scan_config.ScanConfig(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].scan_config + mock_val = gcw_scan_config.ScanConfig(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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_scan_config( + scan_config=gcw_scan_config.ScanConfig(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].scan_config + mock_val = gcw_scan_config.ScanConfig(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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.StartScanRunRequest, + dict, +]) +def test_start_scan_run(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StartScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_start_scan_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.StartScanRunRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.start_scan_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest( + name='name_value', + ) + +def test_start_scan_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc + request = {} + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.start_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.start_scan_run in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.start_scan_run] = mock_rpc + + request = {} + await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.start_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StartScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_start_scan_run_async_from_dict(): + await test_start_scan_run_async(request_type=dict) + +def test_start_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_scan_run( + 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_start_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_start_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_scan_run( + 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_start_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanRunRequest, + dict, +]) +def test_get_scan_run(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_get_scan_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.GetScanRunRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_scan_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest( + name='name_value', + ) + +def test_get_scan_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc + request = {} + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_run(request) + + # Establish that a new wrapper 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_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_run in client._client._transport._wrapped_methods + + # 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_scan_run] = mock_rpc + + request = {} + await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scan_run(request) + + # Establish that a new wrapper 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_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_get_scan_run_async_from_dict(): + await test_get_scan_run_async(request_type=dict) + +def test_get_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scan_run( + 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_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scan_run( + 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_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanRunsRequest, + dict, +]) +def test_list_scan_runs(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_runs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListScanRunsRequest( + 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_scan_runs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_scan_runs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_scan_runs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_runs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_runs] = mock_rpc + request = {} + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_runs(request) + + # Establish that a new wrapper 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_scan_runs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_runs in client._client._transport._wrapped_methods + + # 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_scan_runs] = mock_rpc + + request = {} + await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scan_runs(request) + + # Establish that a new wrapper 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_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_runs_async_from_dict(): + await test_list_scan_runs_async(request_type=dict) + +def test_list_scan_runs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanRunsResponse() + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_runs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_runs_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scan_runs( + 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_scan_runs_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_scan_runs_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scan_runs( + 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_scan_runs_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + + +def test_list_scan_runs_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_runs(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, scan_run.ScanRun) + for i in results) +def test_list_scan_runs_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_runs(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_scan_runs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_runs(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, scan_run.ScanRun) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_scan_runs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + 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_scan_runs(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", [ + web_security_scanner.StopScanRunRequest, + dict, +]) +def test_stop_scan_run(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StopScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_stop_scan_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.StopScanRunRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.stop_scan_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest( + name='name_value', + ) + +def test_stop_scan_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc + request = {} + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.stop_scan_run in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.stop_scan_run] = mock_rpc + + request = {} + await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.stop_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StopScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_stop_scan_run_async_from_dict(): + await test_stop_scan_run_async(request_type=dict) + +def test_stop_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_scan_run( + 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_stop_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_stop_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_scan_run( + 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_stop_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListCrawledUrlsRequest, + dict, +]) +def test_list_crawled_urls(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListCrawledUrlsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_crawled_urls_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListCrawledUrlsRequest( + 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_crawled_urls), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_crawled_urls(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_crawled_urls_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_crawled_urls in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_crawled_urls] = mock_rpc + request = {} + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crawled_urls(request) + + # Establish that a new wrapper 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_crawled_urls_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_crawled_urls in client._client._transport._wrapped_methods + + # 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_crawled_urls] = mock_rpc + + request = {} + await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_crawled_urls(request) + + # Establish that a new wrapper 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_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListCrawledUrlsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_from_dict(): + await test_list_crawled_urls_async(request_type=dict) + +def test_list_crawled_urls_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crawled_urls_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crawled_urls_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_crawled_urls( + 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_crawled_urls_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_crawled_urls_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_crawled_urls( + 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_crawled_urls_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + + +def test_list_crawled_urls_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crawled_urls(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, crawled_url.CrawledUrl) + for i in results) +def test_list_crawled_urls_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + 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_crawled_urls(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", [ + web_security_scanner.GetFindingRequest, + dict, +]) +def test_get_finding(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + finding_type=finding.Finding.FindingType.MIXED_CONTENT, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + ) + response = client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +def test_get_finding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.GetFindingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetFindingRequest( + name='name_value', + ) + +def test_get_finding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_finding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc + request = {} + client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_finding(request) + + # Establish that a new wrapper 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_finding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # 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_finding] = mock_rpc + + request = {} + await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_finding(request) + + # Establish that a new wrapper 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_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + finding_type=finding.Finding.FindingType.MIXED_CONTENT, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + )) + response = await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +@pytest.mark.asyncio +async def test_get_finding_async_from_dict(): + await test_get_finding_async(request_type=dict) + +def test_get_finding_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = finding.Finding() + client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_finding( + 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_finding_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_finding_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_finding( + 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_finding_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_findings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListFindingsRequest( + 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_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_findings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_findings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_findings] = mock_rpc + request = {} + client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_findings(request) + + # Establish that a new wrapper 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_findings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_findings in client._client._transport._wrapped_methods + + # 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_findings] = mock_rpc + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_findings(request) + + # Establish that a new wrapper 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_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + +def test_list_findings_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingsResponse() + client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_findings_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_findings_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_findings( + 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_findings_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_findings( + 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_findings_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_findings_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_findings(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, finding.Finding) + for i in results) +def test_list_findings_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_findings(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_findings_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_findings(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, finding.Finding) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + 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_findings(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", [ + web_security_scanner.ListFindingTypeStatsRequest, + dict, +]) +def test_list_finding_type_stats(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse( + ) + response = client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingTypeStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +def test_list_finding_type_stats_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListFindingTypeStatsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_finding_type_stats(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest( + parent='parent_value', + ) + +def test_list_finding_type_stats_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_finding_type_stats in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_finding_type_stats] = mock_rpc + request = {} + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_finding_type_stats(request) + + # Establish that a new wrapper 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_finding_type_stats_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_finding_type_stats in client._client._transport._wrapped_methods + + # 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_finding_type_stats] = mock_rpc + + request = {} + await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_finding_type_stats(request) + + # Establish that a new wrapper 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_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( + )) + response = await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingTypeStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_async_from_dict(): + await test_list_finding_type_stats_async(request_type=dict) + +def test_list_finding_type_stats_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_type_stats_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_type_stats_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_finding_type_stats( + 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_finding_type_stats_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_finding_type_stats_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_finding_type_stats( + 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_finding_type_stats_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + + +def test_create_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + + request = {} + client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_scan_config(request) + + # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.CreateScanConfigRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_config._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_scan_config._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_scan_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "scanConfig", ))) + + +def test_create_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + + # 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', + scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*}/scanConfigs" % client.transport._host, args[1]) + + +def test_create_scan_config_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + + +def test_delete_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + + request = {} + client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_scan_config(request) + + # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.DeleteScanConfigRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_scan_config._get_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_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + 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 + + response = client.delete_scan_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/scanConfigs/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 + + client.delete_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_scan_config_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + + +def test_get_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc + + request = {} + client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_config(request) + + # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.GetScanConfigRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_scan_config._get_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_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_config.ScanConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_scan_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = scan_config.ScanConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) + + +def test_get_scan_config_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + + +def test_list_scan_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_configs] = mock_rpc + + request = {} + client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_configs(request) + + # Establish 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_scan_configs_rest_required_fields(request_type=web_security_scanner.ListScanConfigsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_configs._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_scan_configs._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_scan_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_scan_configs_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_scan_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_scan_configs_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanConfigsResponse() + + # 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_scan_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*}/scanConfigs" % client.transport._host, args[1]) + + +def test_list_scan_configs_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + + +def test_list_scan_configs_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListScanConfigsResponse.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_scan_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_config.ScanConfig) + for i in results) + + pages = list(client.list_scan_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + + request = {} + client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_scan_config(request) + + # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.UpdateScanConfigRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_config._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_scan_config._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_scan_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("scanConfig", "updateMask", ))) + + +def test_update_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{scan_config.name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) + + +def test_update_scan_config_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_start_scan_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc + + request = {} + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.start_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_start_scan_run_rest_required_fields(request_type=web_security_scanner.StartScanRunRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).start_scan_run._get_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()).start_scan_run._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.start_scan_run(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_start_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.start_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_start_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.start_scan_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*}:start" % client.transport._host, args[1]) + + +def test_start_scan_run_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + + +def test_get_scan_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc + + request = {} + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_run(request) + + # Establish 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_scan_run_rest_required_fields(request_type=web_security_scanner.GetScanRunRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_scan_run._get_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_scan_run._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_scan_run(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_scan_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}" % client.transport._host, args[1]) + + +def test_get_scan_run_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + + +def test_list_scan_runs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_runs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_runs] = mock_rpc + + request = {} + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_runs(request) + + # Establish 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_scan_runs_rest_required_fields(request_type=web_security_scanner.ListScanRunsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_runs._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_scan_runs._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanRunsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_scan_runs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_scan_runs_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_scan_runs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_scan_runs_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanRunsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_scan_runs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/scanConfigs/*}/scanRuns" % client.transport._host, args[1]) + + +def test_list_scan_runs_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + + +def test_list_scan_runs_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListScanRunsResponse.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/scanConfigs/sample2'} + + pager = client.list_scan_runs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_run.ScanRun) + for i in results) + + pages = list(client.list_scan_runs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_stop_scan_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc + + request = {} + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_stop_scan_run_rest_required_fields(request_type=web_security_scanner.StopScanRunRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).stop_scan_run._get_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()).stop_scan_run._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.stop_scan_run(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_stop_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.stop_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_stop_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.stop_scan_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}:stop" % client.transport._host, args[1]) + + +def test_stop_scan_run_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + + +def test_list_crawled_urls_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_crawled_urls in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_crawled_urls] = mock_rpc + + request = {} + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crawled_urls(request) + + # Establish 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_crawled_urls_rest_required_fields(request_type=web_security_scanner.ListCrawledUrlsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_crawled_urls._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_crawled_urls._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListCrawledUrlsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_crawled_urls(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_crawled_urls_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_crawled_urls._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_crawled_urls_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListCrawledUrlsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} + + # 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_crawled_urls(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls" % client.transport._host, args[1]) + + +def test_list_crawled_urls_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + + +def test_list_crawled_urls_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListCrawledUrlsResponse.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/scanConfigs/sample2/scanRuns/sample3'} + + pager = client.list_crawled_urls(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, crawled_url.CrawledUrl) + for i in results) + + pages = list(client.list_crawled_urls(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_finding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_finding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc + + request = {} + client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_finding(request) + + # Establish 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_finding_rest_required_fields(request_type=web_security_scanner.GetFindingRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_finding._get_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_finding._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = finding.Finding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = finding.Finding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_finding_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_finding_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} + + # 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 = finding.Finding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_finding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}" % client.transport._host, args[1]) + + +def test_get_finding_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + + +def test_list_findings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_findings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_findings] = mock_rpc + + request = {} + client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_findings(request) + + # Establish 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_findings_rest_required_fields(request_type=web_security_scanner.ListFindingsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_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 "filter" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "filter" in jsonified_request + assert jsonified_request["filter"] == request_init["filter"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_findings._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' + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_findings(request) + + expected_params = [ + ( + "filter", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_findings_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", "filter", ))) + + +def test_list_findings_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} + + # 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 = web_security_scanner.ListFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_findings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings" % client.transport._host, args[1]) + + +def test_list_findings_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListFindingsResponse.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/scanConfigs/sample2/scanRuns/sample3'} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, finding.Finding) + for i in results) + + pages = list(client.list_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_finding_type_stats_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_finding_type_stats in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_finding_type_stats] = mock_rpc + + request = {} + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_finding_type_stats(request) + + # Establish 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_finding_type_stats_rest_required_fields(request_type=web_security_scanner.ListFindingTypeStatsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_finding_type_stats._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_finding_type_stats._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingTypeStatsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_finding_type_stats(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_finding_type_stats_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_finding_type_stats._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_list_finding_type_stats_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingTypeStatsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} + + # 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 = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_finding_type_stats(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats" % client.transport._host, args[1]) + + +def test_list_finding_type_stats_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + 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 = WebSecurityScannerClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebSecurityScannerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, +]) +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 = WebSecurityScannerClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = WebSecurityScannerClient( + 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.create_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.CreateScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = None + client.delete_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.DeleteScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.get_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_configs_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanConfigsResponse() + client.list_scan_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanConfigsRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.update_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.UpdateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_scan_run_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.start_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StartScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_run_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.get_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_runs_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanRunsResponse() + client.list_scan_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_scan_run_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.stop_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StopScanRunRequest() + + assert args[0] == request_msg + + +# This 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_crawled_urls_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + client.list_crawled_urls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListCrawledUrlsRequest() + + assert args[0] == request_msg + + +# This 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_finding_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = finding.Finding() + client.get_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetFindingRequest() + + assert args[0] == request_msg + + +# This 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_findings_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingsResponse() + client.list_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingsRequest() + + assert args[0] == request_msg + + +# This 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_finding_type_stats_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + client.list_finding_type_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingTypeStatsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = WebSecurityScannerAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + )) + await client.create_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.CreateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.DeleteScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + )) + await client.get_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_configs_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + )) + await client.list_scan_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + )) + await client.update_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.UpdateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_start_scan_run_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + await client.start_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StartScanRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_run_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + await client.get_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_runs_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + )) + await client.list_scan_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_stop_scan_run_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + await client.stop_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StopScanRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_crawled_urls_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + )) + await client.list_crawled_urls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListCrawledUrlsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_finding_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + finding_type=finding.Finding.FindingType.MIXED_CONTENT, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + )) + await client.get_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetFindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_findings_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + )) + await client.list_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_finding_type_stats_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( + )) + await client.list_finding_type_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingTypeStatsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = WebSecurityScannerClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_scan_config_rest_bad_request(request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerClient( + 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 + client.create_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.CreateScanConfigRequest, + dict, +]) +def test_create_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request_init["scan_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'target_platforms': [1], 'latest_run': {'name': 'name_value', 'execution_state': 1, 'result_state': 1, 'start_time': {}, 'end_time': {}, 'urls_crawled_count': 1935, 'urls_tested_count': 1846, 'has_vulnerabilities': True, 'progress_percent': 1733}} + # 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 = web_security_scanner.CreateScanConfigRequest.meta.fields["scan_config"] + + 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["scan_config"].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["scan_config"][field])): + del request_init["scan_config"][field][i][subfield] + else: + del request_init["scan_config"][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 = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_create_scan_config") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_create_scan_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.CreateScanConfigRequest.pb(web_security_scanner.CreateScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcw_scan_config.ScanConfig.to_json(gcw_scan_config.ScanConfig()) + req.return_value.content = return_value + + request = web_security_scanner.CreateScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcw_scan_config.ScanConfig() + + client.create_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_scan_config_rest_bad_request(request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + client.delete_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.DeleteScanConfigRequest, + dict, +]) +def test_delete_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + response = client.delete_scan_config(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_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_delete_scan_config") as pre: + pre.assert_not_called() + pb_message = web_security_scanner.DeleteScanConfigRequest.pb(web_security_scanner.DeleteScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = web_security_scanner.DeleteScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_get_scan_config_rest_bad_request(request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + client.get_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanConfigRequest, + dict, +]) +def test_get_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_config") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanConfigRequest.pb(web_security_scanner.GetScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) + req.return_value.content = return_value + + request = web_security_scanner.GetScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.get_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_configs_rest_bad_request(request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerClient( + 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 + client.list_scan_configs(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanConfigsRequest, + dict, +]) +def test_list_scan_configs_rest_call_success(request_type): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanConfigsResponse( + 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_scan_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_configs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_configs") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanConfigsRequest.pb(web_security_scanner.ListScanConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListScanConfigsResponse.to_json(web_security_scanner.ListScanConfigsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListScanConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanConfigsResponse() + + client.list_scan_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_scan_config_rest_bad_request(request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/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 + client.update_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.UpdateScanConfigRequest, + dict, +]) +def test_update_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} + request_init["scan_config"] = {'name': 'projects/sample1/scanConfigs/sample2', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'target_platforms': [1], 'latest_run': {'name': 'name_value', 'execution_state': 1, 'result_state': 1, 'start_time': {}, 'end_time': {}, 'urls_crawled_count': 1935, 'urls_tested_count': 1846, 'has_vulnerabilities': True, 'progress_percent': 1733}} + # 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 = web_security_scanner.UpdateScanConfigRequest.meta.fields["scan_config"] + + 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["scan_config"].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["scan_config"][field])): + del request_init["scan_config"][field][i][subfield] + else: + del request_init["scan_config"][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 = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_update_scan_config") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_update_scan_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.UpdateScanConfigRequest.pb(web_security_scanner.UpdateScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcw_scan_config.ScanConfig.to_json(gcw_scan_config.ScanConfig()) + req.return_value.content = return_value + + request = web_security_scanner.UpdateScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcw_scan_config.ScanConfig() + + client.update_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_scan_run_rest_bad_request(request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + client.start_scan_run(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.StartScanRunRequest, + dict, +]) +def test_start_scan_run_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.start_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_start_scan_run") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_start_scan_run") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StartScanRunRequest.pb(web_security_scanner.StartScanRunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) + req.return_value.content = return_value + + request = web_security_scanner.StartScanRunRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.start_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_scan_run_rest_bad_request(request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.get_scan_run(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanRunRequest, + dict, +]) +def test_get_scan_run_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_run") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_run") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanRunRequest.pb(web_security_scanner.GetScanRunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) + req.return_value.content = return_value + + request = web_security_scanner.GetScanRunRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.get_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_runs_rest_bad_request(request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/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 + client.list_scan_runs(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanRunsRequest, + dict, +]) +def test_list_scan_runs_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse( + 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_scan_runs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_runs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_runs") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_runs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanRunsRequest.pb(web_security_scanner.ListScanRunsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListScanRunsResponse.to_json(web_security_scanner.ListScanRunsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListScanRunsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanRunsResponse() + + client.list_scan_runs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_scan_run_rest_bad_request(request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.stop_scan_run(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.StopScanRunRequest, + dict, +]) +def test_stop_scan_run_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.stop_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_stop_scan_run") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_stop_scan_run") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StopScanRunRequest.pb(web_security_scanner.StopScanRunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) + req.return_value.content = return_value + + request = web_security_scanner.StopScanRunRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.stop_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_crawled_urls_rest_bad_request(request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.list_crawled_urls(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListCrawledUrlsRequest, + dict, +]) +def test_list_crawled_urls_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListCrawledUrlsResponse( + 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_crawled_urls(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crawled_urls_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_crawled_urls") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_crawled_urls") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListCrawledUrlsRequest.pb(web_security_scanner.ListCrawledUrlsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListCrawledUrlsResponse.to_json(web_security_scanner.ListCrawledUrlsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListCrawledUrlsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListCrawledUrlsResponse() + + client.list_crawled_urls(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_finding_rest_bad_request(request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_finding(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetFindingRequest, + dict, +]) +def test_get_finding_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = finding.Finding( + name='name_value', + finding_type=finding.Finding.FindingType.MIXED_CONTENT, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = finding.Finding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_finding_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_finding") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetFindingRequest.pb(web_security_scanner.GetFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = finding.Finding.to_json(finding.Finding()) + req.return_value.content = return_value + + request = web_security_scanner.GetFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.get_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.list_findings(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListFindingsRequest, + dict, +]) +def test_list_findings_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingsResponse( + 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 = web_security_scanner.ListFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingsRequest.pb(web_security_scanner.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListFindingsResponse.to_json(web_security_scanner.ListFindingsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_finding_type_stats_rest_bad_request(request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.list_finding_type_stats(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListFindingTypeStatsRequest, + dict, +]) +def test_list_finding_type_stats_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingTypeStatsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_finding_type_stats(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_finding_type_stats_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_finding_type_stats") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_finding_type_stats") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingTypeStatsRequest.pb(web_security_scanner.ListFindingTypeStatsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListFindingTypeStatsResponse.to_json(web_security_scanner.ListFindingTypeStatsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListFindingTypeStatsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + client.list_finding_type_stats(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = WebSecurityScannerClient( + 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + client.create_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.CreateScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + client.delete_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.DeleteScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + client.get_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_configs_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + client.list_scan_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanConfigsRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + client.update_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.UpdateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_scan_run_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + client.start_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StartScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_run_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + client.get_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_runs_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + client.list_scan_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_scan_run_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + client.stop_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StopScanRunRequest() + + assert args[0] == request_msg + + +# This 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_crawled_urls_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + client.list_crawled_urls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListCrawledUrlsRequest() + + assert args[0] == request_msg + + +# This 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_finding_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + client.get_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetFindingRequest() + + assert args[0] == request_msg + + +# This 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_findings_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + client.list_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingsRequest() + + assert args[0] == request_msg + + +# This 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_finding_type_stats_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + client.list_finding_type_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingTypeStatsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebSecurityScannerGrpcTransport, + ) + +def test_web_security_scanner_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_web_security_scanner_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_scan_config', + 'delete_scan_config', + 'get_scan_config', + 'list_scan_configs', + 'update_scan_config', + 'start_scan_run', + 'get_scan_run', + 'list_scan_runs', + 'stop_scan_run', + 'list_crawled_urls', + 'get_finding', + 'list_findings', + 'list_finding_type_stats', + ) + 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_web_security_scanner_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + 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_web_security_scanner_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport() + adc.assert_called_once() + + +def test_web_security_scanner_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) + WebSecurityScannerClient() + 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.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + ], +) +def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, + ], +) +def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, grpc_helpers), + (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_web_security_scanner_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( + "websecurityscanner.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="websecurityscanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_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_web_security_scanner_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.WebSecurityScannerRestTransport ( + 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_web_security_scanner_host_no_port(transport_name): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'websecurityscanner.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://websecurityscanner.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_web_security_scanner_host_with_port(transport_name): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'websecurityscanner.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://websecurityscanner.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_web_security_scanner_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WebSecurityScannerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WebSecurityScannerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_scan_config._session + session2 = client2.transport.create_scan_config._session + assert session1 != session2 + session1 = client1.transport.delete_scan_config._session + session2 = client2.transport.delete_scan_config._session + assert session1 != session2 + session1 = client1.transport.get_scan_config._session + session2 = client2.transport.get_scan_config._session + assert session1 != session2 + session1 = client1.transport.list_scan_configs._session + session2 = client2.transport.list_scan_configs._session + assert session1 != session2 + session1 = client1.transport.update_scan_config._session + session2 = client2.transport.update_scan_config._session + assert session1 != session2 + session1 = client1.transport.start_scan_run._session + session2 = client2.transport.start_scan_run._session + assert session1 != session2 + session1 = client1.transport.get_scan_run._session + session2 = client2.transport.get_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_scan_runs._session + session2 = client2.transport.list_scan_runs._session + assert session1 != session2 + session1 = client1.transport.stop_scan_run._session + session2 = client2.transport.stop_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_crawled_urls._session + session2 = client2.transport.list_crawled_urls._session + assert session1 != session2 + session1 = client1.transport.get_finding._session + session2 = client2.transport.get_finding._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_finding_type_stats._session + session2 = client2.transport.list_finding_type_stats._session + assert session1 != session2 +def test_web_security_scanner_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcTransport( + 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_web_security_scanner_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + 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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_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_finding_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + finding = "octopus" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "project": "oyster", + "scan_config": "nudibranch", + "scan_run": "cuttlefish", + "finding": "mussel", + } + path = WebSecurityScannerClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_finding_path(path) + assert expected == actual + +def test_scan_config_path(): + project = "winkle" + scan_config = "nautilus" + expected = "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) + actual = WebSecurityScannerClient.scan_config_path(project, scan_config) + assert expected == actual + + +def test_parse_scan_config_path(): + expected = { + "project": "scallop", + "scan_config": "abalone", + } + path = WebSecurityScannerClient.scan_config_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_scan_config_path(path) + assert expected == actual + +def test_scan_run_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) + actual = WebSecurityScannerClient.scan_run_path(project, scan_config, scan_run) + assert expected == actual + + +def test_parse_scan_run_path(): + expected = { + "project": "octopus", + "scan_config": "oyster", + "scan_run": "nudibranch", + } + path = WebSecurityScannerClient.scan_run_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_scan_run_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WebSecurityScannerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = WebSecurityScannerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = WebSecurityScannerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = WebSecurityScannerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WebSecurityScannerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = WebSecurityScannerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = WebSecurityScannerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = WebSecurityScannerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.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 = WebSecurityScannerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = WebSecurityScannerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.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.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + transport_class = WebSecurityScannerClient.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 = WebSecurityScannerClient( + 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 = WebSecurityScannerAsyncClient( + 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 = WebSecurityScannerClient( + 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 = WebSecurityScannerClient( + 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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport), +]) +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-cloud-websecurityscanner/v1beta/.coveragerc b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/.coveragerc new file mode 100644 index 000000000000..085a92b30288 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/websecurityscanner/__init__.py + google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1beta/.flake8 b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/MANIFEST.in new file mode 100644 index 000000000000..e23fd8ac9a4f --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/websecurityscanner *.py +recursive-include google/cloud/websecurityscanner_v1beta *.py diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/README.rst new file mode 100644 index 000000000000..4de4c103eee6 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Websecurityscanner 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 Cloud Websecurityscanner 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-cloud-websecurityscanner/v1beta/docs/_static/custom.css b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/conf.py new file mode 100644 index 000000000000..40ff11b301ef --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner 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-cloud-websecurityscanner" +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 Cloud 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-cloud-websecurityscanner-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-cloud-websecurityscanner.tex", + u"google-cloud-websecurityscanner 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-cloud-websecurityscanner", + u"Google Cloud Websecurityscanner 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-cloud-websecurityscanner", + u"google-cloud-websecurityscanner Documentation", + author, + "google-cloud-websecurityscanner", + "GAPIC library for Google Cloud Websecurityscanner 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-cloud-websecurityscanner/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/index.rst new file mode 100644 index 000000000000..1760f1337efd --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + websecurityscanner_v1beta/services_ + websecurityscanner_v1beta/types_ diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/services_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/services_.rst new file mode 100644 index 000000000000..37adbdcbd3bb --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Websecurityscanner v1beta API +======================================================= +.. toctree:: + :maxdepth: 2 + + web_security_scanner diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/types_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/types_.rst new file mode 100644 index 000000000000..531b92bae980 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Websecurityscanner v1beta API +==================================================== + +.. automodule:: google.cloud.websecurityscanner_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst new file mode 100644 index 000000000000..8918acef9d56 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst @@ -0,0 +1,10 @@ +WebSecurityScanner +------------------------------------ + +.. automodule:: google.cloud.websecurityscanner_v1beta.services.web_security_scanner + :members: + :inherited-members: + +.. automodule:: google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/__init__.py new file mode 100644 index 000000000000..9c3ef58bf6b7 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/__init__.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner.client import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient + +from google.cloud.websecurityscanner_v1beta.types.crawled_url import CrawledUrl +from google.cloud.websecurityscanner_v1beta.types.finding import Finding +from google.cloud.websecurityscanner_v1beta.types.finding_addon import Form +from google.cloud.websecurityscanner_v1beta.types.finding_addon import OutdatedLibrary +from google.cloud.websecurityscanner_v1beta.types.finding_addon import ViolatingResource +from google.cloud.websecurityscanner_v1beta.types.finding_addon import VulnerableHeaders +from google.cloud.websecurityscanner_v1beta.types.finding_addon import VulnerableParameters +from google.cloud.websecurityscanner_v1beta.types.finding_addon import Xss +from google.cloud.websecurityscanner_v1beta.types.finding_type_stats import FindingTypeStats +from google.cloud.websecurityscanner_v1beta.types.scan_config import ScanConfig +from google.cloud.websecurityscanner_v1beta.types.scan_config_error import ScanConfigError +from google.cloud.websecurityscanner_v1beta.types.scan_run import ScanRun +from google.cloud.websecurityscanner_v1beta.types.scan_run_error_trace import ScanRunErrorTrace +from google.cloud.websecurityscanner_v1beta.types.scan_run_warning_trace import ScanRunWarningTrace +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import CreateScanConfigRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import DeleteScanConfigRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetFindingRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetScanConfigRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetScanRunRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListCrawledUrlsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListCrawledUrlsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingTypeStatsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingTypeStatsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanConfigsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanConfigsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanRunsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanRunsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import StartScanRunRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import StopScanRunRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ('WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', + 'CrawledUrl', + 'Finding', + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanConfigError', + 'ScanRun', + 'ScanRunErrorTrace', + 'ScanRunWarningTrace', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/py.typed new file mode 100644 index 000000000000..8cfb5d256398 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py new file mode 100644 index 000000000000..5eaa835c5f1d --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/__init__.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 google.cloud.websecurityscanner_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.web_security_scanner import WebSecurityScannerClient +from .services.web_security_scanner import WebSecurityScannerAsyncClient + +from .types.crawled_url import CrawledUrl +from .types.finding import Finding +from .types.finding_addon import Form +from .types.finding_addon import OutdatedLibrary +from .types.finding_addon import ViolatingResource +from .types.finding_addon import VulnerableHeaders +from .types.finding_addon import VulnerableParameters +from .types.finding_addon import Xss +from .types.finding_type_stats import FindingTypeStats +from .types.scan_config import ScanConfig +from .types.scan_config_error import ScanConfigError +from .types.scan_run import ScanRun +from .types.scan_run_error_trace import ScanRunErrorTrace +from .types.scan_run_warning_trace import ScanRunWarningTrace +from .types.web_security_scanner import CreateScanConfigRequest +from .types.web_security_scanner import DeleteScanConfigRequest +from .types.web_security_scanner import GetFindingRequest +from .types.web_security_scanner import GetScanConfigRequest +from .types.web_security_scanner import GetScanRunRequest +from .types.web_security_scanner import ListCrawledUrlsRequest +from .types.web_security_scanner import ListCrawledUrlsResponse +from .types.web_security_scanner import ListFindingsRequest +from .types.web_security_scanner import ListFindingsResponse +from .types.web_security_scanner import ListFindingTypeStatsRequest +from .types.web_security_scanner import ListFindingTypeStatsResponse +from .types.web_security_scanner import ListScanConfigsRequest +from .types.web_security_scanner import ListScanConfigsResponse +from .types.web_security_scanner import ListScanRunsRequest +from .types.web_security_scanner import ListScanRunsResponse +from .types.web_security_scanner import StartScanRunRequest +from .types.web_security_scanner import StopScanRunRequest +from .types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ( + 'WebSecurityScannerAsyncClient', +'CrawledUrl', +'CreateScanConfigRequest', +'DeleteScanConfigRequest', +'Finding', +'FindingTypeStats', +'Form', +'GetFindingRequest', +'GetScanConfigRequest', +'GetScanRunRequest', +'ListCrawledUrlsRequest', +'ListCrawledUrlsResponse', +'ListFindingTypeStatsRequest', +'ListFindingTypeStatsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListScanConfigsRequest', +'ListScanConfigsResponse', +'ListScanRunsRequest', +'ListScanRunsResponse', +'OutdatedLibrary', +'ScanConfig', +'ScanConfigError', +'ScanRun', +'ScanRunErrorTrace', +'ScanRunWarningTrace', +'StartScanRunRequest', +'StopScanRunRequest', +'UpdateScanConfigRequest', +'ViolatingResource', +'VulnerableHeaders', +'VulnerableParameters', +'WebSecurityScannerClient', +'Xss', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..329504a244c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json @@ -0,0 +1,223 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.websecurityscanner_v1beta", + "protoPackage": "google.cloud.websecurityscanner.v1beta", + "schema": "1.0", + "services": { + "WebSecurityScanner": { + "clients": { + "grpc": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebSecurityScannerAsyncClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + }, + "rest": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/py.typed new file mode 100644 index 000000000000..8cfb5d256398 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py new file mode 100644 index 000000000000..3aeec5e07d95 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__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 WebSecurityScannerClient +from .async_client import WebSecurityScannerAsyncClient + +__all__ = ( + 'WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py new file mode 100644 index 000000000000..78cb9dc65331 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py @@ -0,0 +1,1700 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.websecurityscanner_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.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import finding_addon +from google.cloud.websecurityscanner_v1beta.types import finding_type_stats +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .client import WebSecurityScannerClient + + +class WebSecurityScannerAsyncClient: + """Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + """ + + _client: WebSecurityScannerClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WebSecurityScannerClient._DEFAULT_UNIVERSE + + finding_path = staticmethod(WebSecurityScannerClient.finding_path) + parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) + scan_config_path = staticmethod(WebSecurityScannerClient.scan_config_path) + parse_scan_config_path = staticmethod(WebSecurityScannerClient.parse_scan_config_path) + scan_run_path = staticmethod(WebSecurityScannerClient.scan_run_path) + parse_scan_run_path = staticmethod(WebSecurityScannerClient.parse_scan_run_path) + common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) + parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) + common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) + parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) + common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) + parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) + common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) + parse_common_location_path = staticmethod(WebSecurityScannerClient.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: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, 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: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, 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 WebSecurityScannerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: 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 = WebSecurityScannerClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner 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,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): + 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 WebSecurityScannerTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WebSecurityScannerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_scan_config(self, + request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + scan_config: Optional[gcw_scan_config.ScanConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1beta.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1beta.CreateScanConfigRequest( + parent="parent_value", + scan_config=scan_config, + ) + + # Make the request + response = await client.create_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest, dict]]): + The request object. Request for the ``CreateScanConfig`` method. + parent (:class:`str`): + Required. The parent resource name + where the scan is created, which should + be a project resource name in the format + 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scan_config (:class:`google.cloud.websecurityscanner_v1beta.types.ScanConfig`): + Required. The ScanConfig to be + created. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_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. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, scan_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, web_security_scanner.CreateScanConfigRequest): + request = web_security_scanner.CreateScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scan_config is not None: + request.scan_config = scan_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_scan_config] + + # Certain fields should be provided within 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_scan_config(self, + request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.DeleteScanConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_scan_config(request=request) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest, dict]]): + The request object. Request for the ``DeleteScanConfig`` method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be deleted. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.DeleteScanConfigRequest): + request = web_security_scanner.DeleteScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_config] + + # Certain fields should be provided within 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 get_scan_config(self, + request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetScanConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest, dict]]): + The request object. Request for the ``GetScanConfig`` method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be returned. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetScanConfigRequest): + request = web_security_scanner.GetScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_config] + + # Certain fields should be provided within 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_scan_configs(self, + request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsAsyncPager: + r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1beta + + async def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListScanConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest, dict]]): + The request object. Request for the ``ListScanConfigs`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a project resource name + in the format 'projects/{projectId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: + Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): + request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] + + # Certain fields should be provided within 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.ListScanConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_scan_config(self, + request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, + *, + scan_config: Optional[gcw_scan_config.ScanConfig] = 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, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1beta.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1beta.UpdateScanConfigRequest( + scan_config=scan_config, + ) + + # Make the request + response = await client.update_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest, dict]]): + The request object. Request for the ``UpdateScanConfigRequest`` method. + scan_config (:class:`google.cloud.websecurityscanner_v1beta.types.ScanConfig`): + Required. The ScanConfig to be + updated. The name field must be set to + identify the resource to be updated. The + values of fields not covered by the mask + will be ignored. + + This corresponds to the ``scan_config`` 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 update mask applies to the resource. For + the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scan_config, 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, web_security_scanner.UpdateScanConfigRequest): + request = web_security_scanner.UpdateScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scan_config is not None: + request.scan_config = scan_config + 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_scan_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.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 start_scan_run(self, + request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.StartScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.start_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest, dict]]): + The request object. Request for the ``StartScanRun`` method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be used. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.StartScanRunRequest): + request = web_security_scanner.StartScanRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.start_scan_run] + + # Certain fields should be provided within 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_scan_run(self, + request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest, dict]]): + The request object. Request for the ``GetScanRun`` method. + name (:class:`str`): + Required. The resource name of the + ScanRun to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetScanRunRequest): + request = web_security_scanner.GetScanRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_run] + + # Certain fields should be provided within 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_scan_runs(self, + request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsAsyncPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListScanRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest, dict]]): + The request object. Request for the ``ListScanRuns`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan resource name in + the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsAsyncPager: + Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): + request = web_security_scanner.ListScanRunsRequest(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_scan_runs] + + # Certain fields should be provided within 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.ListScanRunsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def stop_scan_run(self, + request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.StopScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.stop_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest, dict]]): + The request object. Request for the ``StopScanRun`` method. + name (:class:`str`): + Required. The resource name of the + ScanRun to be stopped. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.StopScanRunRequest): + request = web_security_scanner.StopScanRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.stop_scan_run] + + # Certain fields should be provided within 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_crawled_urls(self, + request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsAsyncPager: + r"""List CrawledUrls under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListCrawledUrlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest, dict]]): + The request object. Request for the ``ListCrawledUrls`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: + Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] + + # Certain fields should be provided within 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.ListCrawledUrlsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_finding(self, + request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_get_finding(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetFindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.GetFindingRequest, dict]]): + The request object. Request for the ``GetFinding`` method. + name (:class:`str`): + Required. The resource name of the + Finding to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetFindingRequest): + request = web_security_scanner.GetFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_finding] + + # Certain fields should be provided within 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_findings(self, + request: Optional[Union[web_security_scanner.ListFindingsRequest, 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, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""List Findings under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_list_findings(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListFindingsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest, dict]]): + The request object. Request for the ``ListFindings`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Required. The filter expression. The expression must be + in the format: . Supported field: 'finding_type'. + Supported operator: '='. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsAsyncPager: + Response for the ListFindings 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, 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, web_security_scanner.ListFindingsRequest): + request = web_security_scanner.ListFindingsRequest(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_findings] + + # Certain fields should be provided within 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.ListFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_finding_type_stats(self, + request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + async def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListFindingTypeStatsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest, dict]]): + The request object. Request for the ``ListFindingTypeStats`` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + 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, web_security_scanner.ListFindingTypeStatsRequest): + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] + + # Certain fields should be provided within 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) -> "WebSecurityScannerAsyncClient": + 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__ = ( + "WebSecurityScannerAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py new file mode 100644 index 000000000000..dca8b7f4c4f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py @@ -0,0 +1,2062 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.websecurityscanner_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 + +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import finding_addon +from google.cloud.websecurityscanner_v1beta.types import finding_type_stats +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WebSecurityScannerGrpcTransport +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .transports.rest import WebSecurityScannerRestTransport + + +class WebSecurityScannerClientMeta(type): + """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] + _transport_registry["grpc"] = WebSecurityScannerGrpcTransport + _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport + _transport_registry["rest"] = WebSecurityScannerRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WebSecurityScannerTransport]: + """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 WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): + """Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + """ + + @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 = "websecurityscanner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "websecurityscanner.{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: + WebSecurityScannerClient: 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: + WebSecurityScannerClient: 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) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def scan_config_path(project: str,scan_config: str,) -> str: + """Returns a fully-qualified scan_config string.""" + return "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) + + @staticmethod + def parse_scan_config_path(path: str) -> Dict[str,str]: + """Parses a scan_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def scan_run_path(project: str,scan_config: str,scan_run: str,) -> str: + """Returns a fully-qualified scan_run string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) + + @staticmethod + def parse_scan_run_path(path: str) -> Dict[str,str]: + """Parses a scan_run path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?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 = WebSecurityScannerClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WebSecurityScannerClient._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 = WebSecurityScannerClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + WebSecurityScannerClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): + 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 WebSecurityScannerTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WebSecurityScannerClient._read_environment_variables() + self._client_cert_source = WebSecurityScannerClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = WebSecurityScannerClient._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 + + 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, WebSecurityScannerTransport) + if transport_provided: + # transport is a WebSecurityScannerTransport 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(WebSecurityScannerTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + WebSecurityScannerClient._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[WebSecurityScannerTransport], Callable[..., WebSecurityScannerTransport]] = ( + WebSecurityScannerClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WebSecurityScannerTransport], 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, + ) + + def create_scan_config(self, + request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + scan_config: Optional[gcw_scan_config.ScanConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1beta.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1beta.CreateScanConfigRequest( + parent="parent_value", + scan_config=scan_config, + ) + + # Make the request + response = client.create_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest, dict]): + The request object. Request for the ``CreateScanConfig`` method. + parent (str): + Required. The parent resource name + where the scan is created, which should + be a project resource name in the format + 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): + Required. The ScanConfig to be + created. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.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. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, scan_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, web_security_scanner.CreateScanConfigRequest): + request = web_security_scanner.CreateScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scan_config is not None: + request.scan_config = scan_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_scan_config] + + # Certain fields should be provided within 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_scan_config(self, + request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.DeleteScanConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_scan_config(request=request) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest, dict]): + The request object. Request for the ``DeleteScanConfig`` method. + name (str): + Required. The resource name of the + ScanConfig to be deleted. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.DeleteScanConfigRequest): + request = web_security_scanner.DeleteScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_config] + + # Certain fields should be provided within 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 get_scan_config(self, + request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetScanConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest, dict]): + The request object. Request for the ``GetScanConfig`` method. + name (str): + Required. The resource name of the + ScanConfig to be returned. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetScanConfigRequest): + request = web_security_scanner.GetScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_config] + + # Certain fields should be provided within 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_scan_configs(self, + request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsPager: + r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1beta + + def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListScanConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest, dict]): + The request object. Request for the ``ListScanConfigs`` method. + parent (str): + Required. The parent resource name, + which should be a project resource name + in the format 'projects/{projectId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsPager: + Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): + request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] + + # Certain fields should be provided within 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.ListScanConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_scan_config(self, + request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, + *, + scan_config: Optional[gcw_scan_config.ScanConfig] = 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, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1beta.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1beta.UpdateScanConfigRequest( + scan_config=scan_config, + ) + + # Make the request + response = client.update_scan_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest, dict]): + The request object. Request for the ``UpdateScanConfigRequest`` method. + scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): + Required. The ScanConfig to be + updated. The name field must be set to + identify the resource to be updated. The + values of fields not covered by the mask + will be ignored. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For + the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scan_config, 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, web_security_scanner.UpdateScanConfigRequest): + request = web_security_scanner.UpdateScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scan_config is not None: + request.scan_config = scan_config + 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_scan_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.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 start_scan_run(self, + request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.StartScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.start_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest, dict]): + The request object. Request for the ``StartScanRun`` method. + name (str): + Required. The resource name of the + ScanConfig to be used. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.StartScanRunRequest): + request = web_security_scanner.StartScanRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.start_scan_run] + + # Certain fields should be provided within 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_scan_run(self, + request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.get_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest, dict]): + The request object. Request for the ``GetScanRun`` method. + name (str): + Required. The resource name of the + ScanRun to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetScanRunRequest): + request = web_security_scanner.GetScanRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scan_run] + + # Certain fields should be provided within 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_scan_runs(self, + request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListScanRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest, dict]): + The request object. Request for the ``ListScanRuns`` method. + parent (str): + Required. The parent resource name, + which should be a scan resource name in + the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsPager: + Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): + request = web_security_scanner.ListScanRunsRequest(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_scan_runs] + + # Certain fields should be provided within 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.ListScanRunsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stop_scan_run(self, + request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.StopScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.stop_scan_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest, dict]): + The request object. Request for the ``StopScanRun`` method. + name (str): + Required. The resource name of the + ScanRun to be stopped. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.StopScanRunRequest): + request = web_security_scanner.StopScanRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.stop_scan_run] + + # Certain fields should be provided within 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_crawled_urls(self, + request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsPager: + r"""List CrawledUrls under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListCrawledUrlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest, dict]): + The request object. Request for the ``ListCrawledUrls`` method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsPager: + Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] + + # Certain fields should be provided within 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.ListCrawledUrlsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_finding(self, + request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_get_finding(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetFindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.GetFindingRequest, dict]): + The request object. Request for the ``GetFinding`` method. + name (str): + Required. The resource name of the + Finding to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, web_security_scanner.GetFindingRequest): + request = web_security_scanner.GetFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_finding] + + # Certain fields should be provided within 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_findings(self, + request: Optional[Union[web_security_scanner.ListFindingsRequest, 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, str]] = (), + ) -> pagers.ListFindingsPager: + r"""List Findings under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_list_findings(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListFindingsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest, dict]): + The request object. Request for the ``ListFindings`` method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Required. The filter expression. The expression must be + in the format: . Supported field: 'finding_type'. + Supported operator: '='. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsPager: + Response for the ListFindings 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, 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, web_security_scanner.ListFindingsRequest): + request = web_security_scanner.ListFindingsRequest(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_findings] + + # Certain fields should be provided within 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.ListFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_finding_type_stats(self, + request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import websecurityscanner_v1beta + + def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListFindingTypeStatsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest, dict]): + The request object. Request for the ``ListFindingTypeStats`` method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + 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, web_security_scanner.ListFindingTypeStatsRequest): + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] + + # Certain fields should be provided within 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) -> "WebSecurityScannerClient": + 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__ = ( + "WebSecurityScannerClient", +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py new file mode 100644 index 000000000000..6efe8a0e28a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py @@ -0,0 +1,571 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner + + +class ListScanConfigsPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListScanConfigsResponse], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + for page in self.pages: + yield from page.scan_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanConfigsAsyncPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` + attributes are available on the 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[web_security_scanner.ListScanConfigsResponse]], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListScanRunsResponse], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + for page in self.pages: + yield from page.scan_runs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsAsyncPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` + attributes are available on the 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[web_security_scanner.ListScanRunsResponse]], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_runs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListCrawledUrlsResponse], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + for page in self.pages: + yield from page.crawled_urls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsAsyncPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` + attributes are available on the 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[web_security_scanner.ListCrawledUrlsResponse]], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + async def async_generator(): + async for page in self.pages: + for response in page.crawled_urls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListFindingsResponse], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: + 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[finding.Finding]: + for page in self.pages: + yield from page.findings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` + attributes are available on the 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[web_security_scanner.ListFindingsResponse]], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: + 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[finding.Finding]: + async def async_generator(): + async for page in self.pages: + for response in page.findings: + 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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/README.rst new file mode 100644 index 000000000000..3479ee767648 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`WebSecurityScannerTransport` is the ABC for all transports. +- public child `WebSecurityScannerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `WebSecurityScannerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseWebSecurityScannerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `WebSecurityScannerRestTransport` 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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py new file mode 100644 index 000000000000..e24819a4ee07 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/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 WebSecurityScannerTransport +from .grpc import WebSecurityScannerGrpcTransport +from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .rest import WebSecurityScannerRestTransport +from .rest import WebSecurityScannerRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] +_transport_registry['grpc'] = WebSecurityScannerGrpcTransport +_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport +_transport_registry['rest'] = WebSecurityScannerRestTransport + +__all__ = ( + 'WebSecurityScannerTransport', + 'WebSecurityScannerGrpcTransport', + 'WebSecurityScannerGrpcAsyncIOTransport', + 'WebSecurityScannerRestTransport', + 'WebSecurityScannerRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py new file mode 100644 index 000000000000..c37593cea39e --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner_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.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WebSecurityScannerTransport(abc.ABC): + """Abstract transport class for WebSecurityScanner.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_scan_config: gapic_v1.method.wrap_method( + self.create_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.delete_scan_config: gapic_v1.method.wrap_method( + self.delete_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_config: gapic_v1.method.wrap_method( + self.get_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_configs: gapic_v1.method.wrap_method( + self.list_scan_configs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_scan_config: gapic_v1.method.wrap_method( + self.update_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.start_scan_run: gapic_v1.method.wrap_method( + self.start_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_run: gapic_v1.method.wrap_method( + self.get_scan_run, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_runs: gapic_v1.method.wrap_method( + self.list_scan_runs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.stop_scan_run: gapic_v1.method.wrap_method( + self.stop_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.list_crawled_urls: gapic_v1.method.wrap_method( + self.list_crawled_urls, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_finding: gapic_v1.method.wrap_method( + self.get_finding, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_finding_type_stats: gapic_v1.method.wrap_method( + self.list_finding_type_stats, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Union[ + gcw_scan_config.ScanConfig, + Awaitable[gcw_scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Union[ + web_security_scanner.ListScanConfigsResponse, + Awaitable[web_security_scanner.ListScanConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Union[ + gcw_scan_config.ScanConfig, + Awaitable[gcw_scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Union[ + web_security_scanner.ListScanRunsResponse, + Awaitable[web_security_scanner.ListScanRunsResponse] + ]]: + raise NotImplementedError() + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Union[ + web_security_scanner.ListCrawledUrlsResponse, + Awaitable[web_security_scanner.ListCrawledUrlsResponse] + ]]: + raise NotImplementedError() + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Union[ + web_security_scanner.ListFindingsResponse, + Awaitable[web_security_scanner.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Union[ + web_security_scanner.ListFindingTypeStatsResponse, + Awaitable[web_security_scanner.ListFindingTypeStatsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WebSecurityScannerTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py new file mode 100644 index 000000000000..e7ee11f751a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO + + +class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): + """gRPC backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'websecurityscanner.googleapis.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_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + gcw_scan_config.ScanConfig]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + ~.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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + ~.ListScanConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + gcw_scan_config.ScanConfig]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + ~.ListScanRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + ~.ListCrawledUrlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + finding.Finding]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + ~.ListFindingTypeStatsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WebSecurityScannerGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e8b3e6905c4c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py @@ -0,0 +1,764 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .grpc import WebSecurityScannerGrpcTransport + + +class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): + """gRPC AsyncIO backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'websecurityscanner.googleapis.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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Awaitable[gcw_scan_config.ScanConfig]]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + 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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Awaitable[web_security_scanner.ListScanConfigsResponse]]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + Awaitable[~.ListScanConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Awaitable[gcw_scan_config.ScanConfig]]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Awaitable[web_security_scanner.ListScanRunsResponse]]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + Awaitable[~.ListScanRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + Awaitable[~.ListCrawledUrlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Awaitable[web_security_scanner.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + Awaitable[~.ListFindingTypeStatsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + 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_scan_config: self._wrap_method( + self.create_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.delete_scan_config: self._wrap_method( + self.delete_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_config: self._wrap_method( + self.get_scan_config, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_configs: self._wrap_method( + self.list_scan_configs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_scan_config: self._wrap_method( + self.update_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.start_scan_run: self._wrap_method( + self.start_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_run: self._wrap_method( + self.get_scan_run, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_runs: self._wrap_method( + self.list_scan_runs, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.stop_scan_run: self._wrap_method( + self.stop_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.list_crawled_urls: self._wrap_method( + self.list_crawled_urls, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_finding: self._wrap_method( + self.get_finding, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_findings: self._wrap_method( + self.list_findings, + 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=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_finding_type_stats: self._wrap_method( + self.list_finding_type_stats, + 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=600.0, + ), + default_timeout=600.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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'WebSecurityScannerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py new file mode 100644 index 000000000000..0047e1ffa541 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py @@ -0,0 +1,1533 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + + +from .rest_base import _BaseWebSecurityScannerRestTransport +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 + + +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 WebSecurityScannerRestInterceptor: + """Interceptor for WebSecurityScanner. + + 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 WebSecurityScannerRestTransport. + + .. code-block:: python + class MyCustomWebSecurityScannerInterceptor(WebSecurityScannerRestInterceptor): + def pre_create_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crawled_urls(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crawled_urls(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_finding_type_stats(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_finding_type_stats(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_runs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_runs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WebSecurityScannerRestTransport(interceptor=MyCustomWebSecurityScannerInterceptor()) + client = WebSecurityScannerClient(transport=transport) + + + """ + def pre_create_scan_config(self, request: web_security_scanner.CreateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.CreateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_create_scan_config(self, response: gcw_scan_config.ScanConfig) -> gcw_scan_config.ScanConfig: + """Post-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_delete_scan_config(self, request: web_security_scanner.DeleteScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.DeleteScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def pre_get_finding(self, request: web_security_scanner.GetFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_finding(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for get_finding + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_config(self, request: web_security_scanner.GetScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: + """Post-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_run(self, request: web_security_scanner.GetScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_crawled_urls(self, request: web_security_scanner.ListCrawledUrlsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListCrawledUrlsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_crawled_urls(self, response: web_security_scanner.ListCrawledUrlsResponse) -> web_security_scanner.ListCrawledUrlsResponse: + """Post-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_findings(self, request: web_security_scanner.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_findings(self, response: web_security_scanner.ListFindingsResponse) -> web_security_scanner.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_finding_type_stats(self, request: web_security_scanner.ListFindingTypeStatsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingTypeStatsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_finding_type_stats(self, response: web_security_scanner.ListFindingTypeStatsResponse) -> web_security_scanner.ListFindingTypeStatsResponse: + """Post-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_configs(self, request: web_security_scanner.ListScanConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_configs(self, response: web_security_scanner.ListScanConfigsResponse) -> web_security_scanner.ListScanConfigsResponse: + """Post-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_runs(self, request: web_security_scanner.ListScanRunsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanRunsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_runs(self, response: web_security_scanner.ListScanRunsResponse) -> web_security_scanner.ListScanRunsResponse: + """Post-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_start_scan_run(self, request: web_security_scanner.StartScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StartScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_start_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_stop_scan_run(self, request: web_security_scanner.StopScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StopScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_stop_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_update_scan_config(self, request: web_security_scanner.UpdateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.UpdateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_update_scan_config(self, response: gcw_scan_config.ScanConfig) -> gcw_scan_config.ScanConfig: + """Post-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WebSecurityScannerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WebSecurityScannerRestInterceptor + + +class WebSecurityScannerRestTransport(_BaseWebSecurityScannerRestTransport): + """REST backend synchronous transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'websecurityscanner.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[WebSecurityScannerRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'websecurityscanner.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 WebSecurityScannerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateScanConfig(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.CreateScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.CreateScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcw_scan_config.ScanConfig: + r"""Call the create scan config method over HTTP. + + Args: + request (~.web_security_scanner.CreateScanConfigRequest): + The request object. Request for the ``CreateScanConfig`` method. + retry (google.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. + + Returns: + ~.gcw_scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_http_options() + request, metadata = self._interceptor.pre_create_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._CreateScanConfig._get_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 = gcw_scan_config.ScanConfig() + pb_resp = gcw_scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_scan_config(resp) + return resp + + class _DeleteScanConfig(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.DeleteScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.DeleteScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete scan config method over HTTP. + + Args: + request (~.web_security_scanner.DeleteScanConfigRequest): + The request object. Request for the ``DeleteScanConfig`` method. + retry (google.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. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_http_options() + request, metadata = self._interceptor.pre_delete_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._DeleteScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 _GetFinding(_BaseWebSecurityScannerRestTransport._BaseGetFinding, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.GetFinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.GetFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the get finding method over HTTP. + + Args: + request (~.web_security_scanner.GetFindingRequest): + The request object. Request for the ``GetFinding`` method. + retry (google.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. + + Returns: + ~.finding.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_http_options() + request, metadata = self._interceptor.pre_get_finding(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._GetFinding._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = finding.Finding() + pb_resp = finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_finding(resp) + return resp + + class _GetScanConfig(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.GetScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.GetScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_config.ScanConfig: + r"""Call the get scan config method over HTTP. + + Args: + request (~.web_security_scanner.GetScanConfigRequest): + The request object. Request for the ``GetScanConfig`` method. + retry (google.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. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_http_options() + request, metadata = self._interceptor.pre_get_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._GetScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_config(resp) + return resp + + class _GetScanRun(_BaseWebSecurityScannerRestTransport._BaseGetScanRun, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.GetScanRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.GetScanRunRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_run.ScanRun: + r"""Call the get scan run method over HTTP. + + Args: + request (~.web_security_scanner.GetScanRunRequest): + The request object. Request for the ``GetScanRun`` method. + retry (google.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. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_http_options() + request, metadata = self._interceptor.pre_get_scan_run(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._GetScanRun._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_run(resp) + return resp + + class _ListCrawledUrls(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListCrawledUrls") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListCrawledUrlsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListCrawledUrlsResponse: + r"""Call the list crawled urls method over HTTP. + + Args: + request (~.web_security_scanner.ListCrawledUrlsRequest): + The request object. Request for the ``ListCrawledUrls`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListCrawledUrlsResponse: + Response for the ``ListCrawledUrls`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_http_options() + request, metadata = self._interceptor.pre_list_crawled_urls(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListCrawledUrls._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListCrawledUrlsResponse() + pb_resp = web_security_scanner.ListCrawledUrlsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crawled_urls(resp) + return resp + + class _ListFindings(_BaseWebSecurityScannerRestTransport._BaseListFindings, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListFindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingsRequest): + The request object. Request for the ``ListFindings`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListFindingsResponse: + Response for the ``ListFindings`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_http_options() + request, metadata = self._interceptor.pre_list_findings(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListFindings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListFindingsResponse() + pb_resp = web_security_scanner.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListFindingTypeStats(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListFindingTypeStats") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListFindingTypeStatsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""Call the list finding type stats method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingTypeStatsRequest): + The request object. Request for the ``ListFindingTypeStats`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListFindingTypeStatsResponse: + Response for the ``ListFindingTypeStats`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_http_options() + request, metadata = self._interceptor.pre_list_finding_type_stats(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListFindingTypeStats._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListFindingTypeStatsResponse() + pb_resp = web_security_scanner.ListFindingTypeStatsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_finding_type_stats(resp) + return resp + + class _ListScanConfigs(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListScanConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListScanConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListScanConfigsResponse: + r"""Call the list scan configs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanConfigsRequest): + The request object. Request for the ``ListScanConfigs`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListScanConfigsResponse: + Response for the ``ListScanConfigs`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_http_options() + request, metadata = self._interceptor.pre_list_scan_configs(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListScanConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListScanConfigsResponse() + pb_resp = web_security_scanner.ListScanConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_configs(resp) + return resp + + class _ListScanRuns(_BaseWebSecurityScannerRestTransport._BaseListScanRuns, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.ListScanRuns") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: web_security_scanner.ListScanRunsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> web_security_scanner.ListScanRunsResponse: + r"""Call the list scan runs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanRunsRequest): + The request object. Request for the ``ListScanRuns`` method. + retry (google.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. + + Returns: + ~.web_security_scanner.ListScanRunsResponse: + Response for the ``ListScanRuns`` method. + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_http_options() + request, metadata = self._interceptor.pre_list_scan_runs(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._ListScanRuns._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = web_security_scanner.ListScanRunsResponse() + pb_resp = web_security_scanner.ListScanRunsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_runs(resp) + return resp + + class _StartScanRun(_BaseWebSecurityScannerRestTransport._BaseStartScanRun, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.StartScanRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.StartScanRunRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_run.ScanRun: + r"""Call the start scan run method over HTTP. + + Args: + request (~.web_security_scanner.StartScanRunRequest): + The request object. Request for the ``StartScanRun`` method. + retry (google.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. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_http_options() + request, metadata = self._interceptor.pre_start_scan_run(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._StartScanRun._get_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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_start_scan_run(resp) + return resp + + class _StopScanRun(_BaseWebSecurityScannerRestTransport._BaseStopScanRun, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.StopScanRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.StopScanRunRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> scan_run.ScanRun: + r"""Call the stop scan run method over HTTP. + + Args: + request (~.web_security_scanner.StopScanRunRequest): + The request object. Request for the ``StopScanRun`` method. + retry (google.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. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_http_options() + request, metadata = self._interceptor.pre_stop_scan_run(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._StopScanRun._get_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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_stop_scan_run(resp) + return resp + + class _UpdateScanConfig(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig, WebSecurityScannerRestStub): + def __hash__(self): + return hash("WebSecurityScannerRestTransport.UpdateScanConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: web_security_scanner.UpdateScanConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcw_scan_config.ScanConfig: + r"""Call the update scan config method over HTTP. + + Args: + request (~.web_security_scanner.UpdateScanConfigRequest): + The request object. Request for the ``UpdateScanConfigRequest`` method. + retry (google.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. + + Returns: + ~.gcw_scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_http_options() + request, metadata = self._interceptor.pre_update_scan_config(request, metadata) + transcoded_request = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_transcoded_request(http_options, request) + + body = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WebSecurityScannerRestTransport._UpdateScanConfig._get_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 = gcw_scan_config.ScanConfig() + pb_resp = gcw_scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_scan_config(resp) + return resp + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + gcw_scan_config.ScanConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + 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._DeleteScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + finding.Finding]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + scan_config.ScanConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + scan_run.ScanRun]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCrawledUrls(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFindingTypeStats(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScanConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScanRuns(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + scan_run.ScanRun]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StartScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + scan_run.ScanRun]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StopScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + gcw_scan_config.ScanConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WebSecurityScannerRestTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest_base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest_base.py new file mode 100644 index 000000000000..0f5225b1985e --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest_base.py @@ -0,0 +1,617 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 WebSecurityScannerTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + + +class _BaseWebSecurityScannerRestTransport(WebSecurityScannerTransport): + """Base REST backend transport for WebSecurityScanner. + + 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 = 'websecurityscanner.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: 'websecurityscanner.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 _BaseCreateScanConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{parent=projects/*}/scanConfigs', + 'body': 'scan_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.CreateScanConfigRequest.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(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteScanConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{name=projects/*/scanConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.DeleteScanConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetFinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.GetFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetFinding._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetScanConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/scanConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.GetScanConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetScanRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.GetScanRunRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCrawledUrls: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListCrawledUrlsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListFindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "filter" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListFindings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListFindingTypeStats: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListFindingTypeStatsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListScanConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*}/scanConfigs', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListScanConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListScanRuns: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/scanConfigs/*}/scanRuns', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.ListScanRunsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStartScanRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{name=projects/*/scanConfigs/*}:start', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.StartScanRunRequest.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(_BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStopScanRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}:stop', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.StopScanRunRequest.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(_BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateScanConfig: + 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': '/v1beta/{scan_config.name=projects/*/scanConfigs/*}', + 'body': 'scan_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = web_security_scanner.UpdateScanConfigRequest.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(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseWebSecurityScannerRestTransport', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py new file mode 100644 index 000000000000..b1fb4aa1c3eb --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.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 .crawled_url import ( + CrawledUrl, +) +from .finding import ( + Finding, +) +from .finding_addon import ( + Form, + OutdatedLibrary, + ViolatingResource, + VulnerableHeaders, + VulnerableParameters, + Xss, +) +from .finding_type_stats import ( + FindingTypeStats, +) +from .scan_config import ( + ScanConfig, +) +from .scan_config_error import ( + ScanConfigError, +) +from .scan_run import ( + ScanRun, +) +from .scan_run_error_trace import ( + ScanRunErrorTrace, +) +from .scan_run_warning_trace import ( + ScanRunWarningTrace, +) +from .web_security_scanner import ( + CreateScanConfigRequest, + DeleteScanConfigRequest, + GetFindingRequest, + GetScanConfigRequest, + GetScanRunRequest, + ListCrawledUrlsRequest, + ListCrawledUrlsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListFindingTypeStatsRequest, + ListFindingTypeStatsResponse, + ListScanConfigsRequest, + ListScanConfigsResponse, + ListScanRunsRequest, + ListScanRunsResponse, + StartScanRunRequest, + StopScanRunRequest, + UpdateScanConfigRequest, +) + +__all__ = ( + 'CrawledUrl', + 'Finding', + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanConfigError', + 'ScanRun', + 'ScanRunErrorTrace', + 'ScanRunWarningTrace', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py new file mode 100644 index 000000000000..cd27919d0274 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.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.cloud.websecurityscanner.v1beta', + manifest={ + 'CrawledUrl', + }, +) + + +class CrawledUrl(proto.Message): + r"""A CrawledUrl resource represents a URL that was crawled + during a ScanRun. Web Security Scanner Service crawls the web + applications, following all links within the scope of sites, to + find the URLs to test against. + + Attributes: + http_method (str): + The http method of the request that was used + to visit the URL, in uppercase. + url (str): + The URL that was crawled. + body (str): + The body of the request that was used to + visit the URL. + """ + + http_method: str = proto.Field( + proto.STRING, + number=1, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + body: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py new file mode 100644 index 000000000000..7dbf038192cb --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner_v1beta.types import finding_addon + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""A Finding resource represents a vulnerability instance + identified during a ScanRun. + + Attributes: + name (str): + The resource name of the Finding. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. + The finding IDs are generated by the system. + finding_type (str): + The type of the Finding. + Detailed and up-to-date information on findings + can be found here: + + https://cloud.google.com/security-scanner/docs/scan-result-details + http_method (str): + The http method of the request that triggered + the vulnerability, in uppercase. + fuzzed_url (str): + The URL produced by the server-side fuzzer + and used in the request that triggered the + vulnerability. + body (str): + The body of the request that triggered the + vulnerability. + description (str): + The description of the vulnerability. + reproduction_url (str): + The URL containing human-readable payload + that user can leverage to reproduce the + vulnerability. + frame_url (str): + If the vulnerability was originated from + nested IFrame, the immediate parent IFrame is + reported. + final_url (str): + The URL where the browser lands when the + vulnerability is detected. + tracking_id (str): + The tracking ID uniquely identifies a + vulnerability instance across multiple ScanRuns. + form (google.cloud.websecurityscanner_v1beta.types.Form): + An addon containing information reported for + a vulnerability with an HTML form, if any. + outdated_library (google.cloud.websecurityscanner_v1beta.types.OutdatedLibrary): + An addon containing information about + outdated libraries. + violating_resource (google.cloud.websecurityscanner_v1beta.types.ViolatingResource): + An addon containing detailed information + regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, + etc. + vulnerable_headers (google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders): + An addon containing information about + vulnerable or missing HTTP headers. + vulnerable_parameters (google.cloud.websecurityscanner_v1beta.types.VulnerableParameters): + An addon containing information about request + parameters which were found to be vulnerable. + xss (google.cloud.websecurityscanner_v1beta.types.Xss): + An addon containing information reported for + an XSS, if any. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + finding_type: str = proto.Field( + proto.STRING, + number=2, + ) + http_method: str = proto.Field( + proto.STRING, + number=3, + ) + fuzzed_url: str = proto.Field( + proto.STRING, + number=4, + ) + body: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + reproduction_url: str = proto.Field( + proto.STRING, + number=7, + ) + frame_url: str = proto.Field( + proto.STRING, + number=8, + ) + final_url: str = proto.Field( + proto.STRING, + number=9, + ) + tracking_id: str = proto.Field( + proto.STRING, + number=10, + ) + form: finding_addon.Form = proto.Field( + proto.MESSAGE, + number=16, + message=finding_addon.Form, + ) + outdated_library: finding_addon.OutdatedLibrary = proto.Field( + proto.MESSAGE, + number=11, + message=finding_addon.OutdatedLibrary, + ) + violating_resource: finding_addon.ViolatingResource = proto.Field( + proto.MESSAGE, + number=12, + message=finding_addon.ViolatingResource, + ) + vulnerable_headers: finding_addon.VulnerableHeaders = proto.Field( + proto.MESSAGE, + number=15, + message=finding_addon.VulnerableHeaders, + ) + vulnerable_parameters: finding_addon.VulnerableParameters = proto.Field( + proto.MESSAGE, + number=13, + message=finding_addon.VulnerableParameters, + ) + xss: finding_addon.Xss = proto.Field( + proto.MESSAGE, + number=14, + message=finding_addon.Xss, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py new file mode 100644 index 000000000000..43f2fac68a72 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableParameters', + 'VulnerableHeaders', + 'Xss', + }, +) + + +class Form(proto.Message): + r"""! Information about a vulnerability with an HTML. + + Attributes: + action_uri (str): + ! The URI where to send the form when it's + submitted. + fields (MutableSequence[str]): + ! The names of form fields related to the + vulnerability. + """ + + action_uri: str = proto.Field( + proto.STRING, + number=1, + ) + fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class OutdatedLibrary(proto.Message): + r"""Information reported for an outdated library. + + Attributes: + library_name (str): + The name of the outdated library. + version (str): + The version number. + learn_more_urls (MutableSequence[str]): + URLs to learn more information about the + vulnerabilities in the library. + """ + + library_name: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + learn_more_urls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ViolatingResource(proto.Message): + r"""Information regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, etc. + + Attributes: + content_type (str): + The MIME type of this resource. + resource_url (str): + URL of this violating resource. + """ + + content_type: str = proto.Field( + proto.STRING, + number=1, + ) + resource_url: str = proto.Field( + proto.STRING, + number=2, + ) + + +class VulnerableParameters(proto.Message): + r"""Information about vulnerable request parameters. + + Attributes: + parameter_names (MutableSequence[str]): + The vulnerable parameter names. + """ + + parameter_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class VulnerableHeaders(proto.Message): + r"""Information about vulnerable or missing HTTP Headers. + + Attributes: + headers (MutableSequence[google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders.Header]): + List of vulnerable headers. + missing_headers (MutableSequence[google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders.Header]): + List of missing headers. + """ + + class Header(proto.Message): + r"""Describes a HTTP Header. + + Attributes: + name (str): + Header name. + value (str): + Header value. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + headers: MutableSequence[Header] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Header, + ) + missing_headers: MutableSequence[Header] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Header, + ) + + +class Xss(proto.Message): + r"""Information reported for an XSS. + + Attributes: + stack_traces (MutableSequence[str]): + Stack traces leading to the point where the + XSS occurred. + error_message (str): + An error message generated by a javascript + breakage. + """ + + stack_traces: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py new file mode 100644 index 000000000000..23166655b9b3 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'FindingTypeStats', + }, +) + + +class FindingTypeStats(proto.Message): + r"""A FindingTypeStats resource represents stats regarding a + specific FindingType of Findings under a given ScanRun. + + Attributes: + finding_type (str): + The finding type associated with the stats. + finding_count (int): + The count of findings belonging to this + finding type. + """ + + finding_type: str = proto.Field( + proto.STRING, + number=1, + ) + finding_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py new file mode 100644 index 000000000000..8ce53ebfbd04 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner_v1beta.types import scan_run +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'ScanConfig', + }, +) + + +class ScanConfig(proto.Message): + r"""A ScanConfig resource contains the configurations to launch a + scan. + + Attributes: + name (str): + The resource name of the ScanConfig. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + The ScanConfig IDs are generated by the system. + display_name (str): + Required. The user provided display name of + the ScanConfig. + max_qps (int): + The maximum QPS during scanning. A valid value ranges from 5 + to 20 inclusively. If the field is unspecified or its value + is set 0, server will default to 15. Other values outside of + [5, 20] range will be rejected with INVALID_ARGUMENT error. + starting_urls (MutableSequence[str]): + Required. The starting URLs from which the + scanner finds site pages. + authentication (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication): + The authentication configuration. If + specified, service will use the authentication + configuration during scanning. + user_agent (google.cloud.websecurityscanner_v1beta.types.ScanConfig.UserAgent): + The user agent used during scanning. + blacklist_patterns (MutableSequence[str]): + The blacklist URL patterns as described in + https://cloud.google.com/security-scanner/docs/excluded-urls + schedule (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Schedule): + The schedule of the ScanConfig. + target_platforms (MutableSequence[google.cloud.websecurityscanner_v1beta.types.ScanConfig.TargetPlatform]): + Set of Cloud Platforms targeted by the scan. If empty, + APP_ENGINE will be used as a default. + export_to_security_command_center (google.cloud.websecurityscanner_v1beta.types.ScanConfig.ExportToSecurityCommandCenter): + Controls export of scan configurations and + results to Cloud Security Command Center. + latest_run (google.cloud.websecurityscanner_v1beta.types.ScanRun): + Latest ScanRun if available. + risk_level (google.cloud.websecurityscanner_v1beta.types.ScanConfig.RiskLevel): + The risk level selected for the scan + """ + class UserAgent(proto.Enum): + r"""Type of user agents used for scanning. + + Values: + USER_AGENT_UNSPECIFIED (0): + The user agent is unknown. Service will default to + CHROME_LINUX. + CHROME_LINUX (1): + Chrome on Linux. This is the service default + if unspecified. + CHROME_ANDROID (2): + Chrome on Android. + SAFARI_IPHONE (3): + Safari on IPhone. + """ + USER_AGENT_UNSPECIFIED = 0 + CHROME_LINUX = 1 + CHROME_ANDROID = 2 + SAFARI_IPHONE = 3 + + class TargetPlatform(proto.Enum): + r"""Cloud platforms supported by Cloud Web Security Scanner. + + Values: + TARGET_PLATFORM_UNSPECIFIED (0): + The target platform is unknown. Requests with this enum + value will be rejected with INVALID_ARGUMENT error. + APP_ENGINE (1): + Google App Engine service. + COMPUTE (2): + Google Compute Engine service. + """ + TARGET_PLATFORM_UNSPECIFIED = 0 + APP_ENGINE = 1 + COMPUTE = 2 + + class RiskLevel(proto.Enum): + r"""Scan risk levels supported by Cloud Web Security Scanner. LOW + impact scanning will minimize requests with the potential to + modify data. To achieve the maximum scan coverage, NORMAL risk + level is recommended. + + Values: + RISK_LEVEL_UNSPECIFIED (0): + Use default, which is NORMAL. + NORMAL (1): + Normal scanning (Recommended) + LOW (2): + Lower impact scanning + """ + RISK_LEVEL_UNSPECIFIED = 0 + NORMAL = 1 + LOW = 2 + + class ExportToSecurityCommandCenter(proto.Enum): + r"""Controls export of scan configurations and results to Cloud + Security Command Center. + + Values: + EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED (0): + Use default, which is ENABLED. + ENABLED (1): + Export results of this scan to Cloud Security + Command Center. + DISABLED (2): + Do not export results of this scan to Cloud + Security Command Center. + """ + EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + + class Authentication(proto.Message): + r"""Scan authentication configuration. + + 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_account (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication.GoogleAccount): + Authentication using a Google account. + + This field is a member of `oneof`_ ``authentication``. + custom_account (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication.CustomAccount): + Authentication using a custom account. + + This field is a member of `oneof`_ ``authentication``. + """ + + class GoogleAccount(proto.Message): + r"""Describes authentication configuration that uses a Google + account. + + Attributes: + username (str): + Required. The user name of the Google + account. + password (str): + Required. Input only. The password of the + Google account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + """ + + username: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + + class CustomAccount(proto.Message): + r"""Describes authentication configuration that uses a custom + account. + + Attributes: + username (str): + Required. The user name of the custom + account. + password (str): + Required. Input only. The password of the + custom account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + login_url (str): + Required. The login form URL of the website. + """ + + username: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + login_url: str = proto.Field( + proto.STRING, + number=3, + ) + + google_account: 'ScanConfig.Authentication.GoogleAccount' = proto.Field( + proto.MESSAGE, + number=1, + oneof='authentication', + message='ScanConfig.Authentication.GoogleAccount', + ) + custom_account: 'ScanConfig.Authentication.CustomAccount' = proto.Field( + proto.MESSAGE, + number=2, + oneof='authentication', + message='ScanConfig.Authentication.CustomAccount', + ) + + class Schedule(proto.Message): + r"""Scan schedule configuration. + + Attributes: + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + A timestamp indicates when the next run will + be scheduled. The value is refreshed by the + server after each run. If unspecified, it will + default to current server time, which means the + scan will be scheduled to start immediately. + interval_duration_days (int): + Required. The duration of time between + executions in days. + """ + + schedule_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + interval_duration_days: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + max_qps: int = proto.Field( + proto.INT32, + number=3, + ) + starting_urls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + authentication: Authentication = proto.Field( + proto.MESSAGE, + number=5, + message=Authentication, + ) + user_agent: UserAgent = proto.Field( + proto.ENUM, + number=6, + enum=UserAgent, + ) + blacklist_patterns: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + schedule: Schedule = proto.Field( + proto.MESSAGE, + number=8, + message=Schedule, + ) + target_platforms: MutableSequence[TargetPlatform] = proto.RepeatedField( + proto.ENUM, + number=9, + enum=TargetPlatform, + ) + export_to_security_command_center: ExportToSecurityCommandCenter = proto.Field( + proto.ENUM, + number=10, + enum=ExportToSecurityCommandCenter, + ) + latest_run: scan_run.ScanRun = proto.Field( + proto.MESSAGE, + number=11, + message=scan_run.ScanRun, + ) + risk_level: RiskLevel = proto.Field( + proto.ENUM, + number=12, + enum=RiskLevel, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py new file mode 100644 index 000000000000..9e301d626790 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner.v1beta', + manifest={ + 'ScanConfigError', + }, +) + + +class ScanConfigError(proto.Message): + r"""Defines a custom error message used by CreateScanConfig and + UpdateScanConfig APIs when scan configuration validation fails. + It is also reported as part of a ScanRunErrorTrace message if + scan validation fails due to a scan configuration error. + + Attributes: + code (google.cloud.websecurityscanner_v1beta.types.ScanConfigError.Code): + Indicates the reason code for a configuration + failure. + field_name (str): + Indicates the full name of the ScanConfig field that + triggers this error, for example "scan_config.max_qps". This + field is provided for troubleshooting purposes only and its + actual value can change in the future. + """ + class Code(proto.Enum): + r"""Output only. + Defines an error reason code. + Next id: 44 + + Values: + CODE_UNSPECIFIED (0): + There is no error. + OK (0): + There is no error. + INTERNAL_ERROR (1): + Indicates an internal server error. + Please DO NOT USE THIS ERROR CODE unless the + root cause is truly unknown. + APPENGINE_API_BACKEND_ERROR (2): + One of the seed URLs is an App Engine URL but + we cannot validate the scan settings due to an + App Engine API backend error. + APPENGINE_API_NOT_ACCESSIBLE (3): + One of the seed URLs is an App Engine URL but + we cannot access the App Engine API to validate + scan settings. + APPENGINE_DEFAULT_HOST_MISSING (4): + One of the seed URLs is an App Engine URL but + the Default Host of the App Engine is not set. + CANNOT_USE_GOOGLE_COM_ACCOUNT (6): + Google corporate accounts can not be used for + scanning. + CANNOT_USE_OWNER_ACCOUNT (7): + The account of the scan creator can not be + used for scanning. + COMPUTE_API_BACKEND_ERROR (8): + This scan targets Compute Engine, but we + cannot validate scan settings due to a Compute + Engine API backend error. + COMPUTE_API_NOT_ACCESSIBLE (9): + This scan targets Compute Engine, but we + cannot access the Compute Engine API to validate + the scan settings. + CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT (10): + The Custom Login URL does not belong to the + current project. + CUSTOM_LOGIN_URL_MALFORMED (11): + The Custom Login URL is malformed (can not be + parsed). + CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS (12): + The Custom Login URL is mapped to a + non-routable IP address in DNS. + CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS (13): + The Custom Login URL is mapped to an IP + address which is not reserved for the current + project. + CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS (14): + The Custom Login URL has a non-routable IP + address. + CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS (15): + The Custom Login URL has an IP address which + is not reserved for the current project. + DUPLICATE_SCAN_NAME (16): + Another scan with the same name + (case-sensitive) already exists. + INVALID_FIELD_VALUE (18): + A field is set to an invalid value. + FAILED_TO_AUTHENTICATE_TO_TARGET (19): + There was an error trying to authenticate to + the scan target. + FINDING_TYPE_UNSPECIFIED (20): + Finding type value is not specified in the + list findings request. + FORBIDDEN_TO_SCAN_COMPUTE (21): + Scan targets Compute Engine, yet current + project was not whitelisted for Google Compute + Engine Scanning Alpha access. + FORBIDDEN_UPDATE_TO_MANAGED_SCAN (43): + User tries to update managed scan + MALFORMED_FILTER (22): + The supplied filter is malformed. For + example, it can not be parsed, does not have a + filter type in expression, or the same filter + type appears more than once. + MALFORMED_RESOURCE_NAME (23): + The supplied resource name is malformed (can + not be parsed). + PROJECT_INACTIVE (24): + The current project is not in an active + state. + REQUIRED_FIELD (25): + A required field is not set. + RESOURCE_NAME_INCONSISTENT (26): + Project id, scanconfig id, scanrun id, or + finding id are not consistent with each other in + resource name. + SCAN_ALREADY_RUNNING (27): + The scan being requested to start is already + running. + SCAN_NOT_RUNNING (28): + The scan that was requested to be stopped is + not running. + SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT (29): + One of the seed URLs does not belong to the + current project. + SEED_URL_MALFORMED (30): + One of the seed URLs is malformed (can not be + parsed). + SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS (31): + One of the seed URLs is mapped to a + non-routable IP address in DNS. + SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS (32): + One of the seed URLs is mapped to an IP + address which is not reserved for the current + project. + SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS (33): + One of the seed URLs has on-routable IP + address. + SEED_URL_HAS_UNRESERVED_IP_ADDRESS (35): + One of the seed URLs has an IP address that + is not reserved for the current project. + SERVICE_ACCOUNT_NOT_CONFIGURED (36): + The Cloud Security Scanner service account is + not configured under the project. + TOO_MANY_SCANS (37): + A project has reached the maximum number of + scans. + UNABLE_TO_RESOLVE_PROJECT_INFO (38): + Resolving the details of the current project + fails. + UNSUPPORTED_BLACKLIST_PATTERN_FORMAT (39): + One or more blacklist patterns were in the + wrong format. + UNSUPPORTED_FILTER (40): + The supplied filter is not supported. + UNSUPPORTED_FINDING_TYPE (41): + The supplied finding type is not supported. + For example, we do not provide findings of the + given finding type. + UNSUPPORTED_URL_SCHEME (42): + The URL scheme of one or more of the supplied + URLs is not supported. + """ + _pb_options = {'allow_alias': True} + CODE_UNSPECIFIED = 0 + OK = 0 + INTERNAL_ERROR = 1 + APPENGINE_API_BACKEND_ERROR = 2 + APPENGINE_API_NOT_ACCESSIBLE = 3 + APPENGINE_DEFAULT_HOST_MISSING = 4 + CANNOT_USE_GOOGLE_COM_ACCOUNT = 6 + CANNOT_USE_OWNER_ACCOUNT = 7 + COMPUTE_API_BACKEND_ERROR = 8 + COMPUTE_API_NOT_ACCESSIBLE = 9 + CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 10 + CUSTOM_LOGIN_URL_MALFORMED = 11 + CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 12 + CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS = 13 + CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 14 + CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS = 15 + DUPLICATE_SCAN_NAME = 16 + INVALID_FIELD_VALUE = 18 + FAILED_TO_AUTHENTICATE_TO_TARGET = 19 + FINDING_TYPE_UNSPECIFIED = 20 + FORBIDDEN_TO_SCAN_COMPUTE = 21 + FORBIDDEN_UPDATE_TO_MANAGED_SCAN = 43 + MALFORMED_FILTER = 22 + MALFORMED_RESOURCE_NAME = 23 + PROJECT_INACTIVE = 24 + REQUIRED_FIELD = 25 + RESOURCE_NAME_INCONSISTENT = 26 + SCAN_ALREADY_RUNNING = 27 + SCAN_NOT_RUNNING = 28 + SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 29 + SEED_URL_MALFORMED = 30 + SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 31 + SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS = 32 + SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 33 + SEED_URL_HAS_UNRESERVED_IP_ADDRESS = 35 + SERVICE_ACCOUNT_NOT_CONFIGURED = 36 + TOO_MANY_SCANS = 37 + UNABLE_TO_RESOLVE_PROJECT_INFO = 38 + UNSUPPORTED_BLACKLIST_PATTERN_FORMAT = 39 + UNSUPPORTED_FILTER = 40 + UNSUPPORTED_FINDING_TYPE = 41 + UNSUPPORTED_URL_SCHEME = 42 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + field_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py new file mode 100644 index 000000000000..0afd6f989f90 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner_v1beta.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'ScanRun', + }, +) + + +class ScanRun(proto.Message): + r"""A ScanRun is a output-only resource representing an actual + run of the scan. Next id: 12 + + Attributes: + name (str): + The resource name of the ScanRun. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + The ScanRun IDs are generated by the system. + execution_state (google.cloud.websecurityscanner_v1beta.types.ScanRun.ExecutionState): + The execution state of the ScanRun. + result_state (google.cloud.websecurityscanner_v1beta.types.ScanRun.ResultState): + The result state of the ScanRun. This field + is only available after the execution state + reaches "FINISHED". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the ScanRun started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the ScanRun reached + termination state - that the ScanRun is either + finished or stopped by user. + urls_crawled_count (int): + The number of URLs crawled during this + ScanRun. If the scan is in progress, the value + represents the number of URLs crawled up to now. + urls_tested_count (int): + The number of URLs tested during this + ScanRun. If the scan is in progress, the value + represents the number of URLs tested up to now. + The number of URLs tested is usually larger than + the number URLS crawled because typically a + crawled URL is tested with multiple test + payloads. + has_vulnerabilities (bool): + Whether the scan run has found any + vulnerabilities. + progress_percent (int): + The percentage of total completion ranging + from 0 to 100. If the scan is in queue, the + value is 0. If the scan is running, the value + ranges from 0 to 100. If the scan is finished, + the value is 100. + error_trace (google.cloud.websecurityscanner_v1beta.types.ScanRunErrorTrace): + If result_state is an ERROR, this field provides the primary + reason for scan's termination and more details, if such are + available. + warning_traces (MutableSequence[google.cloud.websecurityscanner_v1beta.types.ScanRunWarningTrace]): + A list of warnings, if such are encountered + during this scan run. + """ + class ExecutionState(proto.Enum): + r"""Types of ScanRun execution state. + + Values: + EXECUTION_STATE_UNSPECIFIED (0): + Represents an invalid state caused by + internal server error. This value should never + be returned. + QUEUED (1): + The scan is waiting in the queue. + SCANNING (2): + The scan is in progress. + FINISHED (3): + The scan is either finished or stopped by + user. + """ + EXECUTION_STATE_UNSPECIFIED = 0 + QUEUED = 1 + SCANNING = 2 + FINISHED = 3 + + class ResultState(proto.Enum): + r"""Types of ScanRun result state. + + Values: + RESULT_STATE_UNSPECIFIED (0): + Default value. This value is returned when + the ScanRun is not yet finished. + SUCCESS (1): + The scan finished without errors. + ERROR (2): + The scan finished with errors. + KILLED (3): + The scan was terminated by user. + """ + RESULT_STATE_UNSPECIFIED = 0 + SUCCESS = 1 + ERROR = 2 + KILLED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + execution_state: ExecutionState = proto.Field( + proto.ENUM, + number=2, + enum=ExecutionState, + ) + result_state: ResultState = proto.Field( + proto.ENUM, + number=3, + enum=ResultState, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + urls_crawled_count: int = proto.Field( + proto.INT64, + number=6, + ) + urls_tested_count: int = proto.Field( + proto.INT64, + number=7, + ) + has_vulnerabilities: bool = proto.Field( + proto.BOOL, + number=8, + ) + progress_percent: int = proto.Field( + proto.INT32, + number=9, + ) + error_trace: scan_run_error_trace.ScanRunErrorTrace = proto.Field( + proto.MESSAGE, + number=10, + message=scan_run_error_trace.ScanRunErrorTrace, + ) + warning_traces: MutableSequence[scan_run_warning_trace.ScanRunWarningTrace] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=scan_run_warning_trace.ScanRunWarningTrace, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py new file mode 100644 index 000000000000..97e6976dec77 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner_v1beta.types import scan_config_error as gcw_scan_config_error + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'ScanRunErrorTrace', + }, +) + + +class ScanRunErrorTrace(proto.Message): + r"""Output only. + Defines an error trace message for a ScanRun. + + Attributes: + code (google.cloud.websecurityscanner_v1beta.types.ScanRunErrorTrace.Code): + Indicates the error reason code. + scan_config_error (google.cloud.websecurityscanner_v1beta.types.ScanConfigError): + If the scan encounters SCAN_CONFIG_ISSUE error, this field + has the error message encountered during scan configuration + validation that is performed before each scan run. + most_common_http_error_code (int): + If the scan encounters TOO_MANY_HTTP_ERRORS, this field + indicates the most common HTTP error code, if such is + available. For example, if this code is 404, the scan has + encountered too many NOT_FOUND responses. + """ + class Code(proto.Enum): + r"""Output only. + Defines an error reason code. + Next id: 7 + + Values: + CODE_UNSPECIFIED (0): + Default value is never used. + INTERNAL_ERROR (1): + Indicates that the scan run failed due to an + internal server error. + SCAN_CONFIG_ISSUE (2): + Indicates a scan configuration error, usually due to + outdated ScanConfig settings, such as starting_urls or the + DNS configuration. + AUTHENTICATION_CONFIG_ISSUE (3): + Indicates an authentication error, usually + due to outdated ScanConfig authentication + settings. + TIMED_OUT_WHILE_SCANNING (4): + Indicates a scan operation timeout, usually + caused by a very large site. + TOO_MANY_REDIRECTS (5): + Indicates that a scan encountered excessive + redirects, either to authentication or some + other page outside of the scan scope. + TOO_MANY_HTTP_ERRORS (6): + Indicates that a scan encountered numerous errors from the + web site pages. When available, most_common_http_error_code + field indicates the most common HTTP error code encountered + during the scan. + """ + CODE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + SCAN_CONFIG_ISSUE = 2 + AUTHENTICATION_CONFIG_ISSUE = 3 + TIMED_OUT_WHILE_SCANNING = 4 + TOO_MANY_REDIRECTS = 5 + TOO_MANY_HTTP_ERRORS = 6 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + scan_config_error: gcw_scan_config_error.ScanConfigError = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config_error.ScanConfigError, + ) + most_common_http_error_code: int = proto.Field( + proto.INT32, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py new file mode 100644 index 000000000000..c603b733380e --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.websecurityscanner.v1beta', + manifest={ + 'ScanRunWarningTrace', + }, +) + + +class ScanRunWarningTrace(proto.Message): + r"""Output only. + Defines a warning trace message for ScanRun. Warning traces + provide customers with useful information that helps make the + scanning process more effective. + + Attributes: + code (google.cloud.websecurityscanner_v1beta.types.ScanRunWarningTrace.Code): + Indicates the warning code. + """ + class Code(proto.Enum): + r"""Output only. + Defines a warning message code. + Next id: 6 + + Values: + CODE_UNSPECIFIED (0): + Default value is never used. + INSUFFICIENT_CRAWL_RESULTS (1): + Indicates that a scan discovered an + unexpectedly low number of URLs. This is + sometimes caused by complex navigation features + or by using a single URL for numerous pages. + TOO_MANY_CRAWL_RESULTS (2): + Indicates that a scan discovered too many + URLs to test, or excessive redundant URLs. + TOO_MANY_FUZZ_TASKS (3): + Indicates that too many tests have been + generated for the scan. Customer should try + reducing the number of starting URLs, increasing + the QPS rate, or narrowing down the scope of the + scan using the excluded patterns. + BLOCKED_BY_IAP (4): + Indicates that a scan is blocked by IAP. + """ + CODE_UNSPECIFIED = 0 + INSUFFICIENT_CRAWL_RESULTS = 1 + TOO_MANY_CRAWL_RESULTS = 2 + TOO_MANY_FUZZ_TASKS = 3 + BLOCKED_BY_IAP = 4 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py new file mode 100644 index 000000000000..4a19eeb9d038 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import finding_type_stats as gcw_finding_type_stats +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetScanConfigRequest', + 'ListScanConfigsRequest', + 'UpdateScanConfigRequest', + 'ListScanConfigsResponse', + 'StartScanRunRequest', + 'GetScanRunRequest', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StopScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'GetFindingRequest', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + }, +) + + +class CreateScanConfigRequest(proto.Message): + r"""Request for the ``CreateScanConfig`` method. + + Attributes: + parent (str): + Required. The parent resource name where the + scan is created, which should be a project + resource name in the format + 'projects/{projectId}'. + scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): + Required. The ScanConfig to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + scan_config: gcw_scan_config.ScanConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + + +class DeleteScanConfigRequest(proto.Message): + r"""Request for the ``DeleteScanConfig`` method. + + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be deleted. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanConfigRequest(proto.Message): + r"""Request for the ``GetScanConfig`` method. + + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanConfigsRequest(proto.Message): + r"""Request for the ``ListScanConfigs`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a project resource name in the format + 'projects/{projectId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanConfigs to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class UpdateScanConfigRequest(proto.Message): + r"""Request for the ``UpdateScanConfigRequest`` method. + + Attributes: + scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): + Required. The ScanConfig to be updated. The + name field must be set to identify the resource + to be updated. The values of fields not covered + by the mask will be ignored. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For the + ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + """ + + scan_config: gcw_scan_config.ScanConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ListScanConfigsResponse(proto.Message): + r"""Response for the ``ListScanConfigs`` method. + + Attributes: + scan_configs (MutableSequence[google.cloud.websecurityscanner_v1beta.types.ScanConfig]): + The list of ScanConfigs returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_configs: MutableSequence[gcw_scan_config.ScanConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_scan_config.ScanConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class StartScanRunRequest(proto.Message): + r"""Request for the ``StartScanRun`` method. + + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be used. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanRunRequest(proto.Message): + r"""Request for the ``GetScanRun`` method. + + Attributes: + name (str): + Required. The resource name of the ScanRun to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanRunsRequest(proto.Message): + r"""Request for the ``ListScanRuns`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanRuns to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListScanRunsResponse(proto.Message): + r"""Response for the ``ListScanRuns`` method. + + Attributes: + scan_runs (MutableSequence[google.cloud.websecurityscanner_v1beta.types.ScanRun]): + The list of ScanRuns returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_runs: MutableSequence[scan_run.ScanRun] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=scan_run.ScanRun, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class StopScanRunRequest(proto.Message): + r"""Request for the ``StopScanRun`` method. + + Attributes: + name (str): + Required. The resource name of the ScanRun to + be stopped. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCrawledUrlsRequest(proto.Message): + r"""Request for the ``ListCrawledUrls`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of CrawledUrls to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCrawledUrlsResponse(proto.Message): + r"""Response for the ``ListCrawledUrls`` method. + + Attributes: + crawled_urls (MutableSequence[google.cloud.websecurityscanner_v1beta.types.CrawledUrl]): + The list of CrawledUrls returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + crawled_urls: MutableSequence[crawled_url.CrawledUrl] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=crawled_url.CrawledUrl, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFindingRequest(proto.Message): + r"""Request for the ``GetFinding`` method. + + Attributes: + name (str): + Required. The resource name of the Finding to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request for the ``ListFindings`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + filter (str): + Required. The filter expression. The expression must be in + the format: . Supported field: 'finding_type'. Supported + operator: '='. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of Findings to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response for the ``ListFindings`` method. + + Attributes: + findings (MutableSequence[google.cloud.websecurityscanner_v1beta.types.Finding]): + The list of Findings returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + findings: MutableSequence[finding.Finding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=finding.Finding, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFindingTypeStatsRequest(proto.Message): + r"""Request for the ``ListFindingTypeStats`` method. + + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingTypeStatsResponse(proto.Message): + r"""Response for the ``ListFindingTypeStats`` method. + + Attributes: + finding_type_stats (MutableSequence[google.cloud.websecurityscanner_v1beta.types.FindingTypeStats]): + The list of FindingTypeStats returned. + """ + + finding_type_stats: MutableSequence[gcw_finding_type_stats.FindingTypeStats] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_finding_type_stats.FindingTypeStats, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/mypy.ini b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/noxfile.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/noxfile.py new file mode 100644 index 000000000000..71f9c4528104 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner' + +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/cloud/websecurityscanner_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/cloud/websecurityscanner_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-cloud-websecurityscanner/v1beta/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json new file mode 100644 index 000000000000..3896b1676525 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json @@ -0,0 +1,2126 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.websecurityscanner.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-websecurityscanner", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.create_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.CreateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "CreateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "scan_config", + "type": "google.cloud.websecurityscanner_v1beta.types.ScanConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", + "shortName": "create_scan_config" + }, + "description": "Sample for CreateScanConfig", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.create_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.CreateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "CreateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "scan_config", + "type": "google.cloud.websecurityscanner_v1beta.types.ScanConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", + "shortName": "create_scan_config" + }, + "description": "Sample for CreateScanConfig", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.delete_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.DeleteScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "DeleteScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_scan_config" + }, + "description": "Sample for DeleteScanConfig", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.delete_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.DeleteScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "DeleteScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_scan_config" + }, + "description": "Sample for DeleteScanConfig", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.get_finding", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetFinding", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.GetFindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.Finding", + "shortName": "get_finding" + }, + "description": "Sample for GetFinding", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.get_finding", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetFinding", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.GetFindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.Finding", + "shortName": "get_finding" + }, + "description": "Sample for GetFinding", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.get_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", + "shortName": "get_scan_config" + }, + "description": "Sample for GetScanConfig", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.get_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", + "shortName": "get_scan_config" + }, + "description": "Sample for GetScanConfig", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.get_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", + "shortName": "get_scan_run" + }, + "description": "Sample for GetScanRun", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.get_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "GetScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", + "shortName": "get_scan_run" + }, + "description": "Sample for GetScanRun", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_crawled_urls", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListCrawledUrls", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListCrawledUrls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager", + "shortName": "list_crawled_urls" + }, + "description": "Sample for ListCrawledUrls", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_crawled_urls", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListCrawledUrls", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListCrawledUrls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsPager", + "shortName": "list_crawled_urls" + }, + "description": "Sample for ListCrawledUrls", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_finding_type_stats", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListFindingTypeStats", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindingTypeStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse", + "shortName": "list_finding_type_stats" + }, + "description": "Sample for ListFindingTypeStats", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_finding_type_stats", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListFindingTypeStats", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindingTypeStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse", + "shortName": "list_finding_type_stats" + }, + "description": "Sample for ListFindingTypeStats", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListFindings", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest" + }, + { + "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, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_findings", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListFindings", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest" + }, + { + "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, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_scan_configs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListScanConfigs", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsAsyncPager", + "shortName": "list_scan_configs" + }, + "description": "Sample for ListScanConfigs", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_scan_configs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListScanConfigs", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsPager", + "shortName": "list_scan_configs" + }, + "description": "Sample for ListScanConfigs", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_scan_runs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListScanRuns", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsAsyncPager", + "shortName": "list_scan_runs" + }, + "description": "Sample for ListScanRuns", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_scan_runs", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListScanRuns", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "ListScanRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsPager", + "shortName": "list_scan_runs" + }, + "description": "Sample for ListScanRuns", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.start_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.StartScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StartScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", + "shortName": "start_scan_run" + }, + "description": "Sample for StartScanRun", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.start_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.StartScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StartScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", + "shortName": "start_scan_run" + }, + "description": "Sample for StartScanRun", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.stop_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.StopScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StopScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", + "shortName": "stop_scan_run" + }, + "description": "Sample for StopScanRun", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.stop_scan_run", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.StopScanRun", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "StopScanRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", + "shortName": "stop_scan_run" + }, + "description": "Sample for StopScanRun", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", + "shortName": "WebSecurityScannerAsyncClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.update_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.UpdateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "UpdateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest" + }, + { + "name": "scan_config", + "type": "google.cloud.websecurityscanner_v1beta.types.ScanConfig" + }, + { + "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, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", + "shortName": "update_scan_config" + }, + "description": "Sample for UpdateScanConfig", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", + "shortName": "WebSecurityScannerClient" + }, + "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.update_scan_config", + "method": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.UpdateScanConfig", + "service": { + "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", + "shortName": "WebSecurityScanner" + }, + "shortName": "UpdateScanConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest" + }, + { + "name": "scan_config", + "type": "google.cloud.websecurityscanner_v1beta.types.ScanConfig" + }, + { + "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, str]" + } + ], + "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", + "shortName": "update_scan_config" + }, + "description": "Sample for UpdateScanConfig", + "file": "websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py new file mode 100644 index 000000000000..b69fdbd77cdf --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_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 CreateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1beta.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1beta.CreateScanConfigRequest( + parent="parent_value", + scan_config=scan_config, + ) + + # Make the request + response = await client.create_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py new file mode 100644 index 000000000000..6fe99be4457b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_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 CreateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_create_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1beta.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1beta.CreateScanConfigRequest( + parent="parent_value", + scan_config=scan_config, + ) + + # Make the request + response = client.create_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py new file mode 100644 index 000000000000..844e1b3a81cc --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_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 DeleteScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.DeleteScanConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_scan_config(request=request) + + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py new file mode 100644 index 000000000000..41f63690845d --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_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 DeleteScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_delete_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.DeleteScanConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_scan_config(request=request) + + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py new file mode 100644 index 000000000000..196cfe27ed50 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_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 GetFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_get_finding(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetFindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_finding(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py new file mode 100644 index 000000000000..bfa360711c75 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_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 GetFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_get_finding(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetFindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_finding(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py new file mode 100644 index 000000000000..e49ee7d4fab3 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_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 GetScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetScanConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py new file mode 100644 index 000000000000..29677cd1be18 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_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 GetScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_get_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetScanConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py new file mode 100644 index 000000000000..0f798e6cd152 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_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 GetScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py new file mode 100644 index 000000000000..5fbb1c0e5989 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_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 GetScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_get_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.GetScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.get_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py new file mode 100644 index 000000000000..fa6e68fd9ba6 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListCrawledUrlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py new file mode 100644 index 000000000000..3c159200f640 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_list_crawled_urls(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListCrawledUrlsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crawled_urls(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py new file mode 100644 index 000000000000..11826a1426ca --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListFindingTypeStatsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py new file mode 100644 index 000000000000..619e67e6b80b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_list_finding_type_stats(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListFindingTypeStatsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_finding_type_stats(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py new file mode 100644 index 000000000000..e6500adb0ce4 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_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 ListFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_list_findings(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListFindingsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py new file mode 100644 index 000000000000..f28ebd0c35d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_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 ListFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_list_findings(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListFindingsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py new file mode 100644 index 000000000000..c556ee10a2fc --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListScanConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py new file mode 100644 index 000000000000..85b6f5e9b731 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_list_scan_configs(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListScanConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py new file mode 100644 index 000000000000..48091d8d1bbf --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_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 ListScanRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListScanRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py new file mode 100644 index 000000000000..2667ce75f2bb --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_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 ListScanRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_list_scan_runs(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.ListScanRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scan_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py new file mode 100644 index 000000000000..b8a6de14516c --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_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 StartScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.StartScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.start_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py new file mode 100644 index 000000000000..b60a0d5c70bf --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_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 StartScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_start_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.StartScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.start_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py new file mode 100644 index 000000000000..f4a6d65e2f61 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_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 StopScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.StopScanRunRequest( + name="name_value", + ) + + # Make the request + response = await client.stop_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py new file mode 100644 index 000000000000..63a1f9e5f899 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_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 StopScanRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_stop_scan_run(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + request = websecurityscanner_v1beta.StopScanRunRequest( + name="name_value", + ) + + # Make the request + response = client.stop_scan_run(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py new file mode 100644 index 000000000000..3829aeb7f538 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +async def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1beta.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1beta.UpdateScanConfigRequest( + scan_config=scan_config, + ) + + # Make the request + response = await client.update_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py new file mode 100644 index 000000000000..42579467412b --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-websecurityscanner + + +# [START websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import websecurityscanner_v1beta + + +def sample_update_scan_config(): + # Create a client + client = websecurityscanner_v1beta.WebSecurityScannerClient() + + # Initialize request argument(s) + scan_config = websecurityscanner_v1beta.ScanConfig() + scan_config.display_name = "display_name_value" + scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] + + request = websecurityscanner_v1beta.UpdateScanConfigRequest( + scan_config=scan_config, + ) + + # Make the request + response = client.update_scan_config(request=request) + + # Handle the response + print(response) + +# [END websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py new file mode 100644 index 000000000000..cbe5261ddc2a --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py @@ -0,0 +1,188 @@ +#! /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 websecurityscannerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_scan_config': ('parent', 'scan_config', ), + 'delete_scan_config': ('name', ), + 'get_finding': ('name', ), + 'get_scan_config': ('name', ), + 'get_scan_run': ('name', ), + 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_finding_type_stats': ('parent', ), + 'list_scan_configs': ('parent', 'page_token', 'page_size', ), + 'list_scan_runs': ('parent', 'page_token', 'page_size', ), + 'start_scan_run': ('name', ), + 'stop_scan_run': ('name', ), + 'update_scan_config': ('scan_config', '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=websecurityscannerCallTransformer(), +): + """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 websecurityscanner 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-cloud-websecurityscanner/v1beta/setup.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/setup.py new file mode 100644 index 000000000000..b89eea40fd8f --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner' + + +description = "Google Cloud Websecurityscanner API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/websecurityscanner/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-cloud-websecurityscanner" + +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-cloud-websecurityscanner/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_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-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py new file mode 100644 index 000000000000..8e3982546372 --- /dev/null +++ b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py @@ -0,0 +1,11533 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1beta.services.web_security_scanner import WebSecurityScannerAsyncClient +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import transports +from google.cloud.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import finding_addon +from google.cloud.websecurityscanner_v1beta.types import finding_type_stats +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config_error +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_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 WebSecurityScannerClient._get_default_mtls_endpoint(None) is None + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WebSecurityScannerClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + WebSecurityScannerClient._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 WebSecurityScannerClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WebSecurityScannerClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WebSecurityScannerClient._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 WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, False) is None + assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, True) is mock_default_cert_source + assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE + default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert WebSecurityScannerClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + assert WebSecurityScannerClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + WebSecurityScannerClient._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 WebSecurityScannerClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert WebSecurityScannerClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert WebSecurityScannerClient._get_universe_domain(None, None) == WebSecurityScannerClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + WebSecurityScannerClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WebSecurityScannerClient, "grpc"), + (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), +]) +def test_web_security_scanner_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 == ( + 'websecurityscanner.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://websecurityscanner.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WebSecurityScannerGrpcTransport, "grpc"), + (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WebSecurityScannerRestTransport, "rest"), +]) +def test_web_security_scanner_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", [ + (WebSecurityScannerClient, "grpc"), + (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), +]) +def test_web_security_scanner_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 == ( + 'websecurityscanner.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://websecurityscanner.googleapis.com' + ) + + +def test_web_security_scanner_client_get_transport_class(): + transport = WebSecurityScannerClient.get_transport_class() + available_transports = [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerRestTransport, + ] + assert transport in available_transports + + transport = WebSecurityScannerClient.get_transport_class("grpc") + assert transport == transports.WebSecurityScannerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), +]) +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_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(WebSecurityScannerClient, '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(WebSecurityScannerClient, '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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "true"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "false"), +]) +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_web_security_scanner_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", [ + WebSecurityScannerClient, WebSecurityScannerAsyncClient +]) +@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_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", [ + WebSecurityScannerClient, WebSecurityScannerAsyncClient +]) +@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE + default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WebSecurityScannerClient._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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), +]) +def test_web_security_scanner_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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", None), +]) +def test_web_security_scanner_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_web_security_scanner_client_client_options_from_dict(): + with mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WebSecurityScannerClient( + 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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_web_security_scanner_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( + "websecurityscanner.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="websecurityscanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.CreateScanConfigRequest, + dict, +]) +def test_create_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + ) + response = client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.CreateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +def test_create_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.CreateScanConfigRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.CreateScanConfigRequest( + parent='parent_value', + ) + +def test_create_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + request = {} + client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + )) + response = await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.CreateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +@pytest.mark.asyncio +async def test_create_scan_config_async_from_dict(): + await test_create_scan_config_async(request_type=dict) + +def test_create_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_scan_config( + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(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].scan_config + mock_val = gcw_scan_config.ScanConfig(name='name_value') + assert arg == mock_val + + +def test_create_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_scan_config( + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(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].scan_config + mock_val = gcw_scan_config.ScanConfig(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.DeleteScanConfigRequest, + dict, +]) +def test_delete_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.DeleteScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.DeleteScanConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.DeleteScanConfigRequest( + name='name_value', + ) + +def test_delete_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + request = {} + client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.DeleteScanConfigRequest() + 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_scan_config_async_from_dict(): + await test_delete_scan_config_async(request_type=dict) + +def test_delete_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = None + client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__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_scan_config( + 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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__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_scan_config( + 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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanConfigRequest, + dict, +]) +def test_get_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + ) + response = client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + + +def test_get_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.GetScanConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanConfigRequest( + name='name_value', + ) + +def test_get_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc + request = {} + client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + )) + response = await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + + +@pytest.mark.asyncio +async def test_get_scan_config_async_from_dict(): + await test_get_scan_config_async(request_type=dict) + +def test_get_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scan_config( + 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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scan_config( + 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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanConfigsRequest, + dict, +]) +def test_list_scan_configs(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListScanConfigsRequest( + 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_scan_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_scan_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_scan_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_configs] = mock_rpc + request = {} + client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_configs(request) + + # Establish that a new wrapper 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_scan_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_configs in client._client._transport._wrapped_methods + + # 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_scan_configs] = mock_rpc + + request = {} + await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scan_configs(request) + + # Establish that a new wrapper 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_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_configs_async_from_dict(): + await test_list_scan_configs_async(request_type=dict) + +def test_list_scan_configs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanConfigsResponse() + client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_configs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_configs_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scan_configs( + 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_scan_configs_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_scan_configs_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scan_configs( + 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_scan_configs_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + + +def test_list_scan_configs_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_configs(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, scan_config.ScanConfig) + for i in results) +def test_list_scan_configs_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_configs(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_scan_configs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_configs(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, scan_config.ScanConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_scan_configs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + 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_scan_configs(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", [ + web_security_scanner.UpdateScanConfigRequest, + dict, +]) +def test_update_scan_config(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + ) + response = client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.UpdateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +def test_update_scan_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.UpdateScanConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_scan_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.UpdateScanConfigRequest( + ) + +def test_update_scan_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + request = {} + client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_config in client._client._transport._wrapped_methods + + # 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_scan_config] = mock_rpc + + request = {} + await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_scan_config(request) + + # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + )) + response = await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.UpdateScanConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +@pytest.mark.asyncio +async def test_update_scan_config_async_from_dict(): + await test_update_scan_config_async(request_type=dict) + +def test_update_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'scan_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'scan_config.name=name_value', + ) in kw['metadata'] + + +def test_update_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_scan_config( + scan_config=gcw_scan_config.ScanConfig(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].scan_config + mock_val = gcw_scan_config.ScanConfig(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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_scan_config( + scan_config=gcw_scan_config.ScanConfig(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].scan_config + mock_val = gcw_scan_config.ScanConfig(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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.StartScanRunRequest, + dict, +]) +def test_start_scan_run(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StartScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_start_scan_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.StartScanRunRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.start_scan_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest( + name='name_value', + ) + +def test_start_scan_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc + request = {} + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.start_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.start_scan_run in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.start_scan_run] = mock_rpc + + request = {} + await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.start_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StartScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_start_scan_run_async_from_dict(): + await test_start_scan_run_async(request_type=dict) + +def test_start_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_scan_run( + 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_start_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_start_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_scan_run( + 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_start_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanRunRequest, + dict, +]) +def test_get_scan_run(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_get_scan_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.GetScanRunRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_scan_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest( + name='name_value', + ) + +def test_get_scan_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc + request = {} + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_run(request) + + # Establish that a new wrapper 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_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_run in client._client._transport._wrapped_methods + + # 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_scan_run] = mock_rpc + + request = {} + await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scan_run(request) + + # Establish that a new wrapper 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_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_get_scan_run_async_from_dict(): + await test_get_scan_run_async(request_type=dict) + +def test_get_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scan_run( + 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_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scan_run( + 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_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanRunsRequest, + dict, +]) +def test_list_scan_runs(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_runs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListScanRunsRequest( + 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_scan_runs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_scan_runs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_scan_runs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_scan_runs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_runs] = mock_rpc + request = {} + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_runs(request) + + # Establish that a new wrapper 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_scan_runs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_scan_runs in client._client._transport._wrapped_methods + + # 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_scan_runs] = mock_rpc + + request = {} + await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scan_runs(request) + + # Establish that a new wrapper 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_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListScanRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_runs_async_from_dict(): + await test_list_scan_runs_async(request_type=dict) + +def test_list_scan_runs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanRunsResponse() + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_runs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_scan_runs_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scan_runs( + 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_scan_runs_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_scan_runs_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scan_runs( + 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_scan_runs_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + + +def test_list_scan_runs_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_runs(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, scan_run.ScanRun) + for i in results) +def test_list_scan_runs_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_runs(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_scan_runs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_runs(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, scan_run.ScanRun) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_scan_runs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + 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_scan_runs(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", [ + web_security_scanner.StopScanRunRequest, + dict, +]) +def test_stop_scan_run(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StopScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_stop_scan_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.StopScanRunRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.stop_scan_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest( + name='name_value', + ) + +def test_stop_scan_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc + request = {} + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.stop_scan_run in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.stop_scan_run] = mock_rpc + + request = {} + await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.stop_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.StopScanRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_stop_scan_run_async_from_dict(): + await test_stop_scan_run_async(request_type=dict) + +def test_stop_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_scan_run( + 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_stop_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_stop_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_scan_run( + 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_stop_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListCrawledUrlsRequest, + dict, +]) +def test_list_crawled_urls(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListCrawledUrlsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_crawled_urls_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListCrawledUrlsRequest( + 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_crawled_urls), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_crawled_urls(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_crawled_urls_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_crawled_urls in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_crawled_urls] = mock_rpc + request = {} + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crawled_urls(request) + + # Establish that a new wrapper 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_crawled_urls_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_crawled_urls in client._client._transport._wrapped_methods + + # 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_crawled_urls] = mock_rpc + + request = {} + await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_crawled_urls(request) + + # Establish that a new wrapper 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_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListCrawledUrlsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_from_dict(): + await test_list_crawled_urls_async(request_type=dict) + +def test_list_crawled_urls_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crawled_urls_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crawled_urls_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_crawled_urls( + 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_crawled_urls_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_crawled_urls_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_crawled_urls( + 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_crawled_urls_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + + +def test_list_crawled_urls_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crawled_urls(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, crawled_url.CrawledUrl) + for i in results) +def test_list_crawled_urls_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + 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_crawled_urls(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", [ + web_security_scanner.GetFindingRequest, + dict, +]) +def test_get_finding(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + finding_type='finding_type_value', + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + ) + response = client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +def test_get_finding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.GetFindingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetFindingRequest( + name='name_value', + ) + +def test_get_finding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_finding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc + request = {} + client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_finding(request) + + # Establish that a new wrapper 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_finding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # 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_finding] = mock_rpc + + request = {} + await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_finding(request) + + # Establish that a new wrapper 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_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + finding_type='finding_type_value', + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + )) + response = await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.GetFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +@pytest.mark.asyncio +async def test_get_finding_async_from_dict(): + await test_get_finding_async(request_type=dict) + +def test_get_finding_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = finding.Finding() + client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_finding( + 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_finding_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_finding_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_finding( + 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_finding_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_findings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListFindingsRequest( + 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_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_findings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_findings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_findings] = mock_rpc + request = {} + client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_findings(request) + + # Establish that a new wrapper 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_findings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_findings in client._client._transport._wrapped_methods + + # 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_findings] = mock_rpc + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_findings(request) + + # Establish that a new wrapper 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_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + +def test_list_findings_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingsResponse() + client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_findings_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_findings_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_findings( + 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_findings_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_findings( + 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_findings_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_findings_pager(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_findings(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, finding.Finding) + for i in results) +def test_list_findings_pages(transport_name: str = "grpc"): + client = WebSecurityScannerClient( + 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_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_findings(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_findings_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_findings(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, finding.Finding) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + 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_findings(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", [ + web_security_scanner.ListFindingTypeStatsRequest, + dict, +]) +def test_list_finding_type_stats(request_type, transport: str = 'grpc'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse( + ) + response = client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingTypeStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +def test_list_finding_type_stats_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = web_security_scanner.ListFindingTypeStatsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_finding_type_stats(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest( + parent='parent_value', + ) + +def test_list_finding_type_stats_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_finding_type_stats in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_finding_type_stats] = mock_rpc + request = {} + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_finding_type_stats(request) + + # Establish that a new wrapper 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_finding_type_stats_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_finding_type_stats in client._client._transport._wrapped_methods + + # 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_finding_type_stats] = mock_rpc + + request = {} + await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_finding_type_stats(request) + + # Establish that a new wrapper 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_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( + )) + response = await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = web_security_scanner.ListFindingTypeStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_async_from_dict(): + await test_list_finding_type_stats_async(request_type=dict) + +def test_list_finding_type_stats_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_type_stats_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_finding_type_stats_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_finding_type_stats( + 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_finding_type_stats_flattened_error(): + client = WebSecurityScannerClient( + credentials=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_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_finding_type_stats_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_finding_type_stats( + 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_finding_type_stats_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=async_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_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + + +def test_create_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + + request = {} + client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_scan_config(request) + + # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.CreateScanConfigRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_config._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_scan_config._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_scan_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "scanConfig", ))) + + +def test_create_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + + # 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', + scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*}/scanConfigs" % client.transport._host, args[1]) + + +def test_create_scan_config_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + + +def test_delete_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + + request = {} + client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_scan_config(request) + + # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.DeleteScanConfigRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_scan_config._get_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_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + 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 + + response = client.delete_scan_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/scanConfigs/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 + + client.delete_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_scan_config_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + + +def test_get_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc + + request = {} + client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_config(request) + + # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.GetScanConfigRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_scan_config._get_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_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_config.ScanConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_scan_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = scan_config.ScanConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) + + +def test_get_scan_config_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + + +def test_list_scan_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_configs] = mock_rpc + + request = {} + client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_configs(request) + + # Establish 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_scan_configs_rest_required_fields(request_type=web_security_scanner.ListScanConfigsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_configs._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_scan_configs._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_scan_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_scan_configs_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_scan_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_scan_configs_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanConfigsResponse() + + # 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_scan_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*}/scanConfigs" % client.transport._host, args[1]) + + +def test_list_scan_configs_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + + +def test_list_scan_configs_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListScanConfigsResponse.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_scan_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_config.ScanConfig) + for i in results) + + pages = list(client.list_scan_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_scan_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_config] = mock_rpc + + request = {} + client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_scan_config(request) + + # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.UpdateScanConfigRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_config._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_scan_config._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_scan_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("scanConfig", "updateMask", ))) + + +def test_update_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{scan_config.name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) + + +def test_update_scan_config_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_start_scan_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc + + request = {} + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.start_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_start_scan_run_rest_required_fields(request_type=web_security_scanner.StartScanRunRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).start_scan_run._get_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()).start_scan_run._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.start_scan_run(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_start_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.start_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_start_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.start_scan_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*}:start" % client.transport._host, args[1]) + + +def test_start_scan_run_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + + +def test_get_scan_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc + + request = {} + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scan_run(request) + + # Establish 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_scan_run_rest_required_fields(request_type=web_security_scanner.GetScanRunRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_scan_run._get_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_scan_run._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_scan_run(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_scan_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}" % client.transport._host, args[1]) + + +def test_get_scan_run_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + + +def test_list_scan_runs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_scan_runs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_scan_runs] = mock_rpc + + request = {} + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scan_runs(request) + + # Establish 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_scan_runs_rest_required_fields(request_type=web_security_scanner.ListScanRunsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_runs._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_scan_runs._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanRunsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_scan_runs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_scan_runs_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_scan_runs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_scan_runs_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanRunsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_scan_runs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/scanConfigs/*}/scanRuns" % client.transport._host, args[1]) + + +def test_list_scan_runs_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + + +def test_list_scan_runs_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListScanRunsResponse.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/scanConfigs/sample2'} + + pager = client.list_scan_runs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_run.ScanRun) + for i in results) + + pages = list(client.list_scan_runs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_stop_scan_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_scan_run in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc + + request = {} + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_scan_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_stop_scan_run_rest_required_fields(request_type=web_security_scanner.StopScanRunRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).stop_scan_run._get_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()).stop_scan_run._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.stop_scan_run(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_stop_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.stop_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_stop_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.stop_scan_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}:stop" % client.transport._host, args[1]) + + +def test_stop_scan_run_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + + +def test_list_crawled_urls_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_crawled_urls in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_crawled_urls] = mock_rpc + + request = {} + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crawled_urls(request) + + # Establish 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_crawled_urls_rest_required_fields(request_type=web_security_scanner.ListCrawledUrlsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_crawled_urls._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_crawled_urls._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListCrawledUrlsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_crawled_urls(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_crawled_urls_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_crawled_urls._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_crawled_urls_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListCrawledUrlsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} + + # 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_crawled_urls(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls" % client.transport._host, args[1]) + + +def test_list_crawled_urls_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + + +def test_list_crawled_urls_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListCrawledUrlsResponse.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/scanConfigs/sample2/scanRuns/sample3'} + + pager = client.list_crawled_urls(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, crawled_url.CrawledUrl) + for i in results) + + pages = list(client.list_crawled_urls(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_finding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_finding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc + + request = {} + client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_finding(request) + + # Establish 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_finding_rest_required_fields(request_type=web_security_scanner.GetFindingRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_finding._get_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_finding._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = finding.Finding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = finding.Finding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_finding_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_finding_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} + + # 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 = finding.Finding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_finding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}" % client.transport._host, args[1]) + + +def test_get_finding_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + + +def test_list_findings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_findings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_findings] = mock_rpc + + request = {} + client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_findings(request) + + # Establish 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_findings_rest_required_fields(request_type=web_security_scanner.ListFindingsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_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 "filter" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "filter" in jsonified_request + assert jsonified_request["filter"] == request_init["filter"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_findings._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' + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_findings(request) + + expected_params = [ + ( + "filter", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_findings_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", "filter", ))) + + +def test_list_findings_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} + + # 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 = web_security_scanner.ListFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_findings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings" % client.transport._host, args[1]) + + +def test_list_findings_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(web_security_scanner.ListFindingsResponse.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/scanConfigs/sample2/scanRuns/sample3'} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, finding.Finding) + for i in results) + + pages = list(client.list_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_finding_type_stats_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_finding_type_stats in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_finding_type_stats] = mock_rpc + + request = {} + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_finding_type_stats(request) + + # Establish 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_finding_type_stats_rest_required_fields(request_type=web_security_scanner.ListFindingTypeStatsRequest): + transport_class = transports.WebSecurityScannerRestTransport + + 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_finding_type_stats._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_finding_type_stats._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingTypeStatsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_finding_type_stats(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_finding_type_stats_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_finding_type_stats._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_list_finding_type_stats_rest_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingTypeStatsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} + + # 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 = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_finding_type_stats(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats" % client.transport._host, args[1]) + + +def test_list_finding_type_stats_rest_flattened_error(transport: str = 'rest'): + client = WebSecurityScannerClient( + credentials=ga_credentials.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_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + 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 = WebSecurityScannerClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebSecurityScannerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, +]) +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 = WebSecurityScannerClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = WebSecurityScannerClient( + 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.create_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.CreateScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = None + client.delete_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.DeleteScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.get_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_configs_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanConfigsResponse() + client.list_scan_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanConfigsRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.update_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.UpdateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_scan_run_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.start_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StartScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_run_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.get_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_runs_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanRunsResponse() + client.list_scan_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_scan_run_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.stop_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StopScanRunRequest() + + assert args[0] == request_msg + + +# This 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_crawled_urls_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + client.list_crawled_urls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListCrawledUrlsRequest() + + assert args[0] == request_msg + + +# This 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_finding_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = finding.Finding() + client.get_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetFindingRequest() + + assert args[0] == request_msg + + +# This 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_findings_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingsResponse() + client.list_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingsRequest() + + assert args[0] == request_msg + + +# This 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_finding_type_stats_empty_call_grpc(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + client.list_finding_type_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingTypeStatsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = WebSecurityScannerAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + )) + await client.create_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.CreateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.DeleteScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + )) + await client.get_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_configs_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + )) + await client.list_scan_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + )) + await client.update_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.UpdateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_start_scan_run_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + await client.start_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StartScanRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_run_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + await client.get_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_scan_runs_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + )) + await client.list_scan_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_stop_scan_run_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + await client.stop_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StopScanRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_crawled_urls_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + )) + await client.list_crawled_urls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListCrawledUrlsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_finding_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + finding_type='finding_type_value', + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + )) + await client.get_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetFindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_findings_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + )) + await client.list_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_finding_type_stats_empty_call_grpc_asyncio(): + client = WebSecurityScannerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( + )) + await client.list_finding_type_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingTypeStatsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = WebSecurityScannerClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_scan_config_rest_bad_request(request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerClient( + 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 + client.create_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.CreateScanConfigRequest, + dict, +]) +def test_create_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request_init["scan_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'target_platforms': [1], 'export_to_security_command_center': 1, 'latest_run': {'name': 'name_value', 'execution_state': 1, 'result_state': 1, 'start_time': {}, 'end_time': {}, 'urls_crawled_count': 1935, 'urls_tested_count': 1846, 'has_vulnerabilities': True, 'progress_percent': 1733, 'error_trace': {'code': 1, 'scan_config_error': {'code': 1, 'field_name': 'field_name_value'}, 'most_common_http_error_code': 2893}, 'warning_traces': [{'code': 1}]}, 'risk_level': 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 = web_security_scanner.CreateScanConfigRequest.meta.fields["scan_config"] + + 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["scan_config"].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["scan_config"][field])): + del request_init["scan_config"][field][i][subfield] + else: + del request_init["scan_config"][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 = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_create_scan_config") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_create_scan_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.CreateScanConfigRequest.pb(web_security_scanner.CreateScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcw_scan_config.ScanConfig.to_json(gcw_scan_config.ScanConfig()) + req.return_value.content = return_value + + request = web_security_scanner.CreateScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcw_scan_config.ScanConfig() + + client.create_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_scan_config_rest_bad_request(request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + client.delete_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.DeleteScanConfigRequest, + dict, +]) +def test_delete_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + response = client.delete_scan_config(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_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_delete_scan_config") as pre: + pre.assert_not_called() + pb_message = web_security_scanner.DeleteScanConfigRequest.pb(web_security_scanner.DeleteScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = web_security_scanner.DeleteScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_get_scan_config_rest_bad_request(request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + client.get_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanConfigRequest, + dict, +]) +def test_get_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_config") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanConfigRequest.pb(web_security_scanner.GetScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) + req.return_value.content = return_value + + request = web_security_scanner.GetScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.get_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_configs_rest_bad_request(request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerClient( + 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 + client.list_scan_configs(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanConfigsRequest, + dict, +]) +def test_list_scan_configs_rest_call_success(request_type): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanConfigsResponse( + 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_scan_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_configs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_configs") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanConfigsRequest.pb(web_security_scanner.ListScanConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListScanConfigsResponse.to_json(web_security_scanner.ListScanConfigsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListScanConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanConfigsResponse() + + client.list_scan_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_scan_config_rest_bad_request(request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/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 + client.update_scan_config(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.UpdateScanConfigRequest, + dict, +]) +def test_update_scan_config_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} + request_init["scan_config"] = {'name': 'projects/sample1/scanConfigs/sample2', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'target_platforms': [1], 'export_to_security_command_center': 1, 'latest_run': {'name': 'name_value', 'execution_state': 1, 'result_state': 1, 'start_time': {}, 'end_time': {}, 'urls_crawled_count': 1935, 'urls_tested_count': 1846, 'has_vulnerabilities': True, 'progress_percent': 1733, 'error_trace': {'code': 1, 'scan_config_error': {'code': 1, 'field_name': 'field_name_value'}, 'most_common_http_error_code': 2893}, 'warning_traces': [{'code': 1}]}, 'risk_level': 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 = web_security_scanner.UpdateScanConfigRequest.meta.fields["scan_config"] + + 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["scan_config"].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["scan_config"][field])): + del request_init["scan_config"][field][i][subfield] + else: + del request_init["scan_config"][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 = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcw_scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_update_scan_config") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_update_scan_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.UpdateScanConfigRequest.pb(web_security_scanner.UpdateScanConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcw_scan_config.ScanConfig.to_json(gcw_scan_config.ScanConfig()) + req.return_value.content = return_value + + request = web_security_scanner.UpdateScanConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcw_scan_config.ScanConfig() + + client.update_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_scan_run_rest_bad_request(request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 + client.start_scan_run(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.StartScanRunRequest, + dict, +]) +def test_start_scan_run_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.start_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_start_scan_run") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_start_scan_run") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StartScanRunRequest.pb(web_security_scanner.StartScanRunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) + req.return_value.content = return_value + + request = web_security_scanner.StartScanRunRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.start_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_scan_run_rest_bad_request(request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.get_scan_run(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetScanRunRequest, + dict, +]) +def test_get_scan_run_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_run") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_run") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanRunRequest.pb(web_security_scanner.GetScanRunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) + req.return_value.content = return_value + + request = web_security_scanner.GetScanRunRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.get_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_runs_rest_bad_request(request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/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 + client.list_scan_runs(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListScanRunsRequest, + dict, +]) +def test_list_scan_runs_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse( + 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_scan_runs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_runs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_runs") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_runs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanRunsRequest.pb(web_security_scanner.ListScanRunsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListScanRunsResponse.to_json(web_security_scanner.ListScanRunsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListScanRunsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanRunsResponse() + + client.list_scan_runs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_scan_run_rest_bad_request(request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.stop_scan_run(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.StopScanRunRequest, + dict, +]) +def test_stop_scan_run_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = scan_run.ScanRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.stop_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_stop_scan_run") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_stop_scan_run") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StopScanRunRequest.pb(web_security_scanner.StopScanRunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) + req.return_value.content = return_value + + request = web_security_scanner.StopScanRunRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.stop_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_crawled_urls_rest_bad_request(request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.list_crawled_urls(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListCrawledUrlsRequest, + dict, +]) +def test_list_crawled_urls_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListCrawledUrlsResponse( + 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_crawled_urls(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crawled_urls_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_crawled_urls") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_crawled_urls") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListCrawledUrlsRequest.pb(web_security_scanner.ListCrawledUrlsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListCrawledUrlsResponse.to_json(web_security_scanner.ListCrawledUrlsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListCrawledUrlsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListCrawledUrlsResponse() + + client.list_crawled_urls(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_finding_rest_bad_request(request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_finding(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.GetFindingRequest, + dict, +]) +def test_get_finding_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = finding.Finding( + name='name_value', + finding_type='finding_type_value', + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = finding.Finding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_finding_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_finding") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetFindingRequest.pb(web_security_scanner.GetFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = finding.Finding.to_json(finding.Finding()) + req.return_value.content = return_value + + request = web_security_scanner.GetFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.get_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.list_findings(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListFindingsRequest, + dict, +]) +def test_list_findings_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingsResponse( + 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 = web_security_scanner.ListFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingsRequest.pb(web_security_scanner.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListFindingsResponse.to_json(web_security_scanner.ListFindingsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_finding_type_stats_rest_bad_request(request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 + client.list_finding_type_stats(request) + + +@pytest.mark.parametrize("request_type", [ + web_security_scanner.ListFindingTypeStatsRequest, + dict, +]) +def test_list_finding_type_stats_rest_call_success(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingTypeStatsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_finding_type_stats(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_finding_type_stats_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_finding_type_stats") as post, \ + mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_finding_type_stats") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingTypeStatsRequest.pb(web_security_scanner.ListFindingTypeStatsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = web_security_scanner.ListFindingTypeStatsResponse.to_json(web_security_scanner.ListFindingTypeStatsResponse()) + req.return_value.content = return_value + + request = web_security_scanner.ListFindingTypeStatsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + client.list_finding_type_stats(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = WebSecurityScannerClient( + 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + client.create_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.CreateScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + client.delete_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.DeleteScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + client.get_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanConfigRequest() + + assert args[0] == request_msg + + +# This 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_scan_configs_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + client.list_scan_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanConfigsRequest() + + assert args[0] == request_msg + + +# This 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_scan_config_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + client.update_scan_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.UpdateScanConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_scan_run_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + client.start_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StartScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_run_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + client.get_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetScanRunRequest() + + assert args[0] == request_msg + + +# This 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_scan_runs_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + client.list_scan_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListScanRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_scan_run_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + client.stop_scan_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.StopScanRunRequest() + + assert args[0] == request_msg + + +# This 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_crawled_urls_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + client.list_crawled_urls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListCrawledUrlsRequest() + + assert args[0] == request_msg + + +# This 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_finding_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + client.get_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.GetFindingRequest() + + assert args[0] == request_msg + + +# This 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_findings_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + client.list_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingsRequest() + + assert args[0] == request_msg + + +# This 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_finding_type_stats_empty_call_rest(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + client.list_finding_type_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = web_security_scanner.ListFindingTypeStatsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebSecurityScannerGrpcTransport, + ) + +def test_web_security_scanner_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_web_security_scanner_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_scan_config', + 'delete_scan_config', + 'get_scan_config', + 'list_scan_configs', + 'update_scan_config', + 'start_scan_run', + 'get_scan_run', + 'list_scan_runs', + 'stop_scan_run', + 'list_crawled_urls', + 'get_finding', + 'list_findings', + 'list_finding_type_stats', + ) + 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_web_security_scanner_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + 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_web_security_scanner_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport() + adc.assert_called_once() + + +def test_web_security_scanner_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) + WebSecurityScannerClient() + 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.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + ], +) +def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, + ], +) +def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, grpc_helpers), + (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_web_security_scanner_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( + "websecurityscanner.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="websecurityscanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_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_web_security_scanner_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.WebSecurityScannerRestTransport ( + 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_web_security_scanner_host_no_port(transport_name): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'websecurityscanner.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://websecurityscanner.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_web_security_scanner_host_with_port(transport_name): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'websecurityscanner.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://websecurityscanner.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_web_security_scanner_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WebSecurityScannerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WebSecurityScannerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_scan_config._session + session2 = client2.transport.create_scan_config._session + assert session1 != session2 + session1 = client1.transport.delete_scan_config._session + session2 = client2.transport.delete_scan_config._session + assert session1 != session2 + session1 = client1.transport.get_scan_config._session + session2 = client2.transport.get_scan_config._session + assert session1 != session2 + session1 = client1.transport.list_scan_configs._session + session2 = client2.transport.list_scan_configs._session + assert session1 != session2 + session1 = client1.transport.update_scan_config._session + session2 = client2.transport.update_scan_config._session + assert session1 != session2 + session1 = client1.transport.start_scan_run._session + session2 = client2.transport.start_scan_run._session + assert session1 != session2 + session1 = client1.transport.get_scan_run._session + session2 = client2.transport.get_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_scan_runs._session + session2 = client2.transport.list_scan_runs._session + assert session1 != session2 + session1 = client1.transport.stop_scan_run._session + session2 = client2.transport.stop_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_crawled_urls._session + session2 = client2.transport.list_crawled_urls._session + assert session1 != session2 + session1 = client1.transport.get_finding._session + session2 = client2.transport.get_finding._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_finding_type_stats._session + session2 = client2.transport.list_finding_type_stats._session + assert session1 != session2 +def test_web_security_scanner_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcTransport( + 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_web_security_scanner_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + 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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_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_finding_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + finding = "octopus" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "project": "oyster", + "scan_config": "nudibranch", + "scan_run": "cuttlefish", + "finding": "mussel", + } + path = WebSecurityScannerClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_finding_path(path) + assert expected == actual + +def test_scan_config_path(): + project = "winkle" + scan_config = "nautilus" + expected = "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) + actual = WebSecurityScannerClient.scan_config_path(project, scan_config) + assert expected == actual + + +def test_parse_scan_config_path(): + expected = { + "project": "scallop", + "scan_config": "abalone", + } + path = WebSecurityScannerClient.scan_config_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_scan_config_path(path) + assert expected == actual + +def test_scan_run_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) + actual = WebSecurityScannerClient.scan_run_path(project, scan_config, scan_run) + assert expected == actual + + +def test_parse_scan_run_path(): + expected = { + "project": "octopus", + "scan_config": "oyster", + "scan_run": "nudibranch", + } + path = WebSecurityScannerClient.scan_run_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_scan_run_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WebSecurityScannerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = WebSecurityScannerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = WebSecurityScannerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = WebSecurityScannerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WebSecurityScannerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = WebSecurityScannerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = WebSecurityScannerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = WebSecurityScannerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.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 = WebSecurityScannerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = WebSecurityScannerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.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.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + transport_class = WebSecurityScannerClient.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 = WebSecurityScannerClient( + 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 = WebSecurityScannerAsyncClient( + 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 = WebSecurityScannerClient( + 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 = WebSecurityScannerClient( + 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", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport), +]) +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-cloud-workflows/v1/.coveragerc b/owl-bot-staging/google-cloud-workflows/v1/.coveragerc new file mode 100644 index 000000000000..0b3eb91ee6c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/workflows/__init__.py + google/cloud/workflows/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-cloud-workflows/v1/.flake8 b/owl-bot-staging/google-cloud-workflows/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/MANIFEST.in b/owl-bot-staging/google-cloud-workflows/v1/MANIFEST.in new file mode 100644 index 000000000000..73e61ee8a1fe --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/workflows *.py +recursive-include google/cloud/workflows_v1 *.py diff --git a/owl-bot-staging/google-cloud-workflows/v1/README.rst b/owl-bot-staging/google-cloud-workflows/v1/README.rst new file mode 100644 index 000000000000..9ff50ef51f9e --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Workflows 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 Cloud Workflows 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-cloud-workflows/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-workflows/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/conf.py b/owl-bot-staging/google-cloud-workflows/v1/docs/conf.py new file mode 100644 index 000000000000..aa65085dd2d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows 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-cloud-workflows" +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 Cloud 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-cloud-workflows-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-cloud-workflows.tex", + u"google-cloud-workflows 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-cloud-workflows", + u"Google Cloud Workflows 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-cloud-workflows", + u"google-cloud-workflows Documentation", + author, + "google-cloud-workflows", + "GAPIC library for Google Cloud Workflows 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-cloud-workflows/v1/docs/executions_v1/executions.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/executions.rst new file mode 100644 index 000000000000..4bae72f3fd23 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/executions.rst @@ -0,0 +1,10 @@ +Executions +---------------------------- + +.. automodule:: google.cloud.workflows.executions_v1.services.executions + :members: + :inherited-members: + +.. automodule:: google.cloud.workflows.executions_v1.services.executions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/services_.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/services_.rst new file mode 100644 index 000000000000..bc1bbaa59487 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Workflows Executions v1 API +===================================================== +.. toctree:: + :maxdepth: 2 + + executions diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/types_.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/types_.rst new file mode 100644 index 000000000000..e17d766321ac --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Workflows Executions v1 API +================================================== + +.. automodule:: google.cloud.workflows.executions_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/index.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/index.rst new file mode 100644 index 000000000000..88b2eb9495a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + workflows_v1/services_ + workflows_v1/types_ diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/services_.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/services_.rst new file mode 100644 index 000000000000..460e0a385474 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Workflows v1 API +========================================== +.. toctree:: + :maxdepth: 2 + + workflows diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/types_.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/types_.rst new file mode 100644 index 000000000000..054c4fedc752 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Workflows v1 API +======================================= + +.. automodule:: google.cloud.workflows_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/workflows.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/workflows.rst new file mode 100644 index 000000000000..3c916583a384 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/workflows.rst @@ -0,0 +1,10 @@ +Workflows +--------------------------- + +.. automodule:: google.cloud.workflows_v1.services.workflows + :members: + :inherited-members: + +.. automodule:: google.cloud.workflows_v1.services.workflows.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/__init__.py new file mode 100644 index 000000000000..176e5116247b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/__init__.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.workflows_v1.services.workflows.client import WorkflowsClient +from google.cloud.workflows_v1.services.workflows.async_client import WorkflowsAsyncClient + +from google.cloud.workflows_v1.types.workflows import CreateWorkflowRequest +from google.cloud.workflows_v1.types.workflows import DeleteWorkflowRequest +from google.cloud.workflows_v1.types.workflows import GetWorkflowRequest +from google.cloud.workflows_v1.types.workflows import ListWorkflowsRequest +from google.cloud.workflows_v1.types.workflows import ListWorkflowsResponse +from google.cloud.workflows_v1.types.workflows import OperationMetadata +from google.cloud.workflows_v1.types.workflows import UpdateWorkflowRequest +from google.cloud.workflows_v1.types.workflows import Workflow + +__all__ = ('WorkflowsClient', + 'WorkflowsAsyncClient', + 'CreateWorkflowRequest', + 'DeleteWorkflowRequest', + 'GetWorkflowRequest', + 'ListWorkflowsRequest', + 'ListWorkflowsResponse', + 'OperationMetadata', + 'UpdateWorkflowRequest', + 'Workflow', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/__init__.py new file mode 100644 index 000000000000..f864a66be6f0 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows.executions import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.workflows.executions_v1.services.executions.client import ExecutionsClient +from google.cloud.workflows.executions_v1.services.executions.async_client import ExecutionsAsyncClient + +from google.cloud.workflows.executions_v1.types.executions import CancelExecutionRequest +from google.cloud.workflows.executions_v1.types.executions import CreateExecutionRequest +from google.cloud.workflows.executions_v1.types.executions import Execution +from google.cloud.workflows.executions_v1.types.executions import GetExecutionRequest +from google.cloud.workflows.executions_v1.types.executions import ListExecutionsRequest +from google.cloud.workflows.executions_v1.types.executions import ListExecutionsResponse +from google.cloud.workflows.executions_v1.types.executions import ExecutionView + +__all__ = ('ExecutionsClient', + 'ExecutionsAsyncClient', + 'CancelExecutionRequest', + 'CreateExecutionRequest', + 'Execution', + 'GetExecutionRequest', + 'ListExecutionsRequest', + 'ListExecutionsResponse', + 'ExecutionView', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/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-cloud-workflows/v1/google/cloud/workflows/executions/py.typed b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/py.typed new file mode 100644 index 000000000000..ff4d7c1ed09d --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workflows-executions package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/__init__.py new file mode 100644 index 000000000000..b87f2559c8a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/__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 google.cloud.workflows.executions_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.executions import ExecutionsClient +from .services.executions import ExecutionsAsyncClient + +from .types.executions import CancelExecutionRequest +from .types.executions import CreateExecutionRequest +from .types.executions import Execution +from .types.executions import GetExecutionRequest +from .types.executions import ListExecutionsRequest +from .types.executions import ListExecutionsResponse +from .types.executions import ExecutionView + +__all__ = ( + 'ExecutionsAsyncClient', +'CancelExecutionRequest', +'CreateExecutionRequest', +'Execution', +'ExecutionView', +'ExecutionsClient', +'GetExecutionRequest', +'ListExecutionsRequest', +'ListExecutionsResponse', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_metadata.json new file mode 100644 index 000000000000..f17943ae3dfa --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_metadata.json @@ -0,0 +1,63 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.workflows.executions_v1", + "protoPackage": "google.cloud.workflows.executions.v1", + "schema": "1.0", + "services": { + "Executions": { + "clients": { + "grpc": { + "libraryClient": "ExecutionsClient", + "rpcs": { + "CancelExecution": { + "methods": [ + "cancel_execution" + ] + }, + "CreateExecution": { + "methods": [ + "create_execution" + ] + }, + "GetExecution": { + "methods": [ + "get_execution" + ] + }, + "ListExecutions": { + "methods": [ + "list_executions" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ExecutionsAsyncClient", + "rpcs": { + "CancelExecution": { + "methods": [ + "cancel_execution" + ] + }, + "CreateExecution": { + "methods": [ + "create_execution" + ] + }, + "GetExecution": { + "methods": [ + "get_execution" + ] + }, + "ListExecutions": { + "methods": [ + "list_executions" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_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-cloud-workflows/v1/google/cloud/workflows/executions_v1/py.typed b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/py.typed new file mode 100644 index 000000000000..ff4d7c1ed09d --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workflows-executions package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_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-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/__init__.py new file mode 100644 index 000000000000..9295dd9a3cb5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/__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 ExecutionsClient +from .async_client import ExecutionsAsyncClient + +__all__ = ( + 'ExecutionsClient', + 'ExecutionsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/async_client.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/async_client.py new file mode 100644 index 000000000000..384010c7f7e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/async_client.py @@ -0,0 +1,697 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.workflows.executions_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.cloud.workflows.executions_v1.services.executions import pagers +from google.cloud.workflows.executions_v1.types import executions +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExecutionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ExecutionsGrpcAsyncIOTransport +from .client import ExecutionsClient + + +class ExecutionsAsyncClient: + """Executions is used to start and manage running instances of + [Workflows][google.cloud.workflows.v1.Workflow] called executions. + """ + + _client: ExecutionsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ExecutionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ExecutionsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ExecutionsClient._DEFAULT_UNIVERSE + + execution_path = staticmethod(ExecutionsClient.execution_path) + parse_execution_path = staticmethod(ExecutionsClient.parse_execution_path) + workflow_path = staticmethod(ExecutionsClient.workflow_path) + parse_workflow_path = staticmethod(ExecutionsClient.parse_workflow_path) + common_billing_account_path = staticmethod(ExecutionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ExecutionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ExecutionsClient.common_folder_path) + parse_common_folder_path = staticmethod(ExecutionsClient.parse_common_folder_path) + common_organization_path = staticmethod(ExecutionsClient.common_organization_path) + parse_common_organization_path = staticmethod(ExecutionsClient.parse_common_organization_path) + common_project_path = staticmethod(ExecutionsClient.common_project_path) + parse_common_project_path = staticmethod(ExecutionsClient.parse_common_project_path) + common_location_path = staticmethod(ExecutionsClient.common_location_path) + parse_common_location_path = staticmethod(ExecutionsClient.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: + ExecutionsAsyncClient: The constructed client. + """ + return ExecutionsClient.from_service_account_info.__func__(ExecutionsAsyncClient, 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: + ExecutionsAsyncClient: The constructed client. + """ + return ExecutionsClient.from_service_account_file.__func__(ExecutionsAsyncClient, 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 ExecutionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ExecutionsTransport: + """Returns the transport used by the client instance. + + Returns: + ExecutionsTransport: 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 = ExecutionsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ExecutionsTransport, Callable[..., ExecutionsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the executions 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,ExecutionsTransport,Callable[..., ExecutionsTransport]]]): + 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 ExecutionsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ExecutionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_executions(self, + request: Optional[Union[executions.ListExecutionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExecutionsAsyncPager: + r"""Returns a list of executions which belong to the + workflow with the given name. The method returns + executions of all workflow revisions. Returned + executions are ordered by their start time (newest + first). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1 + + async def sample_list_executions(): + # Create a client + client = executions_v1.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1.ListExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_executions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workflows.executions_v1.types.ListExecutionsRequest, dict]]): + The request object. Request for the [ListExecutions][] method. + parent (:class:`str`): + Required. Name of the workflow for + which the executions should be listed. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1.services.executions.pagers.ListExecutionsAsyncPager: + Response for the + [ListExecutions][google.cloud.workflows.executions.v1.Executions.ListExecutions] + 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, executions.ListExecutionsRequest): + request = executions.ListExecutionsRequest(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_executions] + + # Certain fields should be provided within 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.ListExecutionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_execution(self, + request: Optional[Union[executions.CreateExecutionRequest, dict]] = None, + *, + parent: Optional[str] = None, + execution: Optional[executions.Execution] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Creates a new execution using the latest revision of + the given workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1 + + async def sample_create_execution(): + # Create a client + client = executions_v1.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1.CreateExecutionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows.executions_v1.types.CreateExecutionRequest, dict]]): + The request object. Request for the + [CreateExecution][google.cloud.workflows.executions.v1.Executions.CreateExecution] + method. + parent (:class:`str`): + Required. Name of the workflow for + which an execution should be created. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + The latest revision of the workflow will + be used. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + execution (:class:`google.cloud.workflows.executions_v1.types.Execution`): + Required. Execution to be created. + This corresponds to the ``execution`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_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. + + Returns: + google.cloud.workflows.executions_v1.types.Execution: + A running instance of a + [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). + + """ + # Create or coerce a protobuf request object. + # - Quick 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, execution]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, executions.CreateExecutionRequest): + request = executions.CreateExecutionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if execution is not None: + request.execution = execution + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_execution] + + # Certain fields should be provided within 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_execution(self, + request: Optional[Union[executions.GetExecutionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Returns an execution of the given name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1 + + async def sample_get_execution(): + # Create a client + client = executions_v1.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1.GetExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows.executions_v1.types.GetExecutionRequest, dict]]): + The request object. Request for the + [GetExecution][google.cloud.workflows.executions.v1.Executions.GetExecution] + method. + name (:class:`str`): + Required. Name of the execution to be + retrieved. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1.types.Execution: + A running instance of a + [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). + + """ + # Create or coerce a protobuf request object. + # - Quick 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, executions.GetExecutionRequest): + request = executions.GetExecutionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_execution] + + # Certain fields should be provided within 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 cancel_execution(self, + request: Optional[Union[executions.CancelExecutionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Cancels an execution of the given name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1 + + async def sample_cancel_execution(): + # Create a client + client = executions_v1.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1.CancelExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.cancel_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows.executions_v1.types.CancelExecutionRequest, dict]]): + The request object. Request for the + [CancelExecution][google.cloud.workflows.executions.v1.Executions.CancelExecution] + method. + name (:class:`str`): + Required. Name of the execution to be + cancelled. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1.types.Execution: + A running instance of a + [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). + + """ + # Create or coerce a protobuf request object. + # - Quick 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, executions.CancelExecutionRequest): + request = executions.CancelExecutionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.cancel_execution] + + # Certain fields should be provided within 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) -> "ExecutionsAsyncClient": + 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__ = ( + "ExecutionsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/client.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/client.py new file mode 100644 index 000000000000..27a2c765747c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/client.py @@ -0,0 +1,1057 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.workflows.executions_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 + +from google.cloud.workflows.executions_v1.services.executions import pagers +from google.cloud.workflows.executions_v1.types import executions +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExecutionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ExecutionsGrpcTransport +from .transports.grpc_asyncio import ExecutionsGrpcAsyncIOTransport + + +class ExecutionsClientMeta(type): + """Metaclass for the Executions 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[ExecutionsTransport]] + _transport_registry["grpc"] = ExecutionsGrpcTransport + _transport_registry["grpc_asyncio"] = ExecutionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ExecutionsTransport]: + """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 ExecutionsClient(metaclass=ExecutionsClientMeta): + """Executions is used to start and manage running instances of + [Workflows][google.cloud.workflows.v1.Workflow] called executions. + """ + + @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 = "workflowexecutions.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "workflowexecutions.{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: + ExecutionsClient: 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: + ExecutionsClient: 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) -> ExecutionsTransport: + """Returns the transport used by the client instance. + + Returns: + ExecutionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def execution_path(project: str,location: str,workflow: str,execution: str,) -> str: + """Returns a fully-qualified execution string.""" + return "projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}".format(project=project, location=location, workflow=workflow, execution=execution, ) + + @staticmethod + def parse_execution_path(path: str) -> Dict[str,str]: + """Parses a execution path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)/executions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workflow_path(project: str,location: str,workflow: str,) -> str: + """Returns a fully-qualified workflow string.""" + return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + + @staticmethod + def parse_workflow_path(path: str) -> Dict[str,str]: + """Parses a workflow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = ExecutionsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ExecutionsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ExecutionsClient._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 = ExecutionsClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ExecutionsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ExecutionsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, ExecutionsTransport, Callable[..., ExecutionsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the executions client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ExecutionsTransport,Callable[..., ExecutionsTransport]]]): + 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 ExecutionsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ExecutionsClient._read_environment_variables() + self._client_cert_source = ExecutionsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ExecutionsClient._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 + + 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, ExecutionsTransport) + if transport_provided: + # transport is a ExecutionsTransport 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(ExecutionsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ExecutionsClient._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[ExecutionsTransport], Callable[..., ExecutionsTransport]] = ( + ExecutionsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ExecutionsTransport], 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, + ) + + def list_executions(self, + request: Optional[Union[executions.ListExecutionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExecutionsPager: + r"""Returns a list of executions which belong to the + workflow with the given name. The method returns + executions of all workflow revisions. Returned + executions are ordered by their start time (newest + first). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1 + + def sample_list_executions(): + # Create a client + client = executions_v1.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1.ListExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_executions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workflows.executions_v1.types.ListExecutionsRequest, dict]): + The request object. Request for the [ListExecutions][] method. + parent (str): + Required. Name of the workflow for + which the executions should be listed. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1.services.executions.pagers.ListExecutionsPager: + Response for the + [ListExecutions][google.cloud.workflows.executions.v1.Executions.ListExecutions] + 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, executions.ListExecutionsRequest): + request = executions.ListExecutionsRequest(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_executions] + + # Certain fields should be provided within 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.ListExecutionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_execution(self, + request: Optional[Union[executions.CreateExecutionRequest, dict]] = None, + *, + parent: Optional[str] = None, + execution: Optional[executions.Execution] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Creates a new execution using the latest revision of + the given workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1 + + def sample_create_execution(): + # Create a client + client = executions_v1.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1.CreateExecutionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows.executions_v1.types.CreateExecutionRequest, dict]): + The request object. Request for the + [CreateExecution][google.cloud.workflows.executions.v1.Executions.CreateExecution] + method. + parent (str): + Required. Name of the workflow for + which an execution should be created. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + The latest revision of the workflow will + be used. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + execution (google.cloud.workflows.executions_v1.types.Execution): + Required. Execution to be created. + This corresponds to the ``execution`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.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. + + Returns: + google.cloud.workflows.executions_v1.types.Execution: + A running instance of a + [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). + + """ + # Create or coerce a protobuf request object. + # - Quick 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, execution]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, executions.CreateExecutionRequest): + request = executions.CreateExecutionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if execution is not None: + request.execution = execution + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_execution] + + # Certain fields should be provided within 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_execution(self, + request: Optional[Union[executions.GetExecutionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Returns an execution of the given name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1 + + def sample_get_execution(): + # Create a client + client = executions_v1.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1.GetExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.get_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows.executions_v1.types.GetExecutionRequest, dict]): + The request object. Request for the + [GetExecution][google.cloud.workflows.executions.v1.Executions.GetExecution] + method. + name (str): + Required. Name of the execution to be + retrieved. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1.types.Execution: + A running instance of a + [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). + + """ + # Create or coerce a protobuf request object. + # - Quick 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, executions.GetExecutionRequest): + request = executions.GetExecutionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_execution] + + # Certain fields should be provided within 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 cancel_execution(self, + request: Optional[Union[executions.CancelExecutionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Cancels an execution of the given name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1 + + def sample_cancel_execution(): + # Create a client + client = executions_v1.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1.CancelExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.cancel_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows.executions_v1.types.CancelExecutionRequest, dict]): + The request object. Request for the + [CancelExecution][google.cloud.workflows.executions.v1.Executions.CancelExecution] + method. + name (str): + Required. Name of the execution to be + cancelled. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1.types.Execution: + A running instance of a + [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). + + """ + # Create or coerce a protobuf request object. + # - Quick 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, executions.CancelExecutionRequest): + request = executions.CancelExecutionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.cancel_execution] + + # Certain fields should be provided within 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) -> "ExecutionsClient": + 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__ = ( + "ExecutionsClient", +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/pagers.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/pagers.py new file mode 100644 index 000000000000..15cd30651438 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows.executions_v1.types import executions + + +class ListExecutionsPager: + """A pager for iterating through ``list_executions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workflows.executions_v1.types.ListExecutionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``executions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExecutions`` requests and continue to iterate + through the ``executions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workflows.executions_v1.types.ListExecutionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., executions.ListExecutionsResponse], + request: executions.ListExecutionsRequest, + response: executions.ListExecutionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workflows.executions_v1.types.ListExecutionsRequest): + The initial request object. + response (google.cloud.workflows.executions_v1.types.ListExecutionsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = executions.ListExecutionsRequest(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[executions.ListExecutionsResponse]: + 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[executions.Execution]: + for page in self.pages: + yield from page.executions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListExecutionsAsyncPager: + """A pager for iterating through ``list_executions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workflows.executions_v1.types.ListExecutionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``executions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExecutions`` requests and continue to iterate + through the ``executions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workflows.executions_v1.types.ListExecutionsResponse` + attributes are available on the 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[executions.ListExecutionsResponse]], + request: executions.ListExecutionsRequest, + response: executions.ListExecutionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workflows.executions_v1.types.ListExecutionsRequest): + The initial request object. + response (google.cloud.workflows.executions_v1.types.ListExecutionsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = executions.ListExecutionsRequest(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[executions.ListExecutionsResponse]: + 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[executions.Execution]: + async def async_generator(): + async for page in self.pages: + for response in page.executions: + 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-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/README.rst b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/README.rst new file mode 100644 index 000000000000..6555db202c9c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ExecutionsTransport` is the ABC for all transports. +- public child `ExecutionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ExecutionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseExecutionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ExecutionsRestTransport` 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-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/__init__.py new file mode 100644 index 000000000000..fbf990808f62 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 ExecutionsTransport +from .grpc import ExecutionsGrpcTransport +from .grpc_asyncio import ExecutionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ExecutionsTransport]] +_transport_registry['grpc'] = ExecutionsGrpcTransport +_transport_registry['grpc_asyncio'] = ExecutionsGrpcAsyncIOTransport + +__all__ = ( + 'ExecutionsTransport', + 'ExecutionsGrpcTransport', + 'ExecutionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/base.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/base.py new file mode 100644 index 000000000000..685f383ca66b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/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.cloud.workflows.executions_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.cloud.workflows.executions_v1.types import executions + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ExecutionsTransport(abc.ABC): + """Abstract transport class for Executions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_executions: gapic_v1.method.wrap_method( + self.list_executions, + default_timeout=None, + client_info=client_info, + ), + self.create_execution: gapic_v1.method.wrap_method( + self.create_execution, + default_timeout=None, + client_info=client_info, + ), + self.get_execution: gapic_v1.method.wrap_method( + self.get_execution, + default_timeout=None, + client_info=client_info, + ), + self.cancel_execution: gapic_v1.method.wrap_method( + self.cancel_execution, + 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_executions(self) -> Callable[ + [executions.ListExecutionsRequest], + Union[ + executions.ListExecutionsResponse, + Awaitable[executions.ListExecutionsResponse] + ]]: + raise NotImplementedError() + + @property + def create_execution(self) -> Callable[ + [executions.CreateExecutionRequest], + Union[ + executions.Execution, + Awaitable[executions.Execution] + ]]: + raise NotImplementedError() + + @property + def get_execution(self) -> Callable[ + [executions.GetExecutionRequest], + Union[ + executions.Execution, + Awaitable[executions.Execution] + ]]: + raise NotImplementedError() + + @property + def cancel_execution(self) -> Callable[ + [executions.CancelExecutionRequest], + Union[ + executions.Execution, + Awaitable[executions.Execution] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ExecutionsTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc.py new file mode 100644 index 000000000000..634f6ada2a5b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc.py @@ -0,0 +1,354 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.cloud.workflows.executions_v1.types import executions +from .base import ExecutionsTransport, DEFAULT_CLIENT_INFO + + +class ExecutionsGrpcTransport(ExecutionsTransport): + """gRPC backend transport for Executions. + + Executions is used to start and manage running instances of + [Workflows][google.cloud.workflows.v1.Workflow] called executions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'workflowexecutions.googleapis.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_executions(self) -> Callable[ + [executions.ListExecutionsRequest], + executions.ListExecutionsResponse]: + r"""Return a callable for the list executions method over gRPC. + + Returns a list of executions which belong to the + workflow with the given name. The method returns + executions of all workflow revisions. Returned + executions are ordered by their start time (newest + first). + + Returns: + Callable[[~.ListExecutionsRequest], + ~.ListExecutionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_executions' not in self._stubs: + self._stubs['list_executions'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1.Executions/ListExecutions', + request_serializer=executions.ListExecutionsRequest.serialize, + response_deserializer=executions.ListExecutionsResponse.deserialize, + ) + return self._stubs['list_executions'] + + @property + def create_execution(self) -> Callable[ + [executions.CreateExecutionRequest], + executions.Execution]: + r"""Return a callable for the create execution method over gRPC. + + Creates a new execution using the latest revision of + the given workflow. + + Returns: + Callable[[~.CreateExecutionRequest], + ~.Execution]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_execution' not in self._stubs: + self._stubs['create_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1.Executions/CreateExecution', + request_serializer=executions.CreateExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['create_execution'] + + @property + def get_execution(self) -> Callable[ + [executions.GetExecutionRequest], + executions.Execution]: + r"""Return a callable for the get execution method over gRPC. + + Returns an execution of the given name. + + Returns: + Callable[[~.GetExecutionRequest], + ~.Execution]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_execution' not in self._stubs: + self._stubs['get_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1.Executions/GetExecution', + request_serializer=executions.GetExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['get_execution'] + + @property + def cancel_execution(self) -> Callable[ + [executions.CancelExecutionRequest], + executions.Execution]: + r"""Return a callable for the cancel execution method over gRPC. + + Cancels an execution of the given name. + + Returns: + Callable[[~.CancelExecutionRequest], + ~.Execution]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'cancel_execution' not in self._stubs: + self._stubs['cancel_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1.Executions/CancelExecution', + request_serializer=executions.CancelExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['cancel_execution'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ExecutionsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc_asyncio.py new file mode 100644 index 000000000000..1bcafa2551d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc_asyncio.py @@ -0,0 +1,390 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.workflows.executions_v1.types import executions +from .base import ExecutionsTransport, DEFAULT_CLIENT_INFO +from .grpc import ExecutionsGrpcTransport + + +class ExecutionsGrpcAsyncIOTransport(ExecutionsTransport): + """gRPC AsyncIO backend transport for Executions. + + Executions is used to start and manage running instances of + [Workflows][google.cloud.workflows.v1.Workflow] called executions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workflowexecutions.googleapis.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 = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_executions(self) -> Callable[ + [executions.ListExecutionsRequest], + Awaitable[executions.ListExecutionsResponse]]: + r"""Return a callable for the list executions method over gRPC. + + Returns a list of executions which belong to the + workflow with the given name. The method returns + executions of all workflow revisions. Returned + executions are ordered by their start time (newest + first). + + Returns: + Callable[[~.ListExecutionsRequest], + Awaitable[~.ListExecutionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_executions' not in self._stubs: + self._stubs['list_executions'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1.Executions/ListExecutions', + request_serializer=executions.ListExecutionsRequest.serialize, + response_deserializer=executions.ListExecutionsResponse.deserialize, + ) + return self._stubs['list_executions'] + + @property + def create_execution(self) -> Callable[ + [executions.CreateExecutionRequest], + Awaitable[executions.Execution]]: + r"""Return a callable for the create execution method over gRPC. + + Creates a new execution using the latest revision of + the given workflow. + + Returns: + Callable[[~.CreateExecutionRequest], + Awaitable[~.Execution]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_execution' not in self._stubs: + self._stubs['create_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1.Executions/CreateExecution', + request_serializer=executions.CreateExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['create_execution'] + + @property + def get_execution(self) -> Callable[ + [executions.GetExecutionRequest], + Awaitable[executions.Execution]]: + r"""Return a callable for the get execution method over gRPC. + + Returns an execution of the given name. + + Returns: + Callable[[~.GetExecutionRequest], + Awaitable[~.Execution]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_execution' not in self._stubs: + self._stubs['get_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1.Executions/GetExecution', + request_serializer=executions.GetExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['get_execution'] + + @property + def cancel_execution(self) -> Callable[ + [executions.CancelExecutionRequest], + Awaitable[executions.Execution]]: + r"""Return a callable for the cancel execution method over gRPC. + + Cancels an execution of the given name. + + Returns: + Callable[[~.CancelExecutionRequest], + Awaitable[~.Execution]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'cancel_execution' not in self._stubs: + self._stubs['cancel_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1.Executions/CancelExecution', + request_serializer=executions.CancelExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['cancel_execution'] + + 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_executions: self._wrap_method( + self.list_executions, + default_timeout=None, + client_info=client_info, + ), + self.create_execution: self._wrap_method( + self.create_execution, + default_timeout=None, + client_info=client_info, + ), + self.get_execution: self._wrap_method( + self.get_execution, + default_timeout=None, + client_info=client_info, + ), + self.cancel_execution: self._wrap_method( + self.cancel_execution, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'ExecutionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/__init__.py new file mode 100644 index 000000000000..52fb1dab35df --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/__init__.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .executions import ( + CancelExecutionRequest, + CreateExecutionRequest, + Execution, + GetExecutionRequest, + ListExecutionsRequest, + ListExecutionsResponse, + ExecutionView, +) + +__all__ = ( + 'CancelExecutionRequest', + 'CreateExecutionRequest', + 'Execution', + 'GetExecutionRequest', + 'ListExecutionsRequest', + 'ListExecutionsResponse', + 'ExecutionView', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/executions.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/executions.py new file mode 100644 index 000000000000..f6eb9a3d8228 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/executions.py @@ -0,0 +1,580 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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 + + +__protobuf__ = proto.module( + package='google.cloud.workflows.executions.v1', + manifest={ + 'ExecutionView', + 'Execution', + 'ListExecutionsRequest', + 'ListExecutionsResponse', + 'CreateExecutionRequest', + 'GetExecutionRequest', + 'CancelExecutionRequest', + }, +) + + +class ExecutionView(proto.Enum): + r"""Defines possible views for execution resource. + + Values: + EXECUTION_VIEW_UNSPECIFIED (0): + The default / unset value. + BASIC (1): + Includes only basic metadata about the execution. The + following fields are returned: name, start_time, end_time, + duration, state, and workflow_revision_id. + FULL (2): + Includes all data. + """ + EXECUTION_VIEW_UNSPECIFIED = 0 + BASIC = 1 + FULL = 2 + + +class Execution(proto.Message): + r"""A running instance of a + `Workflow `__. + + Attributes: + name (str): + Output only. The resource name of the + execution. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Marks the beginning of + execution. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Marks the end of execution, + successful or not. + duration (google.protobuf.duration_pb2.Duration): + Output only. Measures the duration of the + execution. + state (google.cloud.workflows.executions_v1.types.Execution.State): + Output only. Current state of the execution. + argument (str): + Input parameters of the execution represented as a JSON + string. The size limit is 32KB. + + *Note*: If you are using the REST API directly to run your + workflow, you must escape any JSON string value of + ``argument``. Example: + ``'{"argument":"{\"firstName\":\"FIRST\",\"lastName\":\"LAST\"}"}'`` + result (str): + Output only. Output of the execution represented as a JSON + string. The value can only be present if the execution's + state is ``SUCCEEDED``. + error (google.cloud.workflows.executions_v1.types.Execution.Error): + Output only. The error which caused the execution to finish + prematurely. The value is only present if the execution's + state is ``FAILED`` or ``CANCELLED``. + workflow_revision_id (str): + Output only. Revision of the workflow this + execution is using. + call_log_level (google.cloud.workflows.executions_v1.types.Execution.CallLogLevel): + The call logging level associated to this + execution. + status (google.cloud.workflows.executions_v1.types.Execution.Status): + Output only. Status tracks the current steps + and progress data of this execution. + labels (MutableMapping[str, str]): + Labels associated with this execution. + Labels can contain at most 64 entries. Keys and + values can be no longer than 63 characters and + can only contain lowercase letters, numeric + characters, underscores, and dashes. Label keys + must start with a letter. International + characters are allowed. + By default, labels are inherited from the + workflow but are overridden by any labels + associated with the execution. + state_error (google.cloud.workflows.executions_v1.types.Execution.StateError): + Output only. Error regarding the state of the + Execution resource. For example, this field will + have error details if the execution data is + unavailable due to revoked KMS key permissions. + """ + class State(proto.Enum): + r"""Describes the current state of the execution. More states + might be added in the future. + + Values: + STATE_UNSPECIFIED (0): + Invalid state. + ACTIVE (1): + The execution is in progress. + SUCCEEDED (2): + The execution finished successfully. + FAILED (3): + The execution failed with an error. + CANCELLED (4): + The execution was stopped intentionally. + UNAVAILABLE (5): + Execution data is unavailable. See the ``state_error`` + field. + QUEUED (6): + Request has been placed in the backlog for + processing at a later time. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLED = 4 + UNAVAILABLE = 5 + QUEUED = 6 + + class CallLogLevel(proto.Enum): + r"""Describes the level of platform logging to apply to calls and + call responses during workflow executions. + + Values: + CALL_LOG_LEVEL_UNSPECIFIED (0): + No call logging level specified. + LOG_ALL_CALLS (1): + Log all call steps within workflows, all call + returns, and all exceptions raised. + LOG_ERRORS_ONLY (2): + Log only exceptions that are raised from call + steps within workflows. + LOG_NONE (3): + Explicitly log nothing. + """ + CALL_LOG_LEVEL_UNSPECIFIED = 0 + LOG_ALL_CALLS = 1 + LOG_ERRORS_ONLY = 2 + LOG_NONE = 3 + + class StackTraceElement(proto.Message): + r"""A single stack element (frame) where an error occurred. + + Attributes: + step (str): + The step the error occurred at. + routine (str): + The routine where the error occurred. + position (google.cloud.workflows.executions_v1.types.Execution.StackTraceElement.Position): + The source position information of the stack + trace element. + """ + + class Position(proto.Message): + r"""Position contains source position information about the stack + trace element such as line number, column number and length of + the code block in bytes. + + Attributes: + line (int): + The source code line number the current + instruction was generated from. + column (int): + The source code column position (of the line) + the current instruction was generated from. + length (int): + The number of bytes of source code making up + this stack trace element. + """ + + line: int = proto.Field( + proto.INT64, + number=1, + ) + column: int = proto.Field( + proto.INT64, + number=2, + ) + length: int = proto.Field( + proto.INT64, + number=3, + ) + + step: str = proto.Field( + proto.STRING, + number=1, + ) + routine: str = proto.Field( + proto.STRING, + number=2, + ) + position: 'Execution.StackTraceElement.Position' = proto.Field( + proto.MESSAGE, + number=3, + message='Execution.StackTraceElement.Position', + ) + + class StackTrace(proto.Message): + r"""A collection of stack elements (frames) where an error + occurred. + + Attributes: + elements (MutableSequence[google.cloud.workflows.executions_v1.types.Execution.StackTraceElement]): + An array of stack elements. + """ + + elements: MutableSequence['Execution.StackTraceElement'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Execution.StackTraceElement', + ) + + class Error(proto.Message): + r"""Error describes why the execution was abnormally terminated. + + Attributes: + payload (str): + Error message and data returned represented + as a JSON string. + context (str): + Human-readable stack trace string. + stack_trace (google.cloud.workflows.executions_v1.types.Execution.StackTrace): + Stack trace with detailed information of + where error was generated. + """ + + payload: str = proto.Field( + proto.STRING, + number=1, + ) + context: str = proto.Field( + proto.STRING, + number=2, + ) + stack_trace: 'Execution.StackTrace' = proto.Field( + proto.MESSAGE, + number=3, + message='Execution.StackTrace', + ) + + class Status(proto.Message): + r"""Represents the current status of this execution. + + Attributes: + current_steps (MutableSequence[google.cloud.workflows.executions_v1.types.Execution.Status.Step]): + A list of currently executing or last executed step names + for the workflow execution currently running. If the + workflow has succeeded or failed, this is the last attempted + or executed step. Presently, if the current step is inside a + subworkflow, the list only includes that step. In the + future, the list will contain items for each step in the + call stack, starting with the outermost step in the ``main`` + subworkflow, and ending with the most deeply nested step. + """ + + class Step(proto.Message): + r"""Represents a step of the workflow this execution is running. + + Attributes: + routine (str): + Name of a routine within the workflow. + step (str): + Name of a step within the routine. + """ + + routine: str = proto.Field( + proto.STRING, + number=1, + ) + step: str = proto.Field( + proto.STRING, + number=2, + ) + + current_steps: MutableSequence['Execution.Status.Step'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Execution.Status.Step', + ) + + class StateError(proto.Message): + r"""Describes an error related to the current state of the + Execution resource. + + Attributes: + details (str): + Provides specifics about the error. + type_ (google.cloud.workflows.executions_v1.types.Execution.StateError.Type): + The type of this state error. + """ + class Type(proto.Enum): + r"""Describes the possible types of a state error. + + Values: + TYPE_UNSPECIFIED (0): + No type specified. + KMS_ERROR (1): + Caused by an issue with KMS. + """ + TYPE_UNSPECIFIED = 0 + KMS_ERROR = 1 + + details: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'Execution.StateError.Type' = proto.Field( + proto.ENUM, + number=2, + enum='Execution.StateError.Type', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=12, + message=duration_pb2.Duration, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + argument: str = proto.Field( + proto.STRING, + number=5, + ) + result: str = proto.Field( + proto.STRING, + number=6, + ) + error: Error = proto.Field( + proto.MESSAGE, + number=7, + message=Error, + ) + workflow_revision_id: str = proto.Field( + proto.STRING, + number=8, + ) + call_log_level: CallLogLevel = proto.Field( + proto.ENUM, + number=9, + enum=CallLogLevel, + ) + status: Status = proto.Field( + proto.MESSAGE, + number=10, + message=Status, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=11, + ) + state_error: StateError = proto.Field( + proto.MESSAGE, + number=13, + message=StateError, + ) + + +class ListExecutionsRequest(proto.Message): + r"""Request for the [ListExecutions][] method. + + Attributes: + parent (str): + Required. Name of the workflow for which the + executions should be listed. Format: + projects/{project}/locations/{location}/workflows/{workflow} + page_size (int): + Maximum number of executions to return per + call. Max supported value depends on the + selected Execution view: it's 1000 for BASIC and + 100 for FULL. The default value used if the + field is not specified is 100, regardless of the + selected view. Values greater than the max value + will be coerced down to it. + page_token (str): + A page token, received from a previous ``ListExecutions`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListExecutions`` must match the call that provided the + page token. + + Note that pagination is applied to dynamic data. The list of + executions returned can change between page requests. + view (google.cloud.workflows.executions_v1.types.ExecutionView): + Optional. A view defining which fields should + be filled in the returned executions. The API + will default to the BASIC view. + filter (str): + Optional. Filters applied to the [Executions.ListExecutions] + results. The following fields are supported for filtering: + executionID, state, startTime, endTime, duration, + workflowRevisionID, stepName, and label. + order_by (str): + Optional. The ordering applied to the + [Executions.ListExecutions] results. By default the ordering + is based on descending start time. The following fields are + supported for order by: executionID, startTime, endTime, + duration, state, and workflowRevisionID. + """ + + 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, + ) + view: 'ExecutionView' = proto.Field( + proto.ENUM, + number=4, + enum='ExecutionView', + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListExecutionsResponse(proto.Message): + r"""Response for the + [ListExecutions][google.cloud.workflows.executions.v1.Executions.ListExecutions] + method. + + Attributes: + executions (MutableSequence[google.cloud.workflows.executions_v1.types.Execution]): + The executions which match the request. + 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 + + executions: MutableSequence['Execution'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Execution', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateExecutionRequest(proto.Message): + r"""Request for the + [CreateExecution][google.cloud.workflows.executions.v1.Executions.CreateExecution] + method. + + Attributes: + parent (str): + Required. Name of the workflow for which an + execution should be created. Format: + projects/{project}/locations/{location}/workflows/{workflow} + The latest revision of the workflow will be + used. + execution (google.cloud.workflows.executions_v1.types.Execution): + Required. Execution to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + execution: 'Execution' = proto.Field( + proto.MESSAGE, + number=2, + message='Execution', + ) + + +class GetExecutionRequest(proto.Message): + r"""Request for the + [GetExecution][google.cloud.workflows.executions.v1.Executions.GetExecution] + method. + + Attributes: + name (str): + Required. Name of the execution to be + retrieved. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + view (google.cloud.workflows.executions_v1.types.ExecutionView): + Optional. A view defining which fields should + be filled in the returned execution. The API + will default to the FULL view. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: 'ExecutionView' = proto.Field( + proto.ENUM, + number=2, + enum='ExecutionView', + ) + + +class CancelExecutionRequest(proto.Message): + r"""Request for the + [CancelExecution][google.cloud.workflows.executions.v1.Executions.CancelExecution] + method. + + Attributes: + name (str): + Required. Name of the execution to be + cancelled. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/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-cloud-workflows/v1/google/cloud/workflows/py.typed b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/py.typed new file mode 100644 index 000000000000..b753e6a6bf5b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workflows package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/__init__.py new file mode 100644 index 000000000000..2550c3833296 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/__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 google.cloud.workflows_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.workflows import WorkflowsClient +from .services.workflows import WorkflowsAsyncClient + +from .types.workflows import CreateWorkflowRequest +from .types.workflows import DeleteWorkflowRequest +from .types.workflows import GetWorkflowRequest +from .types.workflows import ListWorkflowsRequest +from .types.workflows import ListWorkflowsResponse +from .types.workflows import OperationMetadata +from .types.workflows import UpdateWorkflowRequest +from .types.workflows import Workflow + +__all__ = ( + 'WorkflowsAsyncClient', +'CreateWorkflowRequest', +'DeleteWorkflowRequest', +'GetWorkflowRequest', +'ListWorkflowsRequest', +'ListWorkflowsResponse', +'OperationMetadata', +'UpdateWorkflowRequest', +'Workflow', +'WorkflowsClient', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_metadata.json new file mode 100644 index 000000000000..a41eecf2981e --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_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.cloud.workflows_v1", + "protoPackage": "google.cloud.workflows.v1", + "schema": "1.0", + "services": { + "Workflows": { + "clients": { + "grpc": { + "libraryClient": "WorkflowsClient", + "rpcs": { + "CreateWorkflow": { + "methods": [ + "create_workflow" + ] + }, + "DeleteWorkflow": { + "methods": [ + "delete_workflow" + ] + }, + "GetWorkflow": { + "methods": [ + "get_workflow" + ] + }, + "ListWorkflows": { + "methods": [ + "list_workflows" + ] + }, + "UpdateWorkflow": { + "methods": [ + "update_workflow" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WorkflowsAsyncClient", + "rpcs": { + "CreateWorkflow": { + "methods": [ + "create_workflow" + ] + }, + "DeleteWorkflow": { + "methods": [ + "delete_workflow" + ] + }, + "GetWorkflow": { + "methods": [ + "get_workflow" + ] + }, + "ListWorkflows": { + "methods": [ + "list_workflows" + ] + }, + "UpdateWorkflow": { + "methods": [ + "update_workflow" + ] + } + } + }, + "rest": { + "libraryClient": "WorkflowsClient", + "rpcs": { + "CreateWorkflow": { + "methods": [ + "create_workflow" + ] + }, + "DeleteWorkflow": { + "methods": [ + "delete_workflow" + ] + }, + "GetWorkflow": { + "methods": [ + "get_workflow" + ] + }, + "ListWorkflows": { + "methods": [ + "list_workflows" + ] + }, + "UpdateWorkflow": { + "methods": [ + "update_workflow" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_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-cloud-workflows/v1/google/cloud/workflows_v1/py.typed b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/py.typed new file mode 100644 index 000000000000..b753e6a6bf5b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workflows package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_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-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/__init__.py new file mode 100644 index 000000000000..5c7fa07ed889 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/__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 WorkflowsClient +from .async_client import WorkflowsAsyncClient + +__all__ = ( + 'WorkflowsClient', + 'WorkflowsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/async_client.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/async_client.py new file mode 100644 index 000000000000..9dffa143847f --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/async_client.py @@ -0,0 +1,1149 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.workflows_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.cloud.location import locations_pb2 # type: ignore +from google.cloud.workflows_v1.services.workflows import pagers +from google.cloud.workflows_v1.types import workflows +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WorkflowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WorkflowsGrpcAsyncIOTransport +from .client import WorkflowsClient + + +class WorkflowsAsyncClient: + """Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + """ + + _client: WorkflowsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WorkflowsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WorkflowsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WorkflowsClient._DEFAULT_UNIVERSE + + crypto_key_path = staticmethod(WorkflowsClient.crypto_key_path) + parse_crypto_key_path = staticmethod(WorkflowsClient.parse_crypto_key_path) + workflow_path = staticmethod(WorkflowsClient.workflow_path) + parse_workflow_path = staticmethod(WorkflowsClient.parse_workflow_path) + common_billing_account_path = staticmethod(WorkflowsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WorkflowsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WorkflowsClient.common_folder_path) + parse_common_folder_path = staticmethod(WorkflowsClient.parse_common_folder_path) + common_organization_path = staticmethod(WorkflowsClient.common_organization_path) + parse_common_organization_path = staticmethod(WorkflowsClient.parse_common_organization_path) + common_project_path = staticmethod(WorkflowsClient.common_project_path) + parse_common_project_path = staticmethod(WorkflowsClient.parse_common_project_path) + common_location_path = staticmethod(WorkflowsClient.common_location_path) + parse_common_location_path = staticmethod(WorkflowsClient.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: + WorkflowsAsyncClient: The constructed client. + """ + return WorkflowsClient.from_service_account_info.__func__(WorkflowsAsyncClient, 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: + WorkflowsAsyncClient: The constructed client. + """ + return WorkflowsClient.from_service_account_file.__func__(WorkflowsAsyncClient, 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 WorkflowsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WorkflowsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkflowsTransport: 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 = WorkflowsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WorkflowsTransport, Callable[..., WorkflowsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workflows 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,WorkflowsTransport,Callable[..., WorkflowsTransport]]]): + 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 WorkflowsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WorkflowsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_workflows(self, + request: Optional[Union[workflows.ListWorkflowsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkflowsAsyncPager: + r"""Lists workflows in a given project and location. + The default order is not specified. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1 + + async def sample_list_workflows(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1.ListWorkflowsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workflows(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1.types.ListWorkflowsRequest, dict]]): + The request object. Request for the + [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] + method. + parent (:class:`str`): + Required. Project and location from + which the workflows should be listed. + Format: + projects/{project}/locations/{location} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows_v1.services.workflows.pagers.ListWorkflowsAsyncPager: + Response for the + [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] + 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, workflows.ListWorkflowsRequest): + request = workflows.ListWorkflowsRequest(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_workflows] + + # Certain fields should be provided within 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.ListWorkflowsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_workflow(self, + request: Optional[Union[workflows.GetWorkflowRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workflows.Workflow: + r"""Gets details of a single workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1 + + async def sample_get_workflow(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1.GetWorkflowRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workflow(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1.types.GetWorkflowRequest, dict]]): + The request object. Request for the + [GetWorkflow][google.cloud.workflows.v1.Workflows.GetWorkflow] + method. + name (:class:`str`): + Required. Name of the workflow for + which information should be retrieved. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows_v1.types.Workflow: + Workflow program to be executed by + Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflows.GetWorkflowRequest): + request = workflows.GetWorkflowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workflow] + + # Certain fields should be provided within 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_workflow(self, + request: Optional[Union[workflows.CreateWorkflowRequest, dict]] = None, + *, + parent: Optional[str] = None, + workflow: Optional[workflows.Workflow] = None, + workflow_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workflow. If a workflow with the specified name + already exists in the specified project and location, the long + running operation returns a + [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] 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.cloud import workflows_v1 + + async def sample_create_workflow(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + workflow = workflows_v1.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1.CreateWorkflowRequest( + parent="parent_value", + workflow=workflow, + workflow_id="workflow_id_value", + ) + + # Make the request + operation = client.create_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1.types.CreateWorkflowRequest, dict]]): + The request object. Request for the + [CreateWorkflow][google.cloud.workflows.v1.Workflows.CreateWorkflow] + method. + parent (:class:`str`): + Required. Project and location in + which the workflow should be created. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workflow (:class:`google.cloud.workflows_v1.types.Workflow`): + Required. Workflow to be created. + This corresponds to the ``workflow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workflow_id (:class:`str`): + Required. The ID of the workflow to be created. It has + to fulfill the following requirements: + + - Must contain only letters, numbers, underscores and + hyphens. + - Must start with a letter. + - Must be between 1-64 characters. + - Must end with a number or a letter. + - Must be unique within the customer project and + location. + + This corresponds to the ``workflow_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workflows_v1.types.Workflow` + Workflow program to be executed by Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflow, workflow_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, workflows.CreateWorkflowRequest): + request = workflows.CreateWorkflowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workflow is not None: + request.workflow = workflow + if workflow_id is not None: + request.workflow_id = workflow_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_workflow] + + # Certain fields should be provided within 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, + workflows.Workflow, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workflow(self, + request: Optional[Union[workflows.DeleteWorkflowRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a workflow with the specified name. + This method also cancels and deletes all running + executions of the workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1 + + async def sample_delete_workflow(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1.DeleteWorkflowRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1.types.DeleteWorkflowRequest, dict]]): + The request object. Request for the + [DeleteWorkflow][google.cloud.workflows.v1.Workflows.DeleteWorkflow] + method. + name (:class:`str`): + Required. Name of the workflow to be + deleted. Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflows.DeleteWorkflowRequest): + request = workflows.DeleteWorkflowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workflow] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workflow(self, + request: Optional[Union[workflows.UpdateWorkflowRequest, dict]] = None, + *, + workflow: Optional[workflows.Workflow] = 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, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an existing workflow. + Running this method has no impact on already running + executions of the workflow. A new revision of the + workflow might be created as a result of a successful + update operation. In that case, the new revision is used + in new workflow executions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1 + + async def sample_update_workflow(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + workflow = workflows_v1.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1.UpdateWorkflowRequest( + workflow=workflow, + ) + + # Make the request + operation = client.update_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1.types.UpdateWorkflowRequest, dict]]): + The request object. Request for the + [UpdateWorkflow][google.cloud.workflows.v1.Workflows.UpdateWorkflow] + method. + workflow (:class:`google.cloud.workflows_v1.types.Workflow`): + Required. Workflow to be updated. + This corresponds to the ``workflow`` 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 to be updated. If not + present, the entire workflow will 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workflows_v1.types.Workflow` + Workflow program to be executed by Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workflow, 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, workflows.UpdateWorkflowRequest): + request = workflows.UpdateWorkflowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workflow is not None: + request.workflow = workflow + 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_workflow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workflow.name", request.workflow.name), + )), + ) + + # 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, + workflows.Workflow, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # 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.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within 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_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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # 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.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location 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 = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within 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_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # 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 = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within 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) -> "WorkflowsAsyncClient": + 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__ = ( + "WorkflowsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/client.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/client.py new file mode 100644 index 000000000000..8ecc9e6ba839 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/client.py @@ -0,0 +1,1505 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.workflows_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 + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workflows_v1.services.workflows import pagers +from google.cloud.workflows_v1.types import workflows +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WorkflowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WorkflowsGrpcTransport +from .transports.grpc_asyncio import WorkflowsGrpcAsyncIOTransport +from .transports.rest import WorkflowsRestTransport + + +class WorkflowsClientMeta(type): + """Metaclass for the Workflows 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[WorkflowsTransport]] + _transport_registry["grpc"] = WorkflowsGrpcTransport + _transport_registry["grpc_asyncio"] = WorkflowsGrpcAsyncIOTransport + _transport_registry["rest"] = WorkflowsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WorkflowsTransport]: + """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 WorkflowsClient(metaclass=WorkflowsClientMeta): + """Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + """ + + @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 = "workflows.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "workflows.{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: + WorkflowsClient: 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: + WorkflowsClient: 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) -> WorkflowsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkflowsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def crypto_key_path(project: str,location: str,keyRing: str,cryptoKey: str,) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}".format(project=project, location=location, keyRing=keyRing, cryptoKey=cryptoKey, ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str,str]: + """Parses a crypto_key path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workflow_path(project: str,location: str,workflow: str,) -> str: + """Returns a fully-qualified workflow string.""" + return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + + @staticmethod + def parse_workflow_path(path: str) -> Dict[str,str]: + """Parses a workflow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = WorkflowsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = WorkflowsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WorkflowsClient._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 = WorkflowsClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = WorkflowsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + WorkflowsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, WorkflowsTransport, Callable[..., WorkflowsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workflows client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,WorkflowsTransport,Callable[..., WorkflowsTransport]]]): + 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 WorkflowsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WorkflowsClient._read_environment_variables() + self._client_cert_source = WorkflowsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = WorkflowsClient._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 + + 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, WorkflowsTransport) + if transport_provided: + # transport is a WorkflowsTransport 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(WorkflowsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + WorkflowsClient._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[WorkflowsTransport], Callable[..., WorkflowsTransport]] = ( + WorkflowsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WorkflowsTransport], 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, + ) + + def list_workflows(self, + request: Optional[Union[workflows.ListWorkflowsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkflowsPager: + r"""Lists workflows in a given project and location. + The default order is not specified. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1 + + def sample_list_workflows(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1.ListWorkflowsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workflows(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workflows_v1.types.ListWorkflowsRequest, dict]): + The request object. Request for the + [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] + method. + parent (str): + Required. Project and location from + which the workflows should be listed. + Format: + projects/{project}/locations/{location} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows_v1.services.workflows.pagers.ListWorkflowsPager: + Response for the + [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] + 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, workflows.ListWorkflowsRequest): + request = workflows.ListWorkflowsRequest(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_workflows] + + # Certain fields should be provided within 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.ListWorkflowsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_workflow(self, + request: Optional[Union[workflows.GetWorkflowRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workflows.Workflow: + r"""Gets details of a single workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1 + + def sample_get_workflow(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1.GetWorkflowRequest( + name="name_value", + ) + + # Make the request + response = client.get_workflow(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows_v1.types.GetWorkflowRequest, dict]): + The request object. Request for the + [GetWorkflow][google.cloud.workflows.v1.Workflows.GetWorkflow] + method. + name (str): + Required. Name of the workflow for + which information should be retrieved. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows_v1.types.Workflow: + Workflow program to be executed by + Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflows.GetWorkflowRequest): + request = workflows.GetWorkflowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workflow] + + # Certain fields should be provided within 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_workflow(self, + request: Optional[Union[workflows.CreateWorkflowRequest, dict]] = None, + *, + parent: Optional[str] = None, + workflow: Optional[workflows.Workflow] = None, + workflow_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workflow. If a workflow with the specified name + already exists in the specified project and location, the long + running operation returns a + [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] 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.cloud import workflows_v1 + + def sample_create_workflow(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + workflow = workflows_v1.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1.CreateWorkflowRequest( + parent="parent_value", + workflow=workflow, + workflow_id="workflow_id_value", + ) + + # Make the request + operation = client.create_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows_v1.types.CreateWorkflowRequest, dict]): + The request object. Request for the + [CreateWorkflow][google.cloud.workflows.v1.Workflows.CreateWorkflow] + method. + parent (str): + Required. Project and location in + which the workflow should be created. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workflow (google.cloud.workflows_v1.types.Workflow): + Required. Workflow to be created. + This corresponds to the ``workflow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workflow_id (str): + Required. The ID of the workflow to be created. It has + to fulfill the following requirements: + + - Must contain only letters, numbers, underscores and + hyphens. + - Must start with a letter. + - Must be between 1-64 characters. + - Must end with a number or a letter. + - Must be unique within the customer project and + location. + + This corresponds to the ``workflow_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workflows_v1.types.Workflow` + Workflow program to be executed by Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflow, workflow_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, workflows.CreateWorkflowRequest): + request = workflows.CreateWorkflowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workflow is not None: + request.workflow = workflow + if workflow_id is not None: + request.workflow_id = workflow_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workflow] + + # Certain fields should be provided within 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, + workflows.Workflow, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workflow(self, + request: Optional[Union[workflows.DeleteWorkflowRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a workflow with the specified name. + This method also cancels and deletes all running + executions of the workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1 + + def sample_delete_workflow(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1.DeleteWorkflowRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows_v1.types.DeleteWorkflowRequest, dict]): + The request object. Request for the + [DeleteWorkflow][google.cloud.workflows.v1.Workflows.DeleteWorkflow] + method. + name (str): + Required. Name of the workflow to be + deleted. Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflows.DeleteWorkflowRequest): + request = workflows.DeleteWorkflowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workflow] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workflow(self, + request: Optional[Union[workflows.UpdateWorkflowRequest, dict]] = None, + *, + workflow: Optional[workflows.Workflow] = 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, str]] = (), + ) -> operation.Operation: + r"""Updates an existing workflow. + Running this method has no impact on already running + executions of the workflow. A new revision of the + workflow might be created as a result of a successful + update operation. In that case, the new revision is used + in new workflow executions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1 + + def sample_update_workflow(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + workflow = workflows_v1.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1.UpdateWorkflowRequest( + workflow=workflow, + ) + + # Make the request + operation = client.update_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows_v1.types.UpdateWorkflowRequest, dict]): + The request object. Request for the + [UpdateWorkflow][google.cloud.workflows.v1.Workflows.UpdateWorkflow] + method. + workflow (google.cloud.workflows_v1.types.Workflow): + Required. Workflow to be updated. + This corresponds to the ``workflow`` 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 to be updated. If not + present, the entire workflow will 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workflows_v1.types.Workflow` + Workflow program to be executed by Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workflow, 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, workflows.UpdateWorkflowRequest): + request = workflows.UpdateWorkflowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workflow is not None: + request.workflow = workflow + 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_workflow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workflow.name", request.workflow.name), + )), + ) + + # 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, + workflows.Workflow, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "WorkflowsClient": + 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 list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.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. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # 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.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within 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_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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.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. + Returns: + None + """ + # 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.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.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. + Returns: + ~.location_pb2.Location: + Location 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 = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within 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_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.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. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # 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 = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within 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__ = ( + "WorkflowsClient", +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/pagers.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/pagers.py new file mode 100644 index 000000000000..06d0678baf04 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows_v1.types import workflows + + +class ListWorkflowsPager: + """A pager for iterating through ``list_workflows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workflows_v1.types.ListWorkflowsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workflows`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkflows`` requests and continue to iterate + through the ``workflows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workflows_v1.types.ListWorkflowsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workflows.ListWorkflowsResponse], + request: workflows.ListWorkflowsRequest, + response: workflows.ListWorkflowsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workflows_v1.types.ListWorkflowsRequest): + The initial request object. + response (google.cloud.workflows_v1.types.ListWorkflowsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workflows.ListWorkflowsRequest(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[workflows.ListWorkflowsResponse]: + 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[workflows.Workflow]: + for page in self.pages: + yield from page.workflows + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkflowsAsyncPager: + """A pager for iterating through ``list_workflows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workflows_v1.types.ListWorkflowsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workflows`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkflows`` requests and continue to iterate + through the ``workflows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workflows_v1.types.ListWorkflowsResponse` + attributes are available on the 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[workflows.ListWorkflowsResponse]], + request: workflows.ListWorkflowsRequest, + response: workflows.ListWorkflowsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workflows_v1.types.ListWorkflowsRequest): + The initial request object. + response (google.cloud.workflows_v1.types.ListWorkflowsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workflows.ListWorkflowsRequest(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[workflows.ListWorkflowsResponse]: + 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[workflows.Workflow]: + async def async_generator(): + async for page in self.pages: + for response in page.workflows: + 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-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/README.rst b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/README.rst new file mode 100644 index 000000000000..f8fb5a859227 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`WorkflowsTransport` is the ABC for all transports. +- public child `WorkflowsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `WorkflowsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseWorkflowsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `WorkflowsRestTransport` 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-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/__init__.py new file mode 100644 index 000000000000..6ebe8b349db7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/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 WorkflowsTransport +from .grpc import WorkflowsGrpcTransport +from .grpc_asyncio import WorkflowsGrpcAsyncIOTransport +from .rest import WorkflowsRestTransport +from .rest import WorkflowsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WorkflowsTransport]] +_transport_registry['grpc'] = WorkflowsGrpcTransport +_transport_registry['grpc_asyncio'] = WorkflowsGrpcAsyncIOTransport +_transport_registry['rest'] = WorkflowsRestTransport + +__all__ = ( + 'WorkflowsTransport', + 'WorkflowsGrpcTransport', + 'WorkflowsGrpcAsyncIOTransport', + 'WorkflowsRestTransport', + 'WorkflowsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/base.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/base.py new file mode 100644 index 000000000000..c21df987437e --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/base.py @@ -0,0 +1,286 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows_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.cloud.location import locations_pb2 # type: ignore +from google.cloud.workflows_v1.types import workflows +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WorkflowsTransport(abc.ABC): + """Abstract transport class for Workflows.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'workflows.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: 'workflows.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_workflows: gapic_v1.method.wrap_method( + self.list_workflows, + default_timeout=None, + client_info=client_info, + ), + self.get_workflow: gapic_v1.method.wrap_method( + self.get_workflow, + default_timeout=None, + client_info=client_info, + ), + self.create_workflow: gapic_v1.method.wrap_method( + self.create_workflow, + default_timeout=None, + client_info=client_info, + ), + self.delete_workflow: gapic_v1.method.wrap_method( + self.delete_workflow, + default_timeout=None, + client_info=client_info, + ), + self.update_workflow: gapic_v1.method.wrap_method( + self.update_workflow, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + 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, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + 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 list_workflows(self) -> Callable[ + [workflows.ListWorkflowsRequest], + Union[ + workflows.ListWorkflowsResponse, + Awaitable[workflows.ListWorkflowsResponse] + ]]: + raise NotImplementedError() + + @property + def get_workflow(self) -> Callable[ + [workflows.GetWorkflowRequest], + Union[ + workflows.Workflow, + Awaitable[workflows.Workflow] + ]]: + raise NotImplementedError() + + @property + def create_workflow(self) -> Callable[ + [workflows.CreateWorkflowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workflow(self) -> Callable[ + [workflows.DeleteWorkflowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workflow(self) -> Callable[ + [workflows.UpdateWorkflowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WorkflowsTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc.py new file mode 100644 index 000000000000..ed43a47b8790 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc.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 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 + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workflows_v1.types import workflows +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO + + +class WorkflowsGrpcTransport(WorkflowsTransport): + """gRPC backend transport for Workflows. + + Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workflows.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: 'workflows.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'workflows.googleapis.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.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_workflows(self) -> Callable[ + [workflows.ListWorkflowsRequest], + workflows.ListWorkflowsResponse]: + r"""Return a callable for the list workflows method over gRPC. + + Lists workflows in a given project and location. + The default order is not specified. + + Returns: + Callable[[~.ListWorkflowsRequest], + ~.ListWorkflowsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workflows' not in self._stubs: + self._stubs['list_workflows'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/ListWorkflows', + request_serializer=workflows.ListWorkflowsRequest.serialize, + response_deserializer=workflows.ListWorkflowsResponse.deserialize, + ) + return self._stubs['list_workflows'] + + @property + def get_workflow(self) -> Callable[ + [workflows.GetWorkflowRequest], + workflows.Workflow]: + r"""Return a callable for the get workflow method over gRPC. + + Gets details of a single workflow. + + Returns: + Callable[[~.GetWorkflowRequest], + ~.Workflow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workflow' not in self._stubs: + self._stubs['get_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/GetWorkflow', + request_serializer=workflows.GetWorkflowRequest.serialize, + response_deserializer=workflows.Workflow.deserialize, + ) + return self._stubs['get_workflow'] + + @property + def create_workflow(self) -> Callable[ + [workflows.CreateWorkflowRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workflow method over gRPC. + + Creates a new workflow. If a workflow with the specified name + already exists in the specified project and location, the long + running operation returns a + [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error. + + Returns: + Callable[[~.CreateWorkflowRequest], + ~.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 'create_workflow' not in self._stubs: + self._stubs['create_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/CreateWorkflow', + request_serializer=workflows.CreateWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workflow'] + + @property + def delete_workflow(self) -> Callable[ + [workflows.DeleteWorkflowRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workflow method over gRPC. + + Deletes a workflow with the specified name. + This method also cancels and deletes all running + executions of the workflow. + + Returns: + Callable[[~.DeleteWorkflowRequest], + ~.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 'delete_workflow' not in self._stubs: + self._stubs['delete_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/DeleteWorkflow', + request_serializer=workflows.DeleteWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workflow'] + + @property + def update_workflow(self) -> Callable[ + [workflows.UpdateWorkflowRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workflow method over gRPC. + + Updates an existing workflow. + Running this method has no impact on already running + executions of the workflow. A new revision of the + workflow might be created as a result of a successful + update operation. In that case, the new revision is used + in new workflow executions. + + Returns: + Callable[[~.UpdateWorkflowRequest], + ~.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 'update_workflow' not in self._stubs: + self._stubs['update_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/UpdateWorkflow', + request_serializer=workflows.UpdateWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workflow'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @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.grpc_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 list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations 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 "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WorkflowsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc_asyncio.py new file mode 100644 index 000000000000..35ee7bb86bb5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc_asyncio.py @@ -0,0 +1,563 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workflows_v1.types import workflows +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO +from .grpc import WorkflowsGrpcTransport + + +class WorkflowsGrpcAsyncIOTransport(WorkflowsTransport): + """gRPC AsyncIO backend transport for Workflows. + + Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workflows.googleapis.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 = 'workflows.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: 'workflows.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_workflows(self) -> Callable[ + [workflows.ListWorkflowsRequest], + Awaitable[workflows.ListWorkflowsResponse]]: + r"""Return a callable for the list workflows method over gRPC. + + Lists workflows in a given project and location. + The default order is not specified. + + Returns: + Callable[[~.ListWorkflowsRequest], + Awaitable[~.ListWorkflowsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workflows' not in self._stubs: + self._stubs['list_workflows'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/ListWorkflows', + request_serializer=workflows.ListWorkflowsRequest.serialize, + response_deserializer=workflows.ListWorkflowsResponse.deserialize, + ) + return self._stubs['list_workflows'] + + @property + def get_workflow(self) -> Callable[ + [workflows.GetWorkflowRequest], + Awaitable[workflows.Workflow]]: + r"""Return a callable for the get workflow method over gRPC. + + Gets details of a single workflow. + + Returns: + Callable[[~.GetWorkflowRequest], + Awaitable[~.Workflow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workflow' not in self._stubs: + self._stubs['get_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/GetWorkflow', + request_serializer=workflows.GetWorkflowRequest.serialize, + response_deserializer=workflows.Workflow.deserialize, + ) + return self._stubs['get_workflow'] + + @property + def create_workflow(self) -> Callable[ + [workflows.CreateWorkflowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workflow method over gRPC. + + Creates a new workflow. If a workflow with the specified name + already exists in the specified project and location, the long + running operation returns a + [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error. + + Returns: + Callable[[~.CreateWorkflowRequest], + 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 'create_workflow' not in self._stubs: + self._stubs['create_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/CreateWorkflow', + request_serializer=workflows.CreateWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workflow'] + + @property + def delete_workflow(self) -> Callable[ + [workflows.DeleteWorkflowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workflow method over gRPC. + + Deletes a workflow with the specified name. + This method also cancels and deletes all running + executions of the workflow. + + Returns: + Callable[[~.DeleteWorkflowRequest], + 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 'delete_workflow' not in self._stubs: + self._stubs['delete_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/DeleteWorkflow', + request_serializer=workflows.DeleteWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workflow'] + + @property + def update_workflow(self) -> Callable[ + [workflows.UpdateWorkflowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workflow method over gRPC. + + Updates an existing workflow. + Running this method has no impact on already running + executions of the workflow. A new revision of the + workflow might be created as a result of a successful + update operation. In that case, the new revision is used + in new workflow executions. + + Returns: + Callable[[~.UpdateWorkflowRequest], + 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 'update_workflow' not in self._stubs: + self._stubs['update_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1.Workflows/UpdateWorkflow', + request_serializer=workflows.UpdateWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workflow'] + + 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_workflows: self._wrap_method( + self.list_workflows, + default_timeout=None, + client_info=client_info, + ), + self.get_workflow: self._wrap_method( + self.get_workflow, + default_timeout=None, + client_info=client_info, + ), + self.create_workflow: self._wrap_method( + self.create_workflow, + default_timeout=None, + client_info=client_info, + ), + self.delete_workflow: self._wrap_method( + self.delete_workflow, + default_timeout=None, + client_info=client_info, + ), + self.update_workflow: self._wrap_method( + self.update_workflow, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @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.grpc_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 list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations 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 "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'WorkflowsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest.py new file mode 100644 index 000000000000..6e27a172c865 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest.py @@ -0,0 +1,1224 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.workflows_v1.types import workflows +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseWorkflowsRestTransport +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 + + +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 WorkflowsRestInterceptor: + """Interceptor for Workflows. + + 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 WorkflowsRestTransport. + + .. code-block:: python + class MyCustomWorkflowsInterceptor(WorkflowsRestInterceptor): + def pre_create_workflow(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workflow(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workflow(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workflow(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workflow(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workflow(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workflows(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workflows(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workflow(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workflow(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WorkflowsRestTransport(interceptor=MyCustomWorkflowsInterceptor()) + client = WorkflowsClient(transport=transport) + + + """ + def pre_create_workflow(self, request: workflows.CreateWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.CreateWorkflowRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workflow + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_create_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workflow + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_delete_workflow(self, request: workflows.DeleteWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.DeleteWorkflowRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workflow + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_delete_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workflow + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_get_workflow(self, request: workflows.GetWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.GetWorkflowRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workflow + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_get_workflow(self, response: workflows.Workflow) -> workflows.Workflow: + """Post-rpc interceptor for get_workflow + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_list_workflows(self, request: workflows.ListWorkflowsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.ListWorkflowsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workflows + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_list_workflows(self, response: workflows.ListWorkflowsResponse) -> workflows.ListWorkflowsResponse: + """Post-rpc interceptor for list_workflows + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_update_workflow(self, request: workflows.UpdateWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.UpdateWorkflowRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workflow + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_update_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workflow + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows 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 Workflows server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WorkflowsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WorkflowsRestInterceptor + + +class WorkflowsRestTransport(_BaseWorkflowsRestTransport): + """REST backend synchronous transport for Workflows. + + Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'workflows.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[WorkflowsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'workflows.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 WorkflowsRestInterceptor() + 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.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + '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 _CreateWorkflow(_BaseWorkflowsRestTransport._BaseCreateWorkflow, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.CreateWorkflow") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workflows.CreateWorkflowRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workflow method over HTTP. + + Args: + request (~.workflows.CreateWorkflowRequest): + The request object. Request for the + [CreateWorkflow][google.cloud.workflows.v1.Workflows.CreateWorkflow] + method. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_http_options() + request, metadata = self._interceptor.pre_create_workflow(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_transcoded_request(http_options, request) + + body = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._CreateWorkflow._get_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_create_workflow(resp) + return resp + + class _DeleteWorkflow(_BaseWorkflowsRestTransport._BaseDeleteWorkflow, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.DeleteWorkflow") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workflows.DeleteWorkflowRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workflow method over HTTP. + + Args: + request (~.workflows.DeleteWorkflowRequest): + The request object. Request for the + [DeleteWorkflow][google.cloud.workflows.v1.Workflows.DeleteWorkflow] + method. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_http_options() + request, metadata = self._interceptor.pre_delete_workflow(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._DeleteWorkflow._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, 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_delete_workflow(resp) + return resp + + class _GetWorkflow(_BaseWorkflowsRestTransport._BaseGetWorkflow, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.GetWorkflow") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workflows.GetWorkflowRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workflows.Workflow: + r"""Call the get workflow method over HTTP. + + Args: + request (~.workflows.GetWorkflowRequest): + The request object. Request for the + [GetWorkflow][google.cloud.workflows.v1.Workflows.GetWorkflow] + method. + retry (google.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. + + Returns: + ~.workflows.Workflow: + Workflow program to be executed by + Workflows. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_http_options() + request, metadata = self._interceptor.pre_get_workflow(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._GetWorkflow._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workflows.Workflow() + pb_resp = workflows.Workflow.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workflow(resp) + return resp + + class _ListWorkflows(_BaseWorkflowsRestTransport._BaseListWorkflows, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.ListWorkflows") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workflows.ListWorkflowsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workflows.ListWorkflowsResponse: + r"""Call the list workflows method over HTTP. + + Args: + request (~.workflows.ListWorkflowsRequest): + The request object. Request for the + [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] + method. + retry (google.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. + + Returns: + ~.workflows.ListWorkflowsResponse: + Response for the + [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] + method. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseListWorkflows._get_http_options() + request, metadata = self._interceptor.pre_list_workflows(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseListWorkflows._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseListWorkflows._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._ListWorkflows._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workflows.ListWorkflowsResponse() + pb_resp = workflows.ListWorkflowsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workflows(resp) + return resp + + class _UpdateWorkflow(_BaseWorkflowsRestTransport._BaseUpdateWorkflow, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.UpdateWorkflow") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workflows.UpdateWorkflowRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workflow method over HTTP. + + Args: + request (~.workflows.UpdateWorkflowRequest): + The request object. Request for the + [UpdateWorkflow][google.cloud.workflows.v1.Workflows.UpdateWorkflow] + method. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_http_options() + request, metadata = self._interceptor.pre_update_workflow(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_transcoded_request(http_options, request) + + body = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._UpdateWorkflow._get_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_update_workflow(resp) + return resp + + @property + def create_workflow(self) -> Callable[ + [workflows.CreateWorkflowRequest], + 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._CreateWorkflow(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workflow(self) -> Callable[ + [workflows.DeleteWorkflowRequest], + 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._DeleteWorkflow(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workflow(self) -> Callable[ + [workflows.GetWorkflowRequest], + workflows.Workflow]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkflow(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workflows(self) -> Callable[ + [workflows.ListWorkflowsRequest], + workflows.ListWorkflowsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkflows(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workflow(self) -> Callable[ + [workflows.UpdateWorkflowRequest], + 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._UpdateWorkflow(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseWorkflowsRestTransport._BaseGetLocation, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.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. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseWorkflowsRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseWorkflowsRestTransport._BaseListLocations, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.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. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseWorkflowsRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseWorkflowsRestTransport._BaseDeleteOperation, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(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.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.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. + """ + + http_options = _BaseWorkflowsRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseWorkflowsRestTransport._BaseGetOperation, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseWorkflowsRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._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) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseWorkflowsRestTransport._BaseListOperations, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(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.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.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. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseWorkflowsRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WorkflowsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest_base.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest_base.py new file mode 100644 index 000000000000..903728571d5d --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest_base.py @@ -0,0 +1,423 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 google.cloud.location import locations_pb2 # type: ignore +from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.workflows_v1.types import workflows +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseWorkflowsRestTransport(WorkflowsTransport): + """Base REST backend transport for Workflows. + + 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 = 'workflows.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: 'workflows.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 _BaseCreateWorkflow: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workflowId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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/*}/workflows', + 'body': 'workflow', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.CreateWorkflowRequest.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(_BaseWorkflowsRestTransport._BaseCreateWorkflow._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteWorkflow: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/workflows/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.DeleteWorkflowRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetWorkflow: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/workflows/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.GetWorkflowRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkflowsRestTransport._BaseGetWorkflow._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkflows: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/workflows', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.ListWorkflowsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkflowsRestTransport._BaseListWorkflows._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateWorkflow: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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/{workflow.name=projects/*/locations/*/workflows/*}', + 'body': 'workflow', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.UpdateWorkflowRequest.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(_BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + 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/*}', + }, + ] + 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 + + class _BaseListLocations: + 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', + }, + ] + 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 + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + '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 + + 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 + + class _BaseListOperations: + 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__=( + '_BaseWorkflowsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/__init__.py new file mode 100644 index 000000000000..99bb09e40279 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/__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 .workflows import ( + CreateWorkflowRequest, + DeleteWorkflowRequest, + GetWorkflowRequest, + ListWorkflowsRequest, + ListWorkflowsResponse, + OperationMetadata, + UpdateWorkflowRequest, + Workflow, +) + +__all__ = ( + 'CreateWorkflowRequest', + 'DeleteWorkflowRequest', + 'GetWorkflowRequest', + 'ListWorkflowsRequest', + 'ListWorkflowsResponse', + 'OperationMetadata', + 'UpdateWorkflowRequest', + 'Workflow', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/workflows.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/workflows.py new file mode 100644 index 000000000000..65ed8d6c80f9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/workflows.py @@ -0,0 +1,521 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.workflows.v1', + manifest={ + 'Workflow', + 'ListWorkflowsRequest', + 'ListWorkflowsResponse', + 'GetWorkflowRequest', + 'CreateWorkflowRequest', + 'DeleteWorkflowRequest', + 'UpdateWorkflowRequest', + 'OperationMetadata', + }, +) + + +class Workflow(proto.Message): + r"""Workflow program to be executed by Workflows. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The resource name of the workflow. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + description (str): + Description of the workflow provided by the + user. Must be at most 1000 unicode characters + long. + state (google.cloud.workflows_v1.types.Workflow.State): + Output only. State of the workflow + deployment. + revision_id (str): + Output only. The revision of the workflow. A new revision of + a workflow is created as a result of updating the following + properties of a workflow: + + - [Service + account][google.cloud.workflows.v1.Workflow.service_account] + - [Workflow code to be + executed][google.cloud.workflows.v1.Workflow.source_contents] + + The format is "000001-a4d", where the first six characters + define the zero-padded revision ordinal number. They are + followed by a hyphen and three hexadecimal random + characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp for when the + workflow was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp for when the + workflow was last updated. + revision_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp for the latest + revision of the workflow's creation. + labels (MutableMapping[str, str]): + Labels associated with this workflow. + Labels can contain at most 64 entries. Keys and + values can be no longer than 63 characters and + can only contain lowercase letters, numeric + characters, underscores, and dashes. Label keys + must start with a letter. International + characters are allowed. + service_account (str): + The service account associated with the latest workflow + version. This service account represents the identity of the + workflow and determines what permissions the workflow has. + Format: projects/{project}/serviceAccounts/{account} or + {account} + + Using ``-`` as a wildcard for the ``{project}`` or not + providing one at all will infer the project from the + account. The ``{account}`` value can be the ``email`` + address or the ``unique_id`` of the service account. + + If not provided, workflow will use the project's default + service account. Modifying this field for an existing + workflow results in a new workflow revision. + source_contents (str): + Workflow code to be executed. The size limit + is 128KB. + + This field is a member of `oneof`_ ``source_code``. + crypto_key_name (str): + Optional. The resource name of a KMS crypto key used to + encrypt or decrypt the data associated with the workflow. + + Format: + projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey} + + Using ``-`` as a wildcard for the ``{project}`` or not + providing one at all will infer the project from the + account. + + If not provided, data associated with the workflow will not + be CMEK-encrypted. + state_error (google.cloud.workflows_v1.types.Workflow.StateError): + Output only. Error regarding the state of the + workflow. For example, this field will have + error details if the execution data is + unavailable due to revoked KMS key permissions. + call_log_level (google.cloud.workflows_v1.types.Workflow.CallLogLevel): + Optional. Describes the level of platform + logging to apply to calls and call responses + during executions of this workflow. If both the + workflow and the execution specify a logging + level, the execution level takes precedence. + user_env_vars (MutableMapping[str, str]): + Optional. User-defined environment variables + associated with this workflow revision. This map + has a maximum length of 20. Each string can take + up to 40KiB. Keys cannot be empty strings and + cannot start with “GOOGLE” or “WORKFLOWS". + """ + class State(proto.Enum): + r"""Describes the current state of workflow deployment. + + Values: + STATE_UNSPECIFIED (0): + Invalid state. + ACTIVE (1): + The workflow has been deployed successfully + and is serving. + UNAVAILABLE (2): + Workflow data is unavailable. See the ``state_error`` field. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + UNAVAILABLE = 2 + + class CallLogLevel(proto.Enum): + r"""Describes the level of platform logging to apply to calls and + call responses during workflow executions. + + Values: + CALL_LOG_LEVEL_UNSPECIFIED (0): + No call logging level specified. + LOG_ALL_CALLS (1): + Log all call steps within workflows, all call + returns, and all exceptions raised. + LOG_ERRORS_ONLY (2): + Log only exceptions that are raised from call + steps within workflows. + LOG_NONE (3): + Explicitly log nothing. + """ + CALL_LOG_LEVEL_UNSPECIFIED = 0 + LOG_ALL_CALLS = 1 + LOG_ERRORS_ONLY = 2 + LOG_NONE = 3 + + class StateError(proto.Message): + r"""Describes an error related to the current state of the + workflow. + + Attributes: + details (str): + Provides specifics about the error. + type_ (google.cloud.workflows_v1.types.Workflow.StateError.Type): + The type of this state error. + """ + class Type(proto.Enum): + r"""Describes the possibled types of a state error. + + Values: + TYPE_UNSPECIFIED (0): + No type specified. + KMS_ERROR (1): + Caused by an issue with KMS. + """ + TYPE_UNSPECIFIED = 0 + KMS_ERROR = 1 + + details: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'Workflow.StateError.Type' = proto.Field( + proto.ENUM, + number=2, + enum='Workflow.StateError.Type', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + revision_id: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + revision_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + service_account: str = proto.Field( + proto.STRING, + number=9, + ) + source_contents: str = proto.Field( + proto.STRING, + number=10, + oneof='source_code', + ) + crypto_key_name: str = proto.Field( + proto.STRING, + number=11, + ) + state_error: StateError = proto.Field( + proto.MESSAGE, + number=12, + message=StateError, + ) + call_log_level: CallLogLevel = proto.Field( + proto.ENUM, + number=13, + enum=CallLogLevel, + ) + user_env_vars: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + + +class ListWorkflowsRequest(proto.Message): + r"""Request for the + [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] + method. + + Attributes: + parent (str): + Required. Project and location from which the + workflows should be listed. Format: + projects/{project}/locations/{location} + page_size (int): + Maximum number of workflows to return per + call. The service might return fewer than this + value even if not at the end of the collection. + If a value is not specified, a default value of + 500 is used. The maximum permitted value is 1000 + and values greater than 1000 are coerced down to + 1000. + page_token (str): + A page token, received from a previous ``ListWorkflows`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListWorkflows`` must match the call that provided the page + token. + filter (str): + Filter to restrict results to specific + workflows. + order_by (str): + Comma-separated list of fields that specify + the order of the results. Default sorting order + for a field is ascending. To specify descending + order for a field, append a "desc" suffix. + If not specified, the results are returned in an + unspecified order. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListWorkflowsResponse(proto.Message): + r"""Response for the + [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] + method. + + Attributes: + workflows (MutableSequence[google.cloud.workflows_v1.types.Workflow]): + The workflows that match the request. + 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. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workflows: MutableSequence['Workflow'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workflow', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetWorkflowRequest(proto.Message): + r"""Request for the + [GetWorkflow][google.cloud.workflows.v1.Workflows.GetWorkflow] + method. + + Attributes: + name (str): + Required. Name of the workflow for which + information should be retrieved. Format: + projects/{project}/locations/{location}/workflows/{workflow} + revision_id (str): + Optional. The revision of the workflow to retrieve. If the + revision_id is empty, the latest revision is retrieved. The + format is "000001-a4d", where the first six characters + define the zero-padded decimal revision number. They are + followed by a hyphen and three hexadecimal characters. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateWorkflowRequest(proto.Message): + r"""Request for the + [CreateWorkflow][google.cloud.workflows.v1.Workflows.CreateWorkflow] + method. + + Attributes: + parent (str): + Required. Project and location in which the + workflow should be created. Format: + projects/{project}/locations/{location} + workflow (google.cloud.workflows_v1.types.Workflow): + Required. Workflow to be created. + workflow_id (str): + Required. The ID of the workflow to be created. It has to + fulfill the following requirements: + + - Must contain only letters, numbers, underscores and + hyphens. + - Must start with a letter. + - Must be between 1-64 characters. + - Must end with a number or a letter. + - Must be unique within the customer project and location. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workflow: 'Workflow' = proto.Field( + proto.MESSAGE, + number=2, + message='Workflow', + ) + workflow_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteWorkflowRequest(proto.Message): + r"""Request for the + [DeleteWorkflow][google.cloud.workflows.v1.Workflows.DeleteWorkflow] + method. + + Attributes: + name (str): + Required. Name of the workflow to be deleted. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateWorkflowRequest(proto.Message): + r"""Request for the + [UpdateWorkflow][google.cloud.workflows.v1.Workflows.UpdateWorkflow] + method. + + Attributes: + workflow (google.cloud.workflows_v1.types.Workflow): + Required. Workflow to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + List of fields to be updated. If not present, + the entire workflow will be updated. + """ + + workflow: 'Workflow' = proto.Field( + proto.MESSAGE, + number=1, + message='Workflow', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation was created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation finished running. + target (str): + Server-defined resource path for the target + of the operation. + verb (str): + Name of the verb executed by the operation. + api_version (str): + API version used to start the operation. + """ + + create_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, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + api_version: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workflows/v1/mypy.ini b/owl-bot-staging/google-cloud-workflows/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workflows/v1/noxfile.py b/owl-bot-staging/google-cloud-workflows/v1/noxfile.py new file mode 100644 index 000000000000..f3df2d3da03f --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows' + +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/cloud/workflows_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/cloud/workflows_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-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json new file mode 100644 index 000000000000..56d60ff5a803 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json @@ -0,0 +1,667 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.workflows.executions.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-workflows-executions", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient", + "shortName": "ExecutionsAsyncClient" + }, + "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient.cancel_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1.Executions.CancelExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1.Executions", + "shortName": "Executions" + }, + "shortName": "CancelExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1.types.CancelExecutionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1.types.Execution", + "shortName": "cancel_execution" + }, + "description": "Sample for CancelExecution", + "file": "workflowexecutions_v1_generated_executions_cancel_execution_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1_generated_Executions_CancelExecution_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": "workflowexecutions_v1_generated_executions_cancel_execution_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient", + "shortName": "ExecutionsClient" + }, + "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient.cancel_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1.Executions.CancelExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1.Executions", + "shortName": "Executions" + }, + "shortName": "CancelExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1.types.CancelExecutionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1.types.Execution", + "shortName": "cancel_execution" + }, + "description": "Sample for CancelExecution", + "file": "workflowexecutions_v1_generated_executions_cancel_execution_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1_generated_Executions_CancelExecution_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": "workflowexecutions_v1_generated_executions_cancel_execution_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient", + "shortName": "ExecutionsAsyncClient" + }, + "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient.create_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1.Executions.CreateExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1.Executions", + "shortName": "Executions" + }, + "shortName": "CreateExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1.types.CreateExecutionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "execution", + "type": "google.cloud.workflows.executions_v1.types.Execution" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1.types.Execution", + "shortName": "create_execution" + }, + "description": "Sample for CreateExecution", + "file": "workflowexecutions_v1_generated_executions_create_execution_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1_generated_Executions_CreateExecution_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": "workflowexecutions_v1_generated_executions_create_execution_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient", + "shortName": "ExecutionsClient" + }, + "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient.create_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1.Executions.CreateExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1.Executions", + "shortName": "Executions" + }, + "shortName": "CreateExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1.types.CreateExecutionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "execution", + "type": "google.cloud.workflows.executions_v1.types.Execution" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1.types.Execution", + "shortName": "create_execution" + }, + "description": "Sample for CreateExecution", + "file": "workflowexecutions_v1_generated_executions_create_execution_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1_generated_Executions_CreateExecution_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": "workflowexecutions_v1_generated_executions_create_execution_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient", + "shortName": "ExecutionsAsyncClient" + }, + "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient.get_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1.Executions.GetExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1.Executions", + "shortName": "Executions" + }, + "shortName": "GetExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1.types.GetExecutionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1.types.Execution", + "shortName": "get_execution" + }, + "description": "Sample for GetExecution", + "file": "workflowexecutions_v1_generated_executions_get_execution_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1_generated_Executions_GetExecution_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": "workflowexecutions_v1_generated_executions_get_execution_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient", + "shortName": "ExecutionsClient" + }, + "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient.get_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1.Executions.GetExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1.Executions", + "shortName": "Executions" + }, + "shortName": "GetExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1.types.GetExecutionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1.types.Execution", + "shortName": "get_execution" + }, + "description": "Sample for GetExecution", + "file": "workflowexecutions_v1_generated_executions_get_execution_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1_generated_Executions_GetExecution_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": "workflowexecutions_v1_generated_executions_get_execution_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient", + "shortName": "ExecutionsAsyncClient" + }, + "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient.list_executions", + "method": { + "fullName": "google.cloud.workflows.executions.v1.Executions.ListExecutions", + "service": { + "fullName": "google.cloud.workflows.executions.v1.Executions", + "shortName": "Executions" + }, + "shortName": "ListExecutions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1.types.ListExecutionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1.services.executions.pagers.ListExecutionsAsyncPager", + "shortName": "list_executions" + }, + "description": "Sample for ListExecutions", + "file": "workflowexecutions_v1_generated_executions_list_executions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1_generated_Executions_ListExecutions_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": "workflowexecutions_v1_generated_executions_list_executions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient", + "shortName": "ExecutionsClient" + }, + "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient.list_executions", + "method": { + "fullName": "google.cloud.workflows.executions.v1.Executions.ListExecutions", + "service": { + "fullName": "google.cloud.workflows.executions.v1.Executions", + "shortName": "Executions" + }, + "shortName": "ListExecutions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1.types.ListExecutionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1.services.executions.pagers.ListExecutionsPager", + "shortName": "list_executions" + }, + "description": "Sample for ListExecutions", + "file": "workflowexecutions_v1_generated_executions_list_executions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1_generated_Executions_ListExecutions_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": "workflowexecutions_v1_generated_executions_list_executions_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json new file mode 100644 index 000000000000..5eeb3c21a076 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json @@ -0,0 +1,844 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.workflows.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-workflows", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.create_workflow", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.CreateWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "CreateWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.CreateWorkflowRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workflow", + "type": "google.cloud.workflows_v1.types.Workflow" + }, + { + "name": "workflow_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workflow" + }, + "description": "Sample for CreateWorkflow", + "file": "workflows_v1_generated_workflows_create_workflow_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_CreateWorkflow_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1_generated_workflows_create_workflow_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsClient.create_workflow", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.CreateWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "CreateWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.CreateWorkflowRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workflow", + "type": "google.cloud.workflows_v1.types.Workflow" + }, + { + "name": "workflow_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workflow" + }, + "description": "Sample for CreateWorkflow", + "file": "workflows_v1_generated_workflows_create_workflow_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_CreateWorkflow_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1_generated_workflows_create_workflow_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.delete_workflow", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.DeleteWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "DeleteWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.DeleteWorkflowRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_workflow" + }, + "description": "Sample for DeleteWorkflow", + "file": "workflows_v1_generated_workflows_delete_workflow_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_DeleteWorkflow_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1_generated_workflows_delete_workflow_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsClient.delete_workflow", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.DeleteWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "DeleteWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.DeleteWorkflowRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_workflow" + }, + "description": "Sample for DeleteWorkflow", + "file": "workflows_v1_generated_workflows_delete_workflow_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_DeleteWorkflow_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1_generated_workflows_delete_workflow_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.get_workflow", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.GetWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "GetWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.GetWorkflowRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows_v1.types.Workflow", + "shortName": "get_workflow" + }, + "description": "Sample for GetWorkflow", + "file": "workflows_v1_generated_workflows_get_workflow_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_GetWorkflow_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": "workflows_v1_generated_workflows_get_workflow_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsClient.get_workflow", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.GetWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "GetWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.GetWorkflowRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows_v1.types.Workflow", + "shortName": "get_workflow" + }, + "description": "Sample for GetWorkflow", + "file": "workflows_v1_generated_workflows_get_workflow_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_GetWorkflow_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": "workflows_v1_generated_workflows_get_workflow_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.list_workflows", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.ListWorkflows", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "ListWorkflows" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.ListWorkflowsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows_v1.services.workflows.pagers.ListWorkflowsAsyncPager", + "shortName": "list_workflows" + }, + "description": "Sample for ListWorkflows", + "file": "workflows_v1_generated_workflows_list_workflows_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_ListWorkflows_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": "workflows_v1_generated_workflows_list_workflows_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsClient.list_workflows", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.ListWorkflows", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "ListWorkflows" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.ListWorkflowsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows_v1.services.workflows.pagers.ListWorkflowsPager", + "shortName": "list_workflows" + }, + "description": "Sample for ListWorkflows", + "file": "workflows_v1_generated_workflows_list_workflows_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_ListWorkflows_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": "workflows_v1_generated_workflows_list_workflows_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.update_workflow", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.UpdateWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "UpdateWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.UpdateWorkflowRequest" + }, + { + "name": "workflow", + "type": "google.cloud.workflows_v1.types.Workflow" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_workflow" + }, + "description": "Sample for UpdateWorkflow", + "file": "workflows_v1_generated_workflows_update_workflow_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_UpdateWorkflow_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1_generated_workflows_update_workflow_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1.WorkflowsClient.update_workflow", + "method": { + "fullName": "google.cloud.workflows.v1.Workflows.UpdateWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1.Workflows", + "shortName": "Workflows" + }, + "shortName": "UpdateWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1.types.UpdateWorkflowRequest" + }, + { + "name": "workflow", + "type": "google.cloud.workflows_v1.types.Workflow" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_workflow" + }, + "description": "Sample for UpdateWorkflow", + "file": "workflows_v1_generated_workflows_update_workflow_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1_generated_Workflows_UpdateWorkflow_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1_generated_workflows_update_workflow_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_async.py new file mode 100644 index 000000000000..70726dd616f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_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 CancelExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1_generated_Executions_CancelExecution_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1 + + +async def sample_cancel_execution(): + # Create a client + client = executions_v1.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1.CancelExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.cancel_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1_generated_Executions_CancelExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_sync.py new file mode 100644 index 000000000000..44a8e8b3265c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_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 CancelExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1_generated_Executions_CancelExecution_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1 + + +def sample_cancel_execution(): + # Create a client + client = executions_v1.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1.CancelExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.cancel_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1_generated_Executions_CancelExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_async.py new file mode 100644 index 000000000000..e95cb22413cb --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_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 CreateExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1_generated_Executions_CreateExecution_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1 + + +async def sample_create_execution(): + # Create a client + client = executions_v1.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1.CreateExecutionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1_generated_Executions_CreateExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_sync.py new file mode 100644 index 000000000000..684ddb237758 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_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 CreateExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1_generated_Executions_CreateExecution_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1 + + +def sample_create_execution(): + # Create a client + client = executions_v1.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1.CreateExecutionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1_generated_Executions_CreateExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_async.py new file mode 100644 index 000000000000..adb49fe0566e --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_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 GetExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1_generated_Executions_GetExecution_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1 + + +async def sample_get_execution(): + # Create a client + client = executions_v1.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1.GetExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1_generated_Executions_GetExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_sync.py new file mode 100644 index 000000000000..37918ba4ecad --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_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 GetExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1_generated_Executions_GetExecution_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1 + + +def sample_get_execution(): + # Create a client + client = executions_v1.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1.GetExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.get_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1_generated_Executions_GetExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_async.py new file mode 100644 index 000000000000..5bb5f579dc64 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_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 ListExecutions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1_generated_Executions_ListExecutions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1 + + +async def sample_list_executions(): + # Create a client + client = executions_v1.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1.ListExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_executions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workflowexecutions_v1_generated_Executions_ListExecutions_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_sync.py new file mode 100644 index 000000000000..aef66f516ec6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_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 ListExecutions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1_generated_Executions_ListExecutions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1 + + +def sample_list_executions(): + # Create a client + client = executions_v1.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1.ListExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_executions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workflowexecutions_v1_generated_Executions_ListExecutions_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_async.py new file mode 100644 index 000000000000..69925ef10858 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_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 CreateWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_CreateWorkflow_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +async def sample_create_workflow(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + workflow = workflows_v1.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1.CreateWorkflowRequest( + parent="parent_value", + workflow=workflow, + workflow_id="workflow_id_value", + ) + + # Make the request + operation = client.create_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workflows_v1_generated_Workflows_CreateWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_sync.py new file mode 100644 index 000000000000..0c1375b6afcb --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_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 CreateWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_CreateWorkflow_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +def sample_create_workflow(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + workflow = workflows_v1.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1.CreateWorkflowRequest( + parent="parent_value", + workflow=workflow, + workflow_id="workflow_id_value", + ) + + # Make the request + operation = client.create_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workflows_v1_generated_Workflows_CreateWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_async.py new file mode 100644 index 000000000000..dbf035cdd5ef --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_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 DeleteWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_DeleteWorkflow_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +async def sample_delete_workflow(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1.DeleteWorkflowRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workflows_v1_generated_Workflows_DeleteWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_sync.py new file mode 100644 index 000000000000..05ec4c2ee70d --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_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 DeleteWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_DeleteWorkflow_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +def sample_delete_workflow(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1.DeleteWorkflowRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workflows_v1_generated_Workflows_DeleteWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_async.py new file mode 100644 index 000000000000..27366a2d667a --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_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 GetWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_GetWorkflow_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +async def sample_get_workflow(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1.GetWorkflowRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workflow(request=request) + + # Handle the response + print(response) + +# [END workflows_v1_generated_Workflows_GetWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_sync.py new file mode 100644 index 000000000000..0b61ebe8dafe --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_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 GetWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_GetWorkflow_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +def sample_get_workflow(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1.GetWorkflowRequest( + name="name_value", + ) + + # Make the request + response = client.get_workflow(request=request) + + # Handle the response + print(response) + +# [END workflows_v1_generated_Workflows_GetWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_async.py new file mode 100644 index 000000000000..63dbaf332e23 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_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 ListWorkflows +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_ListWorkflows_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +async def sample_list_workflows(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1.ListWorkflowsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workflows(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workflows_v1_generated_Workflows_ListWorkflows_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_sync.py new file mode 100644 index 000000000000..90302cc27677 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_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 ListWorkflows +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_ListWorkflows_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +def sample_list_workflows(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1.ListWorkflowsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workflows(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workflows_v1_generated_Workflows_ListWorkflows_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_async.py new file mode 100644 index 000000000000..8710eec78578 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_UpdateWorkflow_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +async def sample_update_workflow(): + # Create a client + client = workflows_v1.WorkflowsAsyncClient() + + # Initialize request argument(s) + workflow = workflows_v1.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1.UpdateWorkflowRequest( + workflow=workflow, + ) + + # Make the request + operation = client.update_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workflows_v1_generated_Workflows_UpdateWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_sync.py new file mode 100644 index 000000000000..7c5223fc3dd5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1_generated_Workflows_UpdateWorkflow_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1 + + +def sample_update_workflow(): + # Create a client + client = workflows_v1.WorkflowsClient() + + # Initialize request argument(s) + workflow = workflows_v1.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1.UpdateWorkflowRequest( + workflow=workflow, + ) + + # Make the request + operation = client.update_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workflows_v1_generated_Workflows_UpdateWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_executions_v1_keywords.py b/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_executions_v1_keywords.py new file mode 100644 index 000000000000..5bce5db0132c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_executions_v1_keywords.py @@ -0,0 +1,179 @@ +#! /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 executionsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'cancel_execution': ('name', ), + 'create_execution': ('parent', 'execution', ), + 'get_execution': ('name', 'view', ), + 'list_executions': ('parent', 'page_size', 'page_token', 'view', 'filter', 'order_by', ), + } + + 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=executionsCallTransformer(), +): + """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 executions 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-cloud-workflows/v1/scripts/fixup_workflows_v1_keywords.py b/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_workflows_v1_keywords.py new file mode 100644 index 000000000000..3c1bc914fff8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_workflows_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 workflowsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_workflow': ('parent', 'workflow', 'workflow_id', ), + 'delete_workflow': ('name', ), + 'get_workflow': ('name', 'revision_id', ), + 'list_workflows': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'update_workflow': ('workflow', '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=workflowsCallTransformer(), +): + """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 workflows 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-cloud-workflows/v1/setup.py b/owl-bot-staging/google-cloud-workflows/v1/setup.py new file mode 100644 index 000000000000..85ca80f0b4ea --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows' + + +description = "Google Cloud Workflows API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/workflows/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-cloud-workflows" + +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-cloud-workflows/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/tests/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/tests/unit/gapic/executions_v1/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_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-cloud-workflows/v1/tests/unit/gapic/executions_v1/test_executions.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/test_executions.py new file mode 100644 index 000000000000..ee1bf4b2cc95 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/test_executions.py @@ -0,0 +1,3165 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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.cloud.workflows.executions_v1.services.executions import ExecutionsAsyncClient +from google.cloud.workflows.executions_v1.services.executions import ExecutionsClient +from google.cloud.workflows.executions_v1.services.executions import pagers +from google.cloud.workflows.executions_v1.services.executions import transports +from google.cloud.workflows.executions_v1.types import executions +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_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 ExecutionsClient._get_default_mtls_endpoint(None) is None + assert ExecutionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ExecutionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ExecutionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ExecutionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ExecutionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ExecutionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ExecutionsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ExecutionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ExecutionsClient._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 ExecutionsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ExecutionsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ExecutionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ExecutionsClient._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 ExecutionsClient._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 ExecutionsClient._get_client_cert_source(None, False) is None + assert ExecutionsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ExecutionsClient._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 ExecutionsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ExecutionsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ExecutionsClient._DEFAULT_UNIVERSE + default_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ExecutionsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ExecutionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT + assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "always") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT + assert ExecutionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT + assert ExecutionsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ExecutionsClient._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 ExecutionsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ExecutionsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ExecutionsClient._get_universe_domain(None, None) == ExecutionsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ExecutionsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ExecutionsClient, "grpc"), + (ExecutionsAsyncClient, "grpc_asyncio"), +]) +def test_executions_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 == ( + 'workflowexecutions.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ExecutionsGrpcTransport, "grpc"), + (transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_executions_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", [ + (ExecutionsClient, "grpc"), + (ExecutionsAsyncClient, "grpc_asyncio"), +]) +def test_executions_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 == ( + 'workflowexecutions.googleapis.com:443' + ) + + +def test_executions_client_get_transport_class(): + transport = ExecutionsClient.get_transport_class() + available_transports = [ + transports.ExecutionsGrpcTransport, + ] + assert transport in available_transports + + transport = ExecutionsClient.get_transport_class("grpc") + assert transport == transports.ExecutionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) +def test_executions_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(ExecutionsClient, '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(ExecutionsClient, '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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", "true"), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", "false"), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_executions_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", [ + ExecutionsClient, ExecutionsAsyncClient +]) +@mock.patch.object(ExecutionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExecutionsAsyncClient)) +def test_executions_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", [ + ExecutionsClient, ExecutionsAsyncClient +]) +@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) +def test_executions_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ExecutionsClient._DEFAULT_UNIVERSE + default_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ExecutionsClient._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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_executions_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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", grpc_helpers), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_executions_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_executions_client_client_options_from_dict(): + with mock.patch('google.cloud.workflows.executions_v1.services.executions.transports.ExecutionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ExecutionsClient( + 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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", grpc_helpers), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_executions_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( + "workflowexecutions.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="workflowexecutions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + executions.ListExecutionsRequest, + dict, +]) +def test_list_executions(request_type, transport: str = 'grpc'): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.ListExecutionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = executions.ListExecutionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExecutionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_executions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = executions.ListExecutionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_executions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == executions.ListExecutionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_executions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_executions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_executions] = mock_rpc + request = {} + client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_executions(request) + + # Establish that a new wrapper 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_executions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_executions in client._client._transport._wrapped_methods + + # 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_executions] = mock_rpc + + request = {} + await client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_executions(request) + + # Establish that a new wrapper 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_executions_async(transport: str = 'grpc_asyncio', request_type=executions.ListExecutionsRequest): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = executions.ListExecutionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExecutionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_executions_async_from_dict(): + await test_list_executions_async(request_type=dict) + +def test_list_executions_field_headers(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.ListExecutionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + call.return_value = executions.ListExecutionsResponse() + client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_executions_field_headers_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.ListExecutionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse()) + await client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_executions_flattened(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.ListExecutionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_executions( + 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_executions_flattened_error(): + client = ExecutionsClient( + credentials=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_executions( + executions.ListExecutionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_executions_flattened_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.ListExecutionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_executions( + 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_executions_flattened_error_async(): + client = ExecutionsAsyncClient( + credentials=async_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_executions( + executions.ListExecutionsRequest(), + parent='parent_value', + ) + + +def test_list_executions_pager(transport_name: str = "grpc"): + client = ExecutionsClient( + 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_executions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + executions.Execution(), + ], + next_page_token='abc', + ), + executions.ListExecutionsResponse( + executions=[], + next_page_token='def', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + ], + next_page_token='ghi', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_executions(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, executions.Execution) + for i in results) +def test_list_executions_pages(transport_name: str = "grpc"): + client = ExecutionsClient( + 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_executions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + executions.Execution(), + ], + next_page_token='abc', + ), + executions.ListExecutionsResponse( + executions=[], + next_page_token='def', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + ], + next_page_token='ghi', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + ], + ), + RuntimeError, + ) + pages = list(client.list_executions(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_executions_async_pager(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + executions.Execution(), + ], + next_page_token='abc', + ), + executions.ListExecutionsResponse( + executions=[], + next_page_token='def', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + ], + next_page_token='ghi', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_executions(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, executions.Execution) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_executions_async_pages(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + executions.Execution(), + ], + next_page_token='abc', + ), + executions.ListExecutionsResponse( + executions=[], + next_page_token='def', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + ], + next_page_token='ghi', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + ], + ), + 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_executions(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", [ + executions.CreateExecutionRequest, + dict, +]) +def test_create_execution(request_type, transport: str = 'grpc'): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, + ) + response = client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = executions.CreateExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS + + +def test_create_execution_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = executions.CreateExecutionRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_execution(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == executions.CreateExecutionRequest( + parent='parent_value', + ) + +def test_create_execution_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_execution in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_execution] = mock_rpc + request = {} + client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_execution(request) + + # Establish that a new wrapper 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_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_execution in client._client._transport._wrapped_methods + + # 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_execution] = mock_rpc + + request = {} + await client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_execution(request) + + # Establish that a new wrapper 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_execution_async(transport: str = 'grpc_asyncio', request_type=executions.CreateExecutionRequest): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, + )) + response = await client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = executions.CreateExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS + + +@pytest.mark.asyncio +async def test_create_execution_async_from_dict(): + await test_create_execution_async(request_type=dict) + +def test_create_execution_field_headers(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.CreateExecutionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_execution_field_headers_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.CreateExecutionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + await client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_execution_flattened(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_execution( + parent='parent_value', + execution=executions.Execution(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].execution + mock_val = executions.Execution(name='name_value') + assert arg == mock_val + + +def test_create_execution_flattened_error(): + client = ExecutionsClient( + credentials=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_execution( + executions.CreateExecutionRequest(), + parent='parent_value', + execution=executions.Execution(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_execution_flattened_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_execution( + parent='parent_value', + execution=executions.Execution(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].execution + mock_val = executions.Execution(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_execution_flattened_error_async(): + client = ExecutionsAsyncClient( + credentials=async_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_execution( + executions.CreateExecutionRequest(), + parent='parent_value', + execution=executions.Execution(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + executions.GetExecutionRequest, + dict, +]) +def test_get_execution(request_type, transport: str = 'grpc'): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, + ) + response = client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = executions.GetExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS + + +def test_get_execution_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = executions.GetExecutionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_execution(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == executions.GetExecutionRequest( + name='name_value', + ) + +def test_get_execution_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_execution in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_execution] = mock_rpc + request = {} + client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_execution(request) + + # Establish that a new wrapper 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_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_execution in client._client._transport._wrapped_methods + + # 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_execution] = mock_rpc + + request = {} + await client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_execution(request) + + # Establish that a new wrapper 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_execution_async(transport: str = 'grpc_asyncio', request_type=executions.GetExecutionRequest): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, + )) + response = await client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = executions.GetExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS + + +@pytest.mark.asyncio +async def test_get_execution_async_from_dict(): + await test_get_execution_async(request_type=dict) + +def test_get_execution_field_headers(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.GetExecutionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_execution_field_headers_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.GetExecutionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + await client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_execution_flattened(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_execution( + 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_execution_flattened_error(): + client = ExecutionsClient( + credentials=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_execution( + executions.GetExecutionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_execution_flattened_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_execution( + 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_execution_flattened_error_async(): + client = ExecutionsAsyncClient( + credentials=async_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_execution( + executions.GetExecutionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + executions.CancelExecutionRequest, + dict, +]) +def test_cancel_execution(request_type, transport: str = 'grpc'): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, + ) + response = client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = executions.CancelExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS + + +def test_cancel_execution_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = executions.CancelExecutionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.cancel_execution(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == executions.CancelExecutionRequest( + name='name_value', + ) + +def test_cancel_execution_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.cancel_execution in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.cancel_execution] = mock_rpc + request = {} + client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.cancel_execution(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_cancel_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.cancel_execution in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.cancel_execution] = mock_rpc + + request = {} + await client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.cancel_execution(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_cancel_execution_async(transport: str = 'grpc_asyncio', request_type=executions.CancelExecutionRequest): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, + )) + response = await client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = executions.CancelExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS + + +@pytest.mark.asyncio +async def test_cancel_execution_async_from_dict(): + await test_cancel_execution_async(request_type=dict) + +def test_cancel_execution_field_headers(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.CancelExecutionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_cancel_execution_field_headers_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.CancelExecutionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + await client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_cancel_execution_flattened(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.cancel_execution( + 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_cancel_execution_flattened_error(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.cancel_execution( + executions.CancelExecutionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_cancel_execution_flattened_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.cancel_execution( + 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_cancel_execution_flattened_error_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.cancel_execution( + executions.CancelExecutionRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExecutionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ExecutionsClient( + 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 = ExecutionsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExecutionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ExecutionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ExecutionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ExecutionsGrpcTransport, + transports.ExecutionsGrpcAsyncIOTransport, +]) +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 = ExecutionsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ExecutionsClient( + 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_executions_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + call.return_value = executions.ListExecutionsResponse() + client.list_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.ListExecutionsRequest() + + assert args[0] == request_msg + + +# This 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_execution_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.create_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.CreateExecutionRequest() + + assert args[0] == request_msg + + +# This 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_execution_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.get_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.GetExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_cancel_execution_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.cancel_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.CancelExecutionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ExecutionsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ExecutionsAsyncClient( + 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_executions_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse( + next_page_token='next_page_token_value', + )) + await client.list_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.ListExecutionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_execution_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, + )) + await client.create_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.CreateExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_execution_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, + )) + await client.get_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.GetExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_cancel_execution_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, + )) + await client.cancel_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.CancelExecutionRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ExecutionsGrpcTransport, + ) + +def test_executions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ExecutionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_executions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.workflows.executions_v1.services.executions.transports.ExecutionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ExecutionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_executions', + 'create_execution', + 'get_execution', + 'cancel_execution', + ) + 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_executions_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workflows.executions_v1.services.executions.transports.ExecutionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExecutionsTransport( + 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_executions_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workflows.executions_v1.services.executions.transports.ExecutionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExecutionsTransport() + adc.assert_called_once() + + +def test_executions_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) + ExecutionsClient() + 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.ExecutionsGrpcTransport, + transports.ExecutionsGrpcAsyncIOTransport, + ], +) +def test_executions_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.ExecutionsGrpcTransport, + transports.ExecutionsGrpcAsyncIOTransport, + ], +) +def test_executions_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.ExecutionsGrpcTransport, grpc_helpers), + (transports.ExecutionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_executions_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( + "workflowexecutions.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="workflowexecutions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) +def test_executions_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_executions_host_no_port(transport_name): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workflowexecutions.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workflowexecutions.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_executions_host_with_port(transport_name): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workflowexecutions.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workflowexecutions.googleapis.com:8000' + ) + +def test_executions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExecutionsGrpcTransport( + 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_executions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExecutionsGrpcAsyncIOTransport( + 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.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) +def test_executions_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.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) +def test_executions_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_execution_path(): + project = "squid" + location = "clam" + workflow = "whelk" + execution = "octopus" + expected = "projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}".format(project=project, location=location, workflow=workflow, execution=execution, ) + actual = ExecutionsClient.execution_path(project, location, workflow, execution) + assert expected == actual + + +def test_parse_execution_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "workflow": "cuttlefish", + "execution": "mussel", + } + path = ExecutionsClient.execution_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_execution_path(path) + assert expected == actual + +def test_workflow_path(): + project = "winkle" + location = "nautilus" + workflow = "scallop" + expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + actual = ExecutionsClient.workflow_path(project, location, workflow) + assert expected == actual + + +def test_parse_workflow_path(): + expected = { + "project": "abalone", + "location": "squid", + "workflow": "clam", + } + path = ExecutionsClient.workflow_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_workflow_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ExecutionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ExecutionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ExecutionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ExecutionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ExecutionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ExecutionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ExecutionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ExecutionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.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 = ExecutionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ExecutionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.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.ExecutionsTransport, '_prep_wrapped_messages') as prep: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ExecutionsTransport, '_prep_wrapped_messages') as prep: + transport_class = ExecutionsClient.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 = ExecutionsClient( + 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 = ExecutionsAsyncClient( + 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_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ExecutionsClient( + 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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport), +]) +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-cloud-workflows/v1/tests/unit/gapic/workflows_v1/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_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-cloud-workflows/v1/tests/unit/gapic/workflows_v1/test_workflows.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/test_workflows.py new file mode 100644 index 000000000000..ec2c9cd03db2 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/test_workflows.py @@ -0,0 +1,6232 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.location import locations_pb2 +from google.cloud.workflows_v1.services.workflows import WorkflowsAsyncClient +from google.cloud.workflows_v1.services.workflows import WorkflowsClient +from google.cloud.workflows_v1.services.workflows import pagers +from google.cloud.workflows_v1.services.workflows import transports +from google.cloud.workflows_v1.types import workflows +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +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 WorkflowsClient._get_default_mtls_endpoint(None) is None + assert WorkflowsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WorkflowsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WorkflowsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WorkflowsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WorkflowsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert WorkflowsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WorkflowsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WorkflowsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + WorkflowsClient._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 WorkflowsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WorkflowsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WorkflowsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WorkflowsClient._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 WorkflowsClient._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 WorkflowsClient._get_client_cert_source(None, False) is None + assert WorkflowsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert WorkflowsClient._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 WorkflowsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert WorkflowsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WorkflowsClient._DEFAULT_UNIVERSE + default_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert WorkflowsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert WorkflowsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT + assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "always") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT + assert WorkflowsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT + assert WorkflowsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + WorkflowsClient._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 WorkflowsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert WorkflowsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert WorkflowsClient._get_universe_domain(None, None) == WorkflowsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + WorkflowsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WorkflowsClient, "grpc"), + (WorkflowsAsyncClient, "grpc_asyncio"), + (WorkflowsClient, "rest"), +]) +def test_workflows_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 == ( + 'workflows.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workflows.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WorkflowsGrpcTransport, "grpc"), + (transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WorkflowsRestTransport, "rest"), +]) +def test_workflows_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", [ + (WorkflowsClient, "grpc"), + (WorkflowsAsyncClient, "grpc_asyncio"), + (WorkflowsClient, "rest"), +]) +def test_workflows_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 == ( + 'workflows.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workflows.googleapis.com' + ) + + +def test_workflows_client_get_transport_class(): + transport = WorkflowsClient.get_transport_class() + available_transports = [ + transports.WorkflowsGrpcTransport, + transports.WorkflowsRestTransport, + ] + assert transport in available_transports + + transport = WorkflowsClient.get_transport_class("grpc") + assert transport == transports.WorkflowsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), +]) +@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) +def test_workflows_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(WorkflowsClient, '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(WorkflowsClient, '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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", "true"), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", "false"), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest", "true"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest", "false"), +]) +@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_workflows_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", [ + WorkflowsClient, WorkflowsAsyncClient +]) +@mock.patch.object(WorkflowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkflowsAsyncClient)) +def test_workflows_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", [ + WorkflowsClient, WorkflowsAsyncClient +]) +@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) +def test_workflows_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WorkflowsClient._DEFAULT_UNIVERSE + default_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WorkflowsClient._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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), +]) +def test_workflows_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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", grpc_helpers), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest", None), +]) +def test_workflows_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_workflows_client_client_options_from_dict(): + with mock.patch('google.cloud.workflows_v1.services.workflows.transports.WorkflowsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WorkflowsClient( + 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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", grpc_helpers), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_workflows_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( + "workflows.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="workflows.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + workflows.ListWorkflowsRequest, + dict, +]) +def test_list_workflows(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.ListWorkflowsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.ListWorkflowsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkflowsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workflows_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.ListWorkflowsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workflows(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.ListWorkflowsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_workflows_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflows in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflows] = mock_rpc + request = {} + client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workflows(request) + + # Establish that a new wrapper 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_workflows_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflows in client._client._transport._wrapped_methods + + # 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_workflows] = mock_rpc + + request = {} + await client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workflows(request) + + # Establish that a new wrapper 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_workflows_async(transport: str = 'grpc_asyncio', request_type=workflows.ListWorkflowsRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.ListWorkflowsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkflowsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workflows_async_from_dict(): + await test_list_workflows_async(request_type=dict) + +def test_list_workflows_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.ListWorkflowsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + call.return_value = workflows.ListWorkflowsResponse() + client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflows_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.ListWorkflowsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse()) + await client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflows_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.ListWorkflowsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workflows( + 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_workflows_flattened_error(): + client = WorkflowsClient( + credentials=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_workflows( + workflows.ListWorkflowsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workflows_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.ListWorkflowsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workflows( + 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_workflows_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflows( + workflows.ListWorkflowsRequest(), + parent='parent_value', + ) + + +def test_list_workflows_pager(transport_name: str = "grpc"): + client = WorkflowsClient( + 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_workflows), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workflows(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, workflows.Workflow) + for i in results) +def test_list_workflows_pages(transport_name: str = "grpc"): + client = WorkflowsClient( + 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_workflows), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workflows(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_workflows_async_pager(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workflows(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, workflows.Workflow) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workflows_async_pages(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + 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_workflows(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", [ + workflows.GetWorkflowRequest, + dict, +]) +def test_get_workflow(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.Workflow( + name='name_value', + description='description_value', + state=workflows.Workflow.State.ACTIVE, + revision_id='revision_id_value', + service_account='service_account_value', + crypto_key_name='crypto_key_name_value', + call_log_level=workflows.Workflow.CallLogLevel.LOG_ALL_CALLS, + source_contents='source_contents_value', + ) + response = client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.GetWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workflows.Workflow) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == workflows.Workflow.State.ACTIVE + assert response.revision_id == 'revision_id_value' + assert response.service_account == 'service_account_value' + assert response.crypto_key_name == 'crypto_key_name_value' + assert response.call_log_level == workflows.Workflow.CallLogLevel.LOG_ALL_CALLS + + +def test_get_workflow_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.GetWorkflowRequest( + name='name_value', + revision_id='revision_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_workflow(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.GetWorkflowRequest( + name='name_value', + revision_id='revision_id_value', + ) + +def test_get_workflow_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workflow] = mock_rpc + request = {} + client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workflow(request) + + # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflow in client._client._transport._wrapped_methods + + # 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_workflow] = mock_rpc + + request = {} + await client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_workflow(request) + + # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.GetWorkflowRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow( + name='name_value', + description='description_value', + state=workflows.Workflow.State.ACTIVE, + revision_id='revision_id_value', + service_account='service_account_value', + crypto_key_name='crypto_key_name_value', + call_log_level=workflows.Workflow.CallLogLevel.LOG_ALL_CALLS, + )) + response = await client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.GetWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workflows.Workflow) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == workflows.Workflow.State.ACTIVE + assert response.revision_id == 'revision_id_value' + assert response.service_account == 'service_account_value' + assert response.crypto_key_name == 'crypto_key_name_value' + assert response.call_log_level == workflows.Workflow.CallLogLevel.LOG_ALL_CALLS + + +@pytest.mark.asyncio +async def test_get_workflow_async_from_dict(): + await test_get_workflow_async(request_type=dict) + +def test_get_workflow_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.GetWorkflowRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + call.return_value = workflows.Workflow() + client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.GetWorkflowRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow()) + await client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.Workflow() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workflow( + 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_workflow_flattened_error(): + client = WorkflowsClient( + credentials=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_workflow( + workflows.GetWorkflowRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workflow_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.Workflow() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workflow( + 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_workflow_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflow( + workflows.GetWorkflowRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workflows.CreateWorkflowRequest, + dict, +]) +def test_create_workflow(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.CreateWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workflow_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.CreateWorkflowRequest( + parent='parent_value', + workflow_id='workflow_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_workflow(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.CreateWorkflowRequest( + parent='parent_value', + workflow_id='workflow_id_value', + ) + +def test_create_workflow_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + request = {} + client.create_workflow(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.create_workflow(request) + + # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflow in client._client._transport._wrapped_methods + + # 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_workflow] = mock_rpc + + request = {} + await client.create_workflow(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.create_workflow(request) + + # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.CreateWorkflowRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__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.create_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.CreateWorkflowRequest() + 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_create_workflow_async_from_dict(): + await test_create_workflow_async(request_type=dict) + +def test_create_workflow_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.CreateWorkflowRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.CreateWorkflowRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_workflow( + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_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].workflow + mock_val = workflows.Workflow(name='name_value') + assert arg == mock_val + arg = args[0].workflow_id + mock_val = 'workflow_id_value' + assert arg == mock_val + + +def test_create_workflow_flattened_error(): + client = WorkflowsClient( + credentials=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_workflow( + workflows.CreateWorkflowRequest(), + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workflow_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_workflow( + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_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].workflow + mock_val = workflows.Workflow(name='name_value') + assert arg == mock_val + arg = args[0].workflow_id + mock_val = 'workflow_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workflow_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflow( + workflows.CreateWorkflowRequest(), + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workflows.DeleteWorkflowRequest, + dict, +]) +def test_delete_workflow(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.DeleteWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workflow_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.DeleteWorkflowRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_workflow(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.DeleteWorkflowRequest( + name='name_value', + ) + +def test_delete_workflow_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + request = {} + client.delete_workflow(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.delete_workflow(request) + + # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflow in client._client._transport._wrapped_methods + + # 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_workflow] = mock_rpc + + request = {} + await client.delete_workflow(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.delete_workflow(request) + + # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.DeleteWorkflowRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__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.delete_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.DeleteWorkflowRequest() + 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_delete_workflow_async_from_dict(): + await test_delete_workflow_async(request_type=dict) + +def test_delete_workflow_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.DeleteWorkflowRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.DeleteWorkflowRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_workflow( + 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_workflow_flattened_error(): + client = WorkflowsClient( + credentials=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_workflow( + workflows.DeleteWorkflowRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workflow_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_workflow( + 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_workflow_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflow( + workflows.DeleteWorkflowRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workflows.UpdateWorkflowRequest, + dict, +]) +def test_update_workflow(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.UpdateWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workflow_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.UpdateWorkflowRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_workflow(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.UpdateWorkflowRequest( + ) + +def test_update_workflow_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + request = {} + client.update_workflow(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.update_workflow(request) + + # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflow in client._client._transport._wrapped_methods + + # 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_workflow] = mock_rpc + + request = {} + await client.update_workflow(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.update_workflow(request) + + # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.UpdateWorkflowRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__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.update_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.UpdateWorkflowRequest() + 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_update_workflow_async_from_dict(): + await test_update_workflow_async(request_type=dict) + +def test_update_workflow_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.UpdateWorkflowRequest() + + request.workflow.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workflow.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workflow_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.UpdateWorkflowRequest() + + request.workflow.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workflow.name=name_value', + ) in kw['metadata'] + + +def test_update_workflow_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_workflow( + workflow=workflows.Workflow(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].workflow + mock_val = workflows.Workflow(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_workflow_flattened_error(): + client = WorkflowsClient( + credentials=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_workflow( + workflows.UpdateWorkflowRequest(), + workflow=workflows.Workflow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workflow_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_workflow( + workflow=workflows.Workflow(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].workflow + mock_val = workflows.Workflow(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_workflow_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflow( + workflows.UpdateWorkflowRequest(), + workflow=workflows.Workflow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_workflows_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflows in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflows] = mock_rpc + + request = {} + client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workflows(request) + + # Establish 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_workflows_rest_required_fields(request_type=workflows.ListWorkflowsRequest): + transport_class = transports.WorkflowsRestTransport + + 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_workflows._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_workflows._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "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 = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workflows.ListWorkflowsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workflows.ListWorkflowsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_workflows(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workflows_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workflows._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workflows_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workflows.ListWorkflowsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/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 = workflows.ListWorkflowsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_workflows(**mock_args) + + # Establish that the underlying call 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/*/locations/*}/workflows" % client.transport._host, args[1]) + + +def test_list_workflows_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflows( + workflows.ListWorkflowsRequest(), + parent='parent_value', + ) + + +def test_list_workflows_rest_pager(transport: str = 'rest'): + client = WorkflowsClient( + 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 = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workflows.ListWorkflowsResponse.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/locations/sample2'} + + pager = client.list_workflows(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workflows.Workflow) + for i in results) + + pages = list(client.list_workflows(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_workflow_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workflow] = mock_rpc + + request = {} + client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workflow(request) + + # Establish 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_workflow_rest_required_fields(request_type=workflows.GetWorkflowRequest): + transport_class = transports.WorkflowsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workflow._get_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_workflow._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("revision_id", )) + jsonified_request.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 = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workflows.Workflow() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workflows.Workflow.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_workflow(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workflow_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workflow._get_unset_required_fields({}) + assert set(unset_fields) == (set(("revisionId", )) & set(("name", ))) + + +def test_get_workflow_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workflows.Workflow() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workflows/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 = workflows.Workflow.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_workflow(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workflows/*}" % client.transport._host, args[1]) + + +def test_get_workflow_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflow( + workflows.GetWorkflowRequest(), + name='name_value', + ) + + +def test_create_workflow_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + + request = {} + client.create_workflow(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.create_workflow(request) + + # Establish 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_workflow_rest_required_fields(request_type=workflows.CreateWorkflowRequest): + transport_class = transports.WorkflowsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workflow_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 "workflowId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workflow._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workflowId" in jsonified_request + assert jsonified_request["workflowId"] == request_init["workflow_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workflowId"] = 'workflow_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workflow._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("workflow_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 "workflowId" in jsonified_request + assert jsonified_request["workflowId"] == 'workflow_id_value' + + client = WorkflowsClient( + 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 + + response = client.create_workflow(request) + + expected_params = [ + ( + "workflowId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workflow_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workflow._get_unset_required_fields({}) + assert set(unset_fields) == (set(("workflowId", )) & set(("parent", "workflow", "workflowId", ))) + + +def test_create_workflow_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workflow(**mock_args) + + # Establish that the underlying call 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/*/locations/*}/workflows" % client.transport._host, args[1]) + + +def test_create_workflow_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflow( + workflows.CreateWorkflowRequest(), + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_id_value', + ) + + +def test_delete_workflow_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + + request = {} + client.delete_workflow(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.delete_workflow(request) + + # Establish 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_workflow_rest_required_fields(request_type=workflows.DeleteWorkflowRequest): + transport_class = transports.WorkflowsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workflow._get_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_workflow._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkflowsClient( + 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': "delete", + '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 + + response = client.delete_workflow(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workflow_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workflow._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_workflow_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workflows/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workflow(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workflows/*}" % client.transport._host, args[1]) + + +def test_delete_workflow_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflow( + workflows.DeleteWorkflowRequest(), + name='name_value', + ) + + +def test_update_workflow_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + + request = {} + client.update_workflow(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.update_workflow(request) + + # Establish 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_workflow_rest_required_fields(request_type=workflows.UpdateWorkflowRequest): + transport_class = transports.WorkflowsRestTransport + + 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_workflow._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_workflow._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 = WorkflowsClient( + 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': "patch", + '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 + + response = client.update_workflow(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workflow_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workflow._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("workflow", ))) + + +def test_update_workflow_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + workflow=workflows.Workflow(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_workflow(**mock_args) + + # Establish that the underlying call 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/{workflow.name=projects/*/locations/*/workflows/*}" % client.transport._host, args[1]) + + +def test_update_workflow_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflow( + workflows.UpdateWorkflowRequest(), + workflow=workflows.Workflow(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.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkflowsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WorkflowsClient( + 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 = WorkflowsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkflowsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WorkflowsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WorkflowsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WorkflowsGrpcTransport, + transports.WorkflowsGrpcAsyncIOTransport, + transports.WorkflowsRestTransport, +]) +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 = WorkflowsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = WorkflowsClient( + 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_workflows_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + call.return_value = workflows.ListWorkflowsResponse() + client.list_workflows(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.ListWorkflowsRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + call.return_value = workflows.Workflow() + client.get_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.GetWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.CreateWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.DeleteWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.UpdateWorkflowRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = WorkflowsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = WorkflowsAsyncClient( + 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_workflows_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_workflows(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.ListWorkflowsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow( + name='name_value', + description='description_value', + state=workflows.Workflow.State.ACTIVE, + revision_id='revision_id_value', + service_account='service_account_value', + crypto_key_name='crypto_key_name_value', + call_log_level=workflows.Workflow.CallLogLevel.LOG_ALL_CALLS, + )) + await client.get_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.GetWorkflowRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__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.create_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.CreateWorkflowRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__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.delete_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.DeleteWorkflowRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__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.update_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.UpdateWorkflowRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = WorkflowsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_workflows_rest_bad_request(request_type=workflows.ListWorkflowsRequest): + client = WorkflowsClient( + 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 + client.list_workflows(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.ListWorkflowsRequest, + dict, +]) +def test_list_workflows_rest_call_success(request_type): + client = WorkflowsClient( + 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 = workflows.ListWorkflowsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workflows.ListWorkflowsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_workflows(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkflowsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workflows_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "post_list_workflows") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_list_workflows") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.ListWorkflowsRequest.pb(workflows.ListWorkflowsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workflows.ListWorkflowsResponse.to_json(workflows.ListWorkflowsResponse()) + req.return_value.content = return_value + + request = workflows.ListWorkflowsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workflows.ListWorkflowsResponse() + + client.list_workflows(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workflow_rest_bad_request(request_type=workflows.GetWorkflowRequest): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 + client.get_workflow(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.GetWorkflowRequest, + dict, +]) +def test_get_workflow_rest_call_success(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 = workflows.Workflow( + name='name_value', + description='description_value', + state=workflows.Workflow.State.ACTIVE, + revision_id='revision_id_value', + service_account='service_account_value', + crypto_key_name='crypto_key_name_value', + call_log_level=workflows.Workflow.CallLogLevel.LOG_ALL_CALLS, + source_contents='source_contents_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 = workflows.Workflow.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_workflow(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workflows.Workflow) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == workflows.Workflow.State.ACTIVE + assert response.revision_id == 'revision_id_value' + assert response.service_account == 'service_account_value' + assert response.crypto_key_name == 'crypto_key_name_value' + assert response.call_log_level == workflows.Workflow.CallLogLevel.LOG_ALL_CALLS + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workflow_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "post_get_workflow") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_get_workflow") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.GetWorkflowRequest.pb(workflows.GetWorkflowRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workflows.Workflow.to_json(workflows.Workflow()) + req.return_value.content = return_value + + request = workflows.GetWorkflowRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workflows.Workflow() + + client.get_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workflow_rest_bad_request(request_type=workflows.CreateWorkflowRequest): + client = WorkflowsClient( + 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 + client.create_workflow(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.CreateWorkflowRequest, + dict, +]) +def test_create_workflow_rest_call_success(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["workflow"] = {'name': 'name_value', 'description': 'description_value', 'state': 1, 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'revision_create_time': {}, 'labels': {}, 'service_account': 'service_account_value', 'source_contents': 'source_contents_value', 'crypto_key_name': 'crypto_key_name_value', 'state_error': {'details': 'details_value', 'type_': 1}, 'call_log_level': 1, 'user_env_vars': {}} + # 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 = workflows.CreateWorkflowRequest.meta.fields["workflow"] + + 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["workflow"].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["workflow"][field])): + del request_init["workflow"][field][i][subfield] + else: + del request_init["workflow"][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 = 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 + response = client.create_workflow(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_create_workflow_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_create_workflow") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_create_workflow") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.CreateWorkflowRequest.pb(workflows.CreateWorkflowRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workflows.CreateWorkflowRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workflow_rest_bad_request(request_type=workflows.DeleteWorkflowRequest): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 + client.delete_workflow(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.DeleteWorkflowRequest, + dict, +]) +def test_delete_workflow_rest_call_success(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 = 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 + response = client.delete_workflow(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_delete_workflow_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_delete_workflow") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_delete_workflow") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.DeleteWorkflowRequest.pb(workflows.DeleteWorkflowRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workflows.DeleteWorkflowRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workflow_rest_bad_request(request_type=workflows.UpdateWorkflowRequest): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/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 + client.update_workflow(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.UpdateWorkflowRequest, + dict, +]) +def test_update_workflow_rest_call_success(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/sample3'}} + request_init["workflow"] = {'name': 'projects/sample1/locations/sample2/workflows/sample3', 'description': 'description_value', 'state': 1, 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'revision_create_time': {}, 'labels': {}, 'service_account': 'service_account_value', 'source_contents': 'source_contents_value', 'crypto_key_name': 'crypto_key_name_value', 'state_error': {'details': 'details_value', 'type_': 1}, 'call_log_level': 1, 'user_env_vars': {}} + # 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 = workflows.UpdateWorkflowRequest.meta.fields["workflow"] + + 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["workflow"].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["workflow"][field])): + del request_init["workflow"][field][i][subfield] + else: + del request_init["workflow"][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 = 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 + response = client.update_workflow(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_update_workflow_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_update_workflow") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_update_workflow") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.UpdateWorkflowRequest.pb(workflows.UpdateWorkflowRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workflows.UpdateWorkflowRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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 + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': '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(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # 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 + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, 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 + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + 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 = locations_pb2.ListLocationsResponse() + + # 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 + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = WorkflowsClient( + 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 + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = WorkflowsClient( + 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 = 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 + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = WorkflowsClient( + 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 + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = WorkflowsClient( + 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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 + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': '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(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = WorkflowsClient( + 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_workflows_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + client.list_workflows(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.ListWorkflowsRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + client.get_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.GetWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + client.create_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.CreateWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + client.delete_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.DeleteWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + client.update_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.UpdateWorkflowRequest() + + assert args[0] == request_msg + + +def test_workflows_rest_lro_client(): + client = WorkflowsClient( + 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 = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WorkflowsGrpcTransport, + ) + +def test_workflows_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WorkflowsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_workflows_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.workflows_v1.services.workflows.transports.WorkflowsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WorkflowsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_workflows', + 'get_workflow', + 'create_workflow', + 'delete_workflow', + 'update_workflow', + 'get_location', + 'list_locations', + 'get_operation', + 'delete_operation', + 'list_operations', + ) + 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_workflows_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workflows_v1.services.workflows.transports.WorkflowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkflowsTransport( + 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_workflows_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workflows_v1.services.workflows.transports.WorkflowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkflowsTransport() + adc.assert_called_once() + + +def test_workflows_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) + WorkflowsClient() + 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.WorkflowsGrpcTransport, + transports.WorkflowsGrpcAsyncIOTransport, + ], +) +def test_workflows_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.WorkflowsGrpcTransport, + transports.WorkflowsGrpcAsyncIOTransport, + transports.WorkflowsRestTransport, + ], +) +def test_workflows_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.WorkflowsGrpcTransport, grpc_helpers), + (transports.WorkflowsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_workflows_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( + "workflows.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="workflows.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) +def test_workflows_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_workflows_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.WorkflowsRestTransport ( + 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_workflows_host_no_port(transport_name): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workflows.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workflows.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workflows.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_workflows_host_with_port(transport_name): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workflows.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workflows.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workflows.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_workflows_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WorkflowsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WorkflowsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_workflows._session + session2 = client2.transport.list_workflows._session + assert session1 != session2 + session1 = client1.transport.get_workflow._session + session2 = client2.transport.get_workflow._session + assert session1 != session2 + session1 = client1.transport.create_workflow._session + session2 = client2.transport.create_workflow._session + assert session1 != session2 + session1 = client1.transport.delete_workflow._session + session2 = client2.transport.delete_workflow._session + assert session1 != session2 + session1 = client1.transport.update_workflow._session + session2 = client2.transport.update_workflow._session + assert session1 != session2 +def test_workflows_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkflowsGrpcTransport( + 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_workflows_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkflowsGrpcAsyncIOTransport( + 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.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) +def test_workflows_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.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) +def test_workflows_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_workflows_grpc_lro_client(): + client = WorkflowsClient( + 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_workflows_grpc_lro_async_client(): + client = WorkflowsAsyncClient( + 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_crypto_key_path(): + project = "squid" + location = "clam" + keyRing = "whelk" + cryptoKey = "octopus" + expected = "projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}".format(project=project, location=location, keyRing=keyRing, cryptoKey=cryptoKey, ) + actual = WorkflowsClient.crypto_key_path(project, location, keyRing, cryptoKey) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "keyRing": "cuttlefish", + "cryptoKey": "mussel", + } + path = WorkflowsClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.parse_crypto_key_path(path) + assert expected == actual + +def test_workflow_path(): + project = "winkle" + location = "nautilus" + workflow = "scallop" + expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + actual = WorkflowsClient.workflow_path(project, location, workflow) + assert expected == actual + + +def test_parse_workflow_path(): + expected = { + "project": "abalone", + "location": "squid", + "workflow": "clam", + } + path = WorkflowsClient.workflow_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.parse_workflow_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WorkflowsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = WorkflowsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = WorkflowsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = WorkflowsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WorkflowsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = WorkflowsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = WorkflowsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = WorkflowsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.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 = WorkflowsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = WorkflowsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.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.WorkflowsTransport, '_prep_wrapped_messages') as prep: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WorkflowsTransport, '_prep_wrapped_messages') as prep: + transport_class = WorkflowsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_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 response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_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 response is None + +def test_delete_operation_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_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_delete_operation_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_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_delete_operation_from_dict(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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 = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = WorkflowsClient( + 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 = WorkflowsAsyncClient( + 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_list_operations(transport: str = "grpc"): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the 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.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the 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.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_list_operations_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_list_operations_from_dict(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the 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, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the 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, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_list_locations_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_list_locations_from_dict(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the 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, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the 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, locations_pb2.Location) + +def test_get_location_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = WorkflowsClient( + 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 = WorkflowsAsyncClient( + 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 = WorkflowsClient( + 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 = WorkflowsClient( + 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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport), +]) +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-cloud-workflows/v1beta/.coveragerc b/owl-bot-staging/google-cloud-workflows/v1beta/.coveragerc new file mode 100644 index 000000000000..0b3eb91ee6c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/workflows/__init__.py + google/cloud/workflows/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-cloud-workflows/v1beta/.flake8 b/owl-bot-staging/google-cloud-workflows/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-workflows/v1beta/MANIFEST.in new file mode 100644 index 000000000000..80137aea1e08 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/workflows *.py +recursive-include google/cloud/workflows_v1beta *.py diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/README.rst b/owl-bot-staging/google-cloud-workflows/v1beta/README.rst new file mode 100644 index 000000000000..9ff50ef51f9e --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Workflows 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 Cloud Workflows 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-cloud-workflows/v1beta/docs/_static/custom.css b/owl-bot-staging/google-cloud-workflows/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-workflows/v1beta/docs/conf.py new file mode 100644 index 000000000000..aa65085dd2d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows 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-cloud-workflows" +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 Cloud 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-cloud-workflows-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-cloud-workflows.tex", + u"google-cloud-workflows 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-cloud-workflows", + u"Google Cloud Workflows 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-cloud-workflows", + u"google-cloud-workflows Documentation", + author, + "google-cloud-workflows", + "GAPIC library for Google Cloud Workflows 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-cloud-workflows/v1beta/docs/executions_v1beta/executions.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/executions.rst new file mode 100644 index 000000000000..8e18a7f058e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/executions.rst @@ -0,0 +1,10 @@ +Executions +---------------------------- + +.. automodule:: google.cloud.workflows.executions_v1beta.services.executions + :members: + :inherited-members: + +.. automodule:: google.cloud.workflows.executions_v1beta.services.executions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/services_.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/services_.rst new file mode 100644 index 000000000000..f6ae17ade08b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Workflows Executions v1beta API +========================================================= +.. toctree:: + :maxdepth: 2 + + executions diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/types_.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/types_.rst new file mode 100644 index 000000000000..6c92f22e378d --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Workflows Executions v1beta API +====================================================== + +.. automodule:: google.cloud.workflows.executions_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/index.rst new file mode 100644 index 000000000000..ed454475774f --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + workflows_v1beta/services_ + workflows_v1beta/types_ diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/services_.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/services_.rst new file mode 100644 index 000000000000..ad4e93dde768 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Workflows v1beta API +============================================== +.. toctree:: + :maxdepth: 2 + + workflows diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/types_.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/types_.rst new file mode 100644 index 000000000000..0b7a8571584f --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Workflows v1beta API +=========================================== + +.. automodule:: google.cloud.workflows_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/workflows.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/workflows.rst new file mode 100644 index 000000000000..ac0a1b0d1b8f --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/workflows.rst @@ -0,0 +1,10 @@ +Workflows +--------------------------- + +.. automodule:: google.cloud.workflows_v1beta.services.workflows + :members: + :inherited-members: + +.. automodule:: google.cloud.workflows_v1beta.services.workflows.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/__init__.py new file mode 100644 index 000000000000..f90c411948b7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/__init__.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.workflows_v1beta.services.workflows.client import WorkflowsClient +from google.cloud.workflows_v1beta.services.workflows.async_client import WorkflowsAsyncClient + +from google.cloud.workflows_v1beta.types.workflows import CreateWorkflowRequest +from google.cloud.workflows_v1beta.types.workflows import DeleteWorkflowRequest +from google.cloud.workflows_v1beta.types.workflows import GetWorkflowRequest +from google.cloud.workflows_v1beta.types.workflows import ListWorkflowsRequest +from google.cloud.workflows_v1beta.types.workflows import ListWorkflowsResponse +from google.cloud.workflows_v1beta.types.workflows import OperationMetadata +from google.cloud.workflows_v1beta.types.workflows import UpdateWorkflowRequest +from google.cloud.workflows_v1beta.types.workflows import Workflow + +__all__ = ('WorkflowsClient', + 'WorkflowsAsyncClient', + 'CreateWorkflowRequest', + 'DeleteWorkflowRequest', + 'GetWorkflowRequest', + 'ListWorkflowsRequest', + 'ListWorkflowsResponse', + 'OperationMetadata', + 'UpdateWorkflowRequest', + 'Workflow', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/__init__.py new file mode 100644 index 000000000000..8475b13abaf8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows.executions import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.workflows.executions_v1beta.services.executions.client import ExecutionsClient +from google.cloud.workflows.executions_v1beta.services.executions.async_client import ExecutionsAsyncClient + +from google.cloud.workflows.executions_v1beta.types.executions import CancelExecutionRequest +from google.cloud.workflows.executions_v1beta.types.executions import CreateExecutionRequest +from google.cloud.workflows.executions_v1beta.types.executions import Execution +from google.cloud.workflows.executions_v1beta.types.executions import GetExecutionRequest +from google.cloud.workflows.executions_v1beta.types.executions import ListExecutionsRequest +from google.cloud.workflows.executions_v1beta.types.executions import ListExecutionsResponse +from google.cloud.workflows.executions_v1beta.types.executions import ExecutionView + +__all__ = ('ExecutionsClient', + 'ExecutionsAsyncClient', + 'CancelExecutionRequest', + 'CreateExecutionRequest', + 'Execution', + 'GetExecutionRequest', + 'ListExecutionsRequest', + 'ListExecutionsResponse', + 'ExecutionView', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/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-cloud-workflows/v1beta/google/cloud/workflows/executions/py.typed b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/py.typed new file mode 100644 index 000000000000..ff4d7c1ed09d --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workflows-executions package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/__init__.py new file mode 100644 index 000000000000..8077643c3e6c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/__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 google.cloud.workflows.executions_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.executions import ExecutionsClient +from .services.executions import ExecutionsAsyncClient + +from .types.executions import CancelExecutionRequest +from .types.executions import CreateExecutionRequest +from .types.executions import Execution +from .types.executions import GetExecutionRequest +from .types.executions import ListExecutionsRequest +from .types.executions import ListExecutionsResponse +from .types.executions import ExecutionView + +__all__ = ( + 'ExecutionsAsyncClient', +'CancelExecutionRequest', +'CreateExecutionRequest', +'Execution', +'ExecutionView', +'ExecutionsClient', +'GetExecutionRequest', +'ListExecutionsRequest', +'ListExecutionsResponse', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..dec2db0f9bb3 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_metadata.json @@ -0,0 +1,63 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.workflows.executions_v1beta", + "protoPackage": "google.cloud.workflows.executions.v1beta", + "schema": "1.0", + "services": { + "Executions": { + "clients": { + "grpc": { + "libraryClient": "ExecutionsClient", + "rpcs": { + "CancelExecution": { + "methods": [ + "cancel_execution" + ] + }, + "CreateExecution": { + "methods": [ + "create_execution" + ] + }, + "GetExecution": { + "methods": [ + "get_execution" + ] + }, + "ListExecutions": { + "methods": [ + "list_executions" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ExecutionsAsyncClient", + "rpcs": { + "CancelExecution": { + "methods": [ + "cancel_execution" + ] + }, + "CreateExecution": { + "methods": [ + "create_execution" + ] + }, + "GetExecution": { + "methods": [ + "get_execution" + ] + }, + "ListExecutions": { + "methods": [ + "list_executions" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_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-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/py.typed b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/py.typed new file mode 100644 index 000000000000..ff4d7c1ed09d --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workflows-executions package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_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-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/__init__.py new file mode 100644 index 000000000000..9295dd9a3cb5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/__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 ExecutionsClient +from .async_client import ExecutionsAsyncClient + +__all__ = ( + 'ExecutionsClient', + 'ExecutionsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/async_client.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/async_client.py new file mode 100644 index 000000000000..752b78064e72 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/async_client.py @@ -0,0 +1,699 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.workflows.executions_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.cloud.workflows.executions_v1beta.services.executions import pagers +from google.cloud.workflows.executions_v1beta.types import executions +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExecutionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ExecutionsGrpcAsyncIOTransport +from .client import ExecutionsClient + + +class ExecutionsAsyncClient: + """Executions is used to start and manage running instances of + [Workflows][google.cloud.workflows.v1beta.Workflow] called + executions. + """ + + _client: ExecutionsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ExecutionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ExecutionsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ExecutionsClient._DEFAULT_UNIVERSE + + execution_path = staticmethod(ExecutionsClient.execution_path) + parse_execution_path = staticmethod(ExecutionsClient.parse_execution_path) + workflow_path = staticmethod(ExecutionsClient.workflow_path) + parse_workflow_path = staticmethod(ExecutionsClient.parse_workflow_path) + common_billing_account_path = staticmethod(ExecutionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ExecutionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ExecutionsClient.common_folder_path) + parse_common_folder_path = staticmethod(ExecutionsClient.parse_common_folder_path) + common_organization_path = staticmethod(ExecutionsClient.common_organization_path) + parse_common_organization_path = staticmethod(ExecutionsClient.parse_common_organization_path) + common_project_path = staticmethod(ExecutionsClient.common_project_path) + parse_common_project_path = staticmethod(ExecutionsClient.parse_common_project_path) + common_location_path = staticmethod(ExecutionsClient.common_location_path) + parse_common_location_path = staticmethod(ExecutionsClient.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: + ExecutionsAsyncClient: The constructed client. + """ + return ExecutionsClient.from_service_account_info.__func__(ExecutionsAsyncClient, 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: + ExecutionsAsyncClient: The constructed client. + """ + return ExecutionsClient.from_service_account_file.__func__(ExecutionsAsyncClient, 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 ExecutionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ExecutionsTransport: + """Returns the transport used by the client instance. + + Returns: + ExecutionsTransport: 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 = ExecutionsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ExecutionsTransport, Callable[..., ExecutionsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the executions 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,ExecutionsTransport,Callable[..., ExecutionsTransport]]]): + 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 ExecutionsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ExecutionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_executions(self, + request: Optional[Union[executions.ListExecutionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExecutionsAsyncPager: + r"""Returns a list of executions which belong to the + workflow with the given name. The method returns + executions of all workflow revisions. Returned + executions are ordered by their start time (newest + first). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1beta + + async def sample_list_executions(): + # Create a client + client = executions_v1beta.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1beta.ListExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_executions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest, dict]]): + The request object. Request for the + [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] + method. + parent (:class:`str`): + Required. Name of the workflow for + which the executions should be listed. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1beta.services.executions.pagers.ListExecutionsAsyncPager: + Response for the + [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] + 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, executions.ListExecutionsRequest): + request = executions.ListExecutionsRequest(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_executions] + + # Certain fields should be provided within 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.ListExecutionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_execution(self, + request: Optional[Union[executions.CreateExecutionRequest, dict]] = None, + *, + parent: Optional[str] = None, + execution: Optional[executions.Execution] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Creates a new execution using the latest revision of + the given workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1beta + + async def sample_create_execution(): + # Create a client + client = executions_v1beta.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1beta.CreateExecutionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows.executions_v1beta.types.CreateExecutionRequest, dict]]): + The request object. Request for the + [CreateExecution][google.cloud.workflows.executions.v1beta.Executions.CreateExecution] + method. + parent (:class:`str`): + Required. Name of the workflow for + which an execution should be created. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + The latest revision of the workflow will + be used. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + execution (:class:`google.cloud.workflows.executions_v1beta.types.Execution`): + Required. Execution to be created. + This corresponds to the ``execution`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_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. + + Returns: + google.cloud.workflows.executions_v1beta.types.Execution: + A running instance of a + [Workflow][google.cloud.workflows.v1beta.Workflow]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, execution]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, executions.CreateExecutionRequest): + request = executions.CreateExecutionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if execution is not None: + request.execution = execution + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_execution] + + # Certain fields should be provided within 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_execution(self, + request: Optional[Union[executions.GetExecutionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Returns an execution of the given name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1beta + + async def sample_get_execution(): + # Create a client + client = executions_v1beta.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1beta.GetExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows.executions_v1beta.types.GetExecutionRequest, dict]]): + The request object. Request for the + [GetExecution][google.cloud.workflows.executions.v1beta.Executions.GetExecution] + method. + name (:class:`str`): + Required. Name of the execution to be + retrieved. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1beta.types.Execution: + A running instance of a + [Workflow][google.cloud.workflows.v1beta.Workflow]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, executions.GetExecutionRequest): + request = executions.GetExecutionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_execution] + + # Certain fields should be provided within 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 cancel_execution(self, + request: Optional[Union[executions.CancelExecutionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Cancels an execution of the given name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1beta + + async def sample_cancel_execution(): + # Create a client + client = executions_v1beta.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1beta.CancelExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.cancel_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows.executions_v1beta.types.CancelExecutionRequest, dict]]): + The request object. Request for the + [CancelExecution][google.cloud.workflows.executions.v1beta.Executions.CancelExecution] + method. + name (:class:`str`): + Required. Name of the execution to be + cancelled. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1beta.types.Execution: + A running instance of a + [Workflow][google.cloud.workflows.v1beta.Workflow]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, executions.CancelExecutionRequest): + request = executions.CancelExecutionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.cancel_execution] + + # Certain fields should be provided within 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) -> "ExecutionsAsyncClient": + 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__ = ( + "ExecutionsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/client.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/client.py new file mode 100644 index 000000000000..bf859f10dbb9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/client.py @@ -0,0 +1,1059 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.workflows.executions_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 + +from google.cloud.workflows.executions_v1beta.services.executions import pagers +from google.cloud.workflows.executions_v1beta.types import executions +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExecutionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ExecutionsGrpcTransport +from .transports.grpc_asyncio import ExecutionsGrpcAsyncIOTransport + + +class ExecutionsClientMeta(type): + """Metaclass for the Executions 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[ExecutionsTransport]] + _transport_registry["grpc"] = ExecutionsGrpcTransport + _transport_registry["grpc_asyncio"] = ExecutionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ExecutionsTransport]: + """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 ExecutionsClient(metaclass=ExecutionsClientMeta): + """Executions is used to start and manage running instances of + [Workflows][google.cloud.workflows.v1beta.Workflow] called + executions. + """ + + @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 = "workflowexecutions.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "workflowexecutions.{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: + ExecutionsClient: 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: + ExecutionsClient: 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) -> ExecutionsTransport: + """Returns the transport used by the client instance. + + Returns: + ExecutionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def execution_path(project: str,location: str,workflow: str,execution: str,) -> str: + """Returns a fully-qualified execution string.""" + return "projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}".format(project=project, location=location, workflow=workflow, execution=execution, ) + + @staticmethod + def parse_execution_path(path: str) -> Dict[str,str]: + """Parses a execution path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)/executions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workflow_path(project: str,location: str,workflow: str,) -> str: + """Returns a fully-qualified workflow string.""" + return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + + @staticmethod + def parse_workflow_path(path: str) -> Dict[str,str]: + """Parses a workflow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = ExecutionsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ExecutionsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ExecutionsClient._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 = ExecutionsClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ExecutionsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ExecutionsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, ExecutionsTransport, Callable[..., ExecutionsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the executions client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ExecutionsTransport,Callable[..., ExecutionsTransport]]]): + 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 ExecutionsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ExecutionsClient._read_environment_variables() + self._client_cert_source = ExecutionsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ExecutionsClient._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 + + 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, ExecutionsTransport) + if transport_provided: + # transport is a ExecutionsTransport 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(ExecutionsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ExecutionsClient._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[ExecutionsTransport], Callable[..., ExecutionsTransport]] = ( + ExecutionsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ExecutionsTransport], 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, + ) + + def list_executions(self, + request: Optional[Union[executions.ListExecutionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExecutionsPager: + r"""Returns a list of executions which belong to the + workflow with the given name. The method returns + executions of all workflow revisions. Returned + executions are ordered by their start time (newest + first). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1beta + + def sample_list_executions(): + # Create a client + client = executions_v1beta.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1beta.ListExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_executions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest, dict]): + The request object. Request for the + [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] + method. + parent (str): + Required. Name of the workflow for + which the executions should be listed. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1beta.services.executions.pagers.ListExecutionsPager: + Response for the + [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] + 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, executions.ListExecutionsRequest): + request = executions.ListExecutionsRequest(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_executions] + + # Certain fields should be provided within 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.ListExecutionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_execution(self, + request: Optional[Union[executions.CreateExecutionRequest, dict]] = None, + *, + parent: Optional[str] = None, + execution: Optional[executions.Execution] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Creates a new execution using the latest revision of + the given workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1beta + + def sample_create_execution(): + # Create a client + client = executions_v1beta.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1beta.CreateExecutionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows.executions_v1beta.types.CreateExecutionRequest, dict]): + The request object. Request for the + [CreateExecution][google.cloud.workflows.executions.v1beta.Executions.CreateExecution] + method. + parent (str): + Required. Name of the workflow for + which an execution should be created. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + The latest revision of the workflow will + be used. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + execution (google.cloud.workflows.executions_v1beta.types.Execution): + Required. Execution to be created. + This corresponds to the ``execution`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.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. + + Returns: + google.cloud.workflows.executions_v1beta.types.Execution: + A running instance of a + [Workflow][google.cloud.workflows.v1beta.Workflow]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, execution]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, executions.CreateExecutionRequest): + request = executions.CreateExecutionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if execution is not None: + request.execution = execution + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_execution] + + # Certain fields should be provided within 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_execution(self, + request: Optional[Union[executions.GetExecutionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Returns an execution of the given name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1beta + + def sample_get_execution(): + # Create a client + client = executions_v1beta.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1beta.GetExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.get_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows.executions_v1beta.types.GetExecutionRequest, dict]): + The request object. Request for the + [GetExecution][google.cloud.workflows.executions.v1beta.Executions.GetExecution] + method. + name (str): + Required. Name of the execution to be + retrieved. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1beta.types.Execution: + A running instance of a + [Workflow][google.cloud.workflows.v1beta.Workflow]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, executions.GetExecutionRequest): + request = executions.GetExecutionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_execution] + + # Certain fields should be provided within 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 cancel_execution(self, + request: Optional[Union[executions.CancelExecutionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> executions.Execution: + r"""Cancels an execution of the given name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.workflows import executions_v1beta + + def sample_cancel_execution(): + # Create a client + client = executions_v1beta.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1beta.CancelExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.cancel_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows.executions_v1beta.types.CancelExecutionRequest, dict]): + The request object. Request for the + [CancelExecution][google.cloud.workflows.executions.v1beta.Executions.CancelExecution] + method. + name (str): + Required. Name of the execution to be + cancelled. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows.executions_v1beta.types.Execution: + A running instance of a + [Workflow][google.cloud.workflows.v1beta.Workflow]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, executions.CancelExecutionRequest): + request = executions.CancelExecutionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.cancel_execution] + + # Certain fields should be provided within 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) -> "ExecutionsClient": + 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__ = ( + "ExecutionsClient", +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/pagers.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/pagers.py new file mode 100644 index 000000000000..e9a2ed7aba20 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows.executions_v1beta.types import executions + + +class ListExecutionsPager: + """A pager for iterating through ``list_executions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``executions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExecutions`` requests and continue to iterate + through the ``executions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., executions.ListExecutionsResponse], + request: executions.ListExecutionsRequest, + response: executions.ListExecutionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest): + The initial request object. + response (google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = executions.ListExecutionsRequest(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[executions.ListExecutionsResponse]: + 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[executions.Execution]: + for page in self.pages: + yield from page.executions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListExecutionsAsyncPager: + """A pager for iterating through ``list_executions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``executions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExecutions`` requests and continue to iterate + through the ``executions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse` + attributes are available on the 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[executions.ListExecutionsResponse]], + request: executions.ListExecutionsRequest, + response: executions.ListExecutionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest): + The initial request object. + response (google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = executions.ListExecutionsRequest(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[executions.ListExecutionsResponse]: + 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[executions.Execution]: + async def async_generator(): + async for page in self.pages: + for response in page.executions: + 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-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/README.rst b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/README.rst new file mode 100644 index 000000000000..6555db202c9c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ExecutionsTransport` is the ABC for all transports. +- public child `ExecutionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ExecutionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseExecutionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ExecutionsRestTransport` 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-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/__init__.py new file mode 100644 index 000000000000..fbf990808f62 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 ExecutionsTransport +from .grpc import ExecutionsGrpcTransport +from .grpc_asyncio import ExecutionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ExecutionsTransport]] +_transport_registry['grpc'] = ExecutionsGrpcTransport +_transport_registry['grpc_asyncio'] = ExecutionsGrpcAsyncIOTransport + +__all__ = ( + 'ExecutionsTransport', + 'ExecutionsGrpcTransport', + 'ExecutionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/base.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/base.py new file mode 100644 index 000000000000..13fb59eb4d07 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/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.cloud.workflows.executions_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.cloud.workflows.executions_v1beta.types import executions + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ExecutionsTransport(abc.ABC): + """Abstract transport class for Executions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_executions: gapic_v1.method.wrap_method( + self.list_executions, + default_timeout=None, + client_info=client_info, + ), + self.create_execution: gapic_v1.method.wrap_method( + self.create_execution, + default_timeout=None, + client_info=client_info, + ), + self.get_execution: gapic_v1.method.wrap_method( + self.get_execution, + default_timeout=None, + client_info=client_info, + ), + self.cancel_execution: gapic_v1.method.wrap_method( + self.cancel_execution, + 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_executions(self) -> Callable[ + [executions.ListExecutionsRequest], + Union[ + executions.ListExecutionsResponse, + Awaitable[executions.ListExecutionsResponse] + ]]: + raise NotImplementedError() + + @property + def create_execution(self) -> Callable[ + [executions.CreateExecutionRequest], + Union[ + executions.Execution, + Awaitable[executions.Execution] + ]]: + raise NotImplementedError() + + @property + def get_execution(self) -> Callable[ + [executions.GetExecutionRequest], + Union[ + executions.Execution, + Awaitable[executions.Execution] + ]]: + raise NotImplementedError() + + @property + def cancel_execution(self) -> Callable[ + [executions.CancelExecutionRequest], + Union[ + executions.Execution, + Awaitable[executions.Execution] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ExecutionsTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc.py new file mode 100644 index 000000000000..6229e44d3912 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc.py @@ -0,0 +1,355 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.cloud.workflows.executions_v1beta.types import executions +from .base import ExecutionsTransport, DEFAULT_CLIENT_INFO + + +class ExecutionsGrpcTransport(ExecutionsTransport): + """gRPC backend transport for Executions. + + Executions is used to start and manage running instances of + [Workflows][google.cloud.workflows.v1beta.Workflow] called + executions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'workflowexecutions.googleapis.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_executions(self) -> Callable[ + [executions.ListExecutionsRequest], + executions.ListExecutionsResponse]: + r"""Return a callable for the list executions method over gRPC. + + Returns a list of executions which belong to the + workflow with the given name. The method returns + executions of all workflow revisions. Returned + executions are ordered by their start time (newest + first). + + Returns: + Callable[[~.ListExecutionsRequest], + ~.ListExecutionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_executions' not in self._stubs: + self._stubs['list_executions'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1beta.Executions/ListExecutions', + request_serializer=executions.ListExecutionsRequest.serialize, + response_deserializer=executions.ListExecutionsResponse.deserialize, + ) + return self._stubs['list_executions'] + + @property + def create_execution(self) -> Callable[ + [executions.CreateExecutionRequest], + executions.Execution]: + r"""Return a callable for the create execution method over gRPC. + + Creates a new execution using the latest revision of + the given workflow. + + Returns: + Callable[[~.CreateExecutionRequest], + ~.Execution]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_execution' not in self._stubs: + self._stubs['create_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1beta.Executions/CreateExecution', + request_serializer=executions.CreateExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['create_execution'] + + @property + def get_execution(self) -> Callable[ + [executions.GetExecutionRequest], + executions.Execution]: + r"""Return a callable for the get execution method over gRPC. + + Returns an execution of the given name. + + Returns: + Callable[[~.GetExecutionRequest], + ~.Execution]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_execution' not in self._stubs: + self._stubs['get_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1beta.Executions/GetExecution', + request_serializer=executions.GetExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['get_execution'] + + @property + def cancel_execution(self) -> Callable[ + [executions.CancelExecutionRequest], + executions.Execution]: + r"""Return a callable for the cancel execution method over gRPC. + + Cancels an execution of the given name. + + Returns: + Callable[[~.CancelExecutionRequest], + ~.Execution]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'cancel_execution' not in self._stubs: + self._stubs['cancel_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1beta.Executions/CancelExecution', + request_serializer=executions.CancelExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['cancel_execution'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ExecutionsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc_asyncio.py new file mode 100644 index 000000000000..be8c4683b8e8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc_asyncio.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 inspect +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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.workflows.executions_v1beta.types import executions +from .base import ExecutionsTransport, DEFAULT_CLIENT_INFO +from .grpc import ExecutionsGrpcTransport + + +class ExecutionsGrpcAsyncIOTransport(ExecutionsTransport): + """gRPC AsyncIO backend transport for Executions. + + Executions is used to start and manage running instances of + [Workflows][google.cloud.workflows.v1beta.Workflow] called + executions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workflowexecutions.googleapis.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 = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_executions(self) -> Callable[ + [executions.ListExecutionsRequest], + Awaitable[executions.ListExecutionsResponse]]: + r"""Return a callable for the list executions method over gRPC. + + Returns a list of executions which belong to the + workflow with the given name. The method returns + executions of all workflow revisions. Returned + executions are ordered by their start time (newest + first). + + Returns: + Callable[[~.ListExecutionsRequest], + Awaitable[~.ListExecutionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_executions' not in self._stubs: + self._stubs['list_executions'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1beta.Executions/ListExecutions', + request_serializer=executions.ListExecutionsRequest.serialize, + response_deserializer=executions.ListExecutionsResponse.deserialize, + ) + return self._stubs['list_executions'] + + @property + def create_execution(self) -> Callable[ + [executions.CreateExecutionRequest], + Awaitable[executions.Execution]]: + r"""Return a callable for the create execution method over gRPC. + + Creates a new execution using the latest revision of + the given workflow. + + Returns: + Callable[[~.CreateExecutionRequest], + Awaitable[~.Execution]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_execution' not in self._stubs: + self._stubs['create_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1beta.Executions/CreateExecution', + request_serializer=executions.CreateExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['create_execution'] + + @property + def get_execution(self) -> Callable[ + [executions.GetExecutionRequest], + Awaitable[executions.Execution]]: + r"""Return a callable for the get execution method over gRPC. + + Returns an execution of the given name. + + Returns: + Callable[[~.GetExecutionRequest], + Awaitable[~.Execution]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_execution' not in self._stubs: + self._stubs['get_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1beta.Executions/GetExecution', + request_serializer=executions.GetExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['get_execution'] + + @property + def cancel_execution(self) -> Callable[ + [executions.CancelExecutionRequest], + Awaitable[executions.Execution]]: + r"""Return a callable for the cancel execution method over gRPC. + + Cancels an execution of the given name. + + Returns: + Callable[[~.CancelExecutionRequest], + Awaitable[~.Execution]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'cancel_execution' not in self._stubs: + self._stubs['cancel_execution'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.executions.v1beta.Executions/CancelExecution', + request_serializer=executions.CancelExecutionRequest.serialize, + response_deserializer=executions.Execution.deserialize, + ) + return self._stubs['cancel_execution'] + + 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_executions: self._wrap_method( + self.list_executions, + default_timeout=None, + client_info=client_info, + ), + self.create_execution: self._wrap_method( + self.create_execution, + default_timeout=None, + client_info=client_info, + ), + self.get_execution: self._wrap_method( + self.get_execution, + default_timeout=None, + client_info=client_info, + ), + self.cancel_execution: self._wrap_method( + self.cancel_execution, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'ExecutionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/__init__.py new file mode 100644 index 000000000000..52fb1dab35df --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/__init__.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .executions import ( + CancelExecutionRequest, + CreateExecutionRequest, + Execution, + GetExecutionRequest, + ListExecutionsRequest, + ListExecutionsResponse, + ExecutionView, +) + +__all__ = ( + 'CancelExecutionRequest', + 'CreateExecutionRequest', + 'Execution', + 'GetExecutionRequest', + 'ListExecutionsRequest', + 'ListExecutionsResponse', + 'ExecutionView', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/executions.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/executions.py new file mode 100644 index 000000000000..d9cfd2e6eb71 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/executions.py @@ -0,0 +1,324 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.workflows.executions.v1beta', + manifest={ + 'ExecutionView', + 'Execution', + 'ListExecutionsRequest', + 'ListExecutionsResponse', + 'CreateExecutionRequest', + 'GetExecutionRequest', + 'CancelExecutionRequest', + }, +) + + +class ExecutionView(proto.Enum): + r"""Defines possible views for execution resource. + + Values: + EXECUTION_VIEW_UNSPECIFIED (0): + The default / unset value. + BASIC (1): + Includes only basic metadata about the execution. Following + fields are returned: name, start_time, end_time, state and + workflow_revision_id. + FULL (2): + Includes all data. + """ + EXECUTION_VIEW_UNSPECIFIED = 0 + BASIC = 1 + FULL = 2 + + +class Execution(proto.Message): + r"""A running instance of a + [Workflow][google.cloud.workflows.v1beta.Workflow]. + + Attributes: + name (str): + Output only. The resource name of the + execution. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Marks the beginning of + execution. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Marks the end of execution, + successful or not. + state (google.cloud.workflows.executions_v1beta.types.Execution.State): + Output only. Current state of the execution. + argument (str): + Input parameters of the execution represented + as a JSON string. The size limit is 32KB. + result (str): + Output only. Output of the execution represented as a JSON + string. The value can only be present if the execution's + state is ``SUCCEEDED``. + error (google.cloud.workflows.executions_v1beta.types.Execution.Error): + Output only. The error which caused the execution to finish + prematurely. The value is only present if the execution's + state is ``FAILED`` or ``CANCELLED``. + workflow_revision_id (str): + Output only. Revision of the workflow this + execution is using. + """ + class State(proto.Enum): + r"""Describes the current state of the execution. More states may + be added in the future. + + Values: + STATE_UNSPECIFIED (0): + Invalid state. + ACTIVE (1): + The execution is in progress. + SUCCEEDED (2): + The execution finished successfully. + FAILED (3): + The execution failed with an error. + CANCELLED (4): + The execution was stopped intentionally. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLED = 4 + + class Error(proto.Message): + r"""Error describes why the execution was abnormally terminated. + + Attributes: + payload (str): + Error payload returned by the execution, + represented as a JSON string. + context (str): + Human readable error context, helpful for + debugging purposes. + """ + + payload: str = proto.Field( + proto.STRING, + number=1, + ) + context: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + argument: str = proto.Field( + proto.STRING, + number=5, + ) + result: str = proto.Field( + proto.STRING, + number=6, + ) + error: Error = proto.Field( + proto.MESSAGE, + number=7, + message=Error, + ) + workflow_revision_id: str = proto.Field( + proto.STRING, + number=8, + ) + + +class ListExecutionsRequest(proto.Message): + r"""Request for the + [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] + method. + + Attributes: + parent (str): + Required. Name of the workflow for which the + executions should be listed. Format: + projects/{project}/locations/{location}/workflows/{workflow} + page_size (int): + Maximum number of executions to return per + call. Max supported value depends on the + selected Execution view: it's 10000 for BASIC + and 100 for FULL. The default value used if the + field is not specified is 100, regardless of the + selected view. Values greater than the max value + will be coerced down to it. + page_token (str): + A page token, received from a previous ``ListExecutions`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListExecutions`` must match the call that provided the + page token. + view (google.cloud.workflows.executions_v1beta.types.ExecutionView): + Optional. A view defining which fields should + be filled in the returned executions. The API + will default to the BASIC view. + """ + + 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, + ) + view: 'ExecutionView' = proto.Field( + proto.ENUM, + number=4, + enum='ExecutionView', + ) + + +class ListExecutionsResponse(proto.Message): + r"""Response for the + [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] + method. + + Attributes: + executions (MutableSequence[google.cloud.workflows.executions_v1beta.types.Execution]): + The executions which match the request. + 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 + + executions: MutableSequence['Execution'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Execution', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateExecutionRequest(proto.Message): + r"""Request for the + [CreateExecution][google.cloud.workflows.executions.v1beta.Executions.CreateExecution] + method. + + Attributes: + parent (str): + Required. Name of the workflow for which an + execution should be created. Format: + projects/{project}/locations/{location}/workflows/{workflow} + The latest revision of the workflow will be + used. + execution (google.cloud.workflows.executions_v1beta.types.Execution): + Required. Execution to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + execution: 'Execution' = proto.Field( + proto.MESSAGE, + number=2, + message='Execution', + ) + + +class GetExecutionRequest(proto.Message): + r"""Request for the + [GetExecution][google.cloud.workflows.executions.v1beta.Executions.GetExecution] + method. + + Attributes: + name (str): + Required. Name of the execution to be + retrieved. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + view (google.cloud.workflows.executions_v1beta.types.ExecutionView): + Optional. A view defining which fields should + be filled in the returned execution. The API + will default to the FULL view. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: 'ExecutionView' = proto.Field( + proto.ENUM, + number=2, + enum='ExecutionView', + ) + + +class CancelExecutionRequest(proto.Message): + r"""Request for the + [CancelExecution][google.cloud.workflows.executions.v1beta.Executions.CancelExecution] + method. + + Attributes: + name (str): + Required. Name of the execution to be + cancelled. Format: + + projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/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-cloud-workflows/v1beta/google/cloud/workflows/py.typed b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/py.typed new file mode 100644 index 000000000000..b753e6a6bf5b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workflows package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/__init__.py new file mode 100644 index 000000000000..50073afcf641 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/__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 google.cloud.workflows_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.workflows import WorkflowsClient +from .services.workflows import WorkflowsAsyncClient + +from .types.workflows import CreateWorkflowRequest +from .types.workflows import DeleteWorkflowRequest +from .types.workflows import GetWorkflowRequest +from .types.workflows import ListWorkflowsRequest +from .types.workflows import ListWorkflowsResponse +from .types.workflows import OperationMetadata +from .types.workflows import UpdateWorkflowRequest +from .types.workflows import Workflow + +__all__ = ( + 'WorkflowsAsyncClient', +'CreateWorkflowRequest', +'DeleteWorkflowRequest', +'GetWorkflowRequest', +'ListWorkflowsRequest', +'ListWorkflowsResponse', +'OperationMetadata', +'UpdateWorkflowRequest', +'Workflow', +'WorkflowsClient', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..28846823fc96 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_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.cloud.workflows_v1beta", + "protoPackage": "google.cloud.workflows.v1beta", + "schema": "1.0", + "services": { + "Workflows": { + "clients": { + "grpc": { + "libraryClient": "WorkflowsClient", + "rpcs": { + "CreateWorkflow": { + "methods": [ + "create_workflow" + ] + }, + "DeleteWorkflow": { + "methods": [ + "delete_workflow" + ] + }, + "GetWorkflow": { + "methods": [ + "get_workflow" + ] + }, + "ListWorkflows": { + "methods": [ + "list_workflows" + ] + }, + "UpdateWorkflow": { + "methods": [ + "update_workflow" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WorkflowsAsyncClient", + "rpcs": { + "CreateWorkflow": { + "methods": [ + "create_workflow" + ] + }, + "DeleteWorkflow": { + "methods": [ + "delete_workflow" + ] + }, + "GetWorkflow": { + "methods": [ + "get_workflow" + ] + }, + "ListWorkflows": { + "methods": [ + "list_workflows" + ] + }, + "UpdateWorkflow": { + "methods": [ + "update_workflow" + ] + } + } + }, + "rest": { + "libraryClient": "WorkflowsClient", + "rpcs": { + "CreateWorkflow": { + "methods": [ + "create_workflow" + ] + }, + "DeleteWorkflow": { + "methods": [ + "delete_workflow" + ] + }, + "GetWorkflow": { + "methods": [ + "get_workflow" + ] + }, + "ListWorkflows": { + "methods": [ + "list_workflows" + ] + }, + "UpdateWorkflow": { + "methods": [ + "update_workflow" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_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-cloud-workflows/v1beta/google/cloud/workflows_v1beta/py.typed b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/py.typed new file mode 100644 index 000000000000..b753e6a6bf5b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workflows package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_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-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/__init__.py new file mode 100644 index 000000000000..5c7fa07ed889 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/__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 WorkflowsClient +from .async_client import WorkflowsAsyncClient + +__all__ = ( + 'WorkflowsClient', + 'WorkflowsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/async_client.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/async_client.py new file mode 100644 index 000000000000..fcec767a099e --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/async_client.py @@ -0,0 +1,894 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.workflows_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.workflows_v1beta.services.workflows import pagers +from google.cloud.workflows_v1beta.types import workflows +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WorkflowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WorkflowsGrpcAsyncIOTransport +from .client import WorkflowsClient + + +class WorkflowsAsyncClient: + """Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + """ + + _client: WorkflowsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WorkflowsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WorkflowsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WorkflowsClient._DEFAULT_UNIVERSE + + workflow_path = staticmethod(WorkflowsClient.workflow_path) + parse_workflow_path = staticmethod(WorkflowsClient.parse_workflow_path) + common_billing_account_path = staticmethod(WorkflowsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WorkflowsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WorkflowsClient.common_folder_path) + parse_common_folder_path = staticmethod(WorkflowsClient.parse_common_folder_path) + common_organization_path = staticmethod(WorkflowsClient.common_organization_path) + parse_common_organization_path = staticmethod(WorkflowsClient.parse_common_organization_path) + common_project_path = staticmethod(WorkflowsClient.common_project_path) + parse_common_project_path = staticmethod(WorkflowsClient.parse_common_project_path) + common_location_path = staticmethod(WorkflowsClient.common_location_path) + parse_common_location_path = staticmethod(WorkflowsClient.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: + WorkflowsAsyncClient: The constructed client. + """ + return WorkflowsClient.from_service_account_info.__func__(WorkflowsAsyncClient, 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: + WorkflowsAsyncClient: The constructed client. + """ + return WorkflowsClient.from_service_account_file.__func__(WorkflowsAsyncClient, 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 WorkflowsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WorkflowsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkflowsTransport: 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 = WorkflowsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WorkflowsTransport, Callable[..., WorkflowsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workflows 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,WorkflowsTransport,Callable[..., WorkflowsTransport]]]): + 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 WorkflowsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WorkflowsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_workflows(self, + request: Optional[Union[workflows.ListWorkflowsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkflowsAsyncPager: + r"""Lists Workflows in a given project and location. + The default order is not specified. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1beta + + async def sample_list_workflows(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1beta.ListWorkflowsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workflows(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1beta.types.ListWorkflowsRequest, dict]]): + The request object. Request for the + [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] + method. + parent (:class:`str`): + Required. Project and location from + which the workflows should be listed. + Format: + projects/{project}/locations/{location} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows_v1beta.services.workflows.pagers.ListWorkflowsAsyncPager: + Response for the + [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] + 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, workflows.ListWorkflowsRequest): + request = workflows.ListWorkflowsRequest(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_workflows] + + # Certain fields should be provided within 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.ListWorkflowsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_workflow(self, + request: Optional[Union[workflows.GetWorkflowRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workflows.Workflow: + r"""Gets details of a single Workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1beta + + async def sample_get_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1beta.GetWorkflowRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workflow(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1beta.types.GetWorkflowRequest, dict]]): + The request object. Request for the + [GetWorkflow][google.cloud.workflows.v1beta.Workflows.GetWorkflow] + method. + name (:class:`str`): + Required. Name of the workflow which + information should be retrieved. Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows_v1beta.types.Workflow: + Workflow program to be executed by + Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflows.GetWorkflowRequest): + request = workflows.GetWorkflowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workflow] + + # Certain fields should be provided within 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_workflow(self, + request: Optional[Union[workflows.CreateWorkflowRequest, dict]] = None, + *, + parent: Optional[str] = None, + workflow: Optional[workflows.Workflow] = None, + workflow_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workflow. If a workflow with the specified name + already exists in the specified project and location, the long + running operation will return + [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] 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.cloud import workflows_v1beta + + async def sample_create_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + workflow = workflows_v1beta.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1beta.CreateWorkflowRequest( + parent="parent_value", + workflow=workflow, + workflow_id="workflow_id_value", + ) + + # Make the request + operation = client.create_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1beta.types.CreateWorkflowRequest, dict]]): + The request object. Request for the + [CreateWorkflow][google.cloud.workflows.v1beta.Workflows.CreateWorkflow] + method. + parent (:class:`str`): + Required. Project and location in + which the workflow should be created. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workflow (:class:`google.cloud.workflows_v1beta.types.Workflow`): + Required. Workflow to be created. + This corresponds to the ``workflow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workflow_id (:class:`str`): + Required. The ID of the workflow to be created. It has + to fulfill the following requirements: + + - Must contain only letters, numbers, underscores and + hyphens. + - Must start with a letter. + - Must be between 1-64 characters. + - Must end with a number or a letter. + - Must be unique within the customer project and + location. + + This corresponds to the ``workflow_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workflows_v1beta.types.Workflow` + Workflow program to be executed by Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflow, workflow_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, workflows.CreateWorkflowRequest): + request = workflows.CreateWorkflowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workflow is not None: + request.workflow = workflow + if workflow_id is not None: + request.workflow_id = workflow_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_workflow] + + # Certain fields should be provided within 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, + workflows.Workflow, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workflow(self, + request: Optional[Union[workflows.DeleteWorkflowRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a workflow with the specified name. + This method also cancels and deletes all running + executions of the workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1beta + + async def sample_delete_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1beta.DeleteWorkflowRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1beta.types.DeleteWorkflowRequest, dict]]): + The request object. Request for the + [DeleteWorkflow][google.cloud.workflows.v1beta.Workflows.DeleteWorkflow] + method. + name (:class:`str`): + Required. Name of the workflow to be + deleted. Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflows.DeleteWorkflowRequest): + request = workflows.DeleteWorkflowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workflow] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workflow(self, + request: Optional[Union[workflows.UpdateWorkflowRequest, dict]] = None, + *, + workflow: Optional[workflows.Workflow] = 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, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an existing workflow. + Running this method has no impact on already running + executions of the workflow. A new revision of the + workflow may be created as a result of a successful + update operation. In that case, such revision will be + used in new workflow executions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1beta + + async def sample_update_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + workflow = workflows_v1beta.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1beta.UpdateWorkflowRequest( + workflow=workflow, + ) + + # Make the request + operation = client.update_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workflows_v1beta.types.UpdateWorkflowRequest, dict]]): + The request object. Request for the + [UpdateWorkflow][google.cloud.workflows.v1beta.Workflows.UpdateWorkflow] + method. + workflow (:class:`google.cloud.workflows_v1beta.types.Workflow`): + Required. Workflow to be updated. + This corresponds to the ``workflow`` 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 to be updated. If not + present, the entire workflow will 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workflows_v1beta.types.Workflow` + Workflow program to be executed by Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workflow, 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, workflows.UpdateWorkflowRequest): + request = workflows.UpdateWorkflowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workflow is not None: + request.workflow = workflow + 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_workflow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workflow.name", request.workflow.name), + )), + ) + + # 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, + workflows.Workflow, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "WorkflowsAsyncClient": + 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__ = ( + "WorkflowsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/client.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/client.py new file mode 100644 index 000000000000..382b4d0beb69 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/client.py @@ -0,0 +1,1246 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.workflows_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 + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.workflows_v1beta.services.workflows import pagers +from google.cloud.workflows_v1beta.types import workflows +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WorkflowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WorkflowsGrpcTransport +from .transports.grpc_asyncio import WorkflowsGrpcAsyncIOTransport +from .transports.rest import WorkflowsRestTransport + + +class WorkflowsClientMeta(type): + """Metaclass for the Workflows 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[WorkflowsTransport]] + _transport_registry["grpc"] = WorkflowsGrpcTransport + _transport_registry["grpc_asyncio"] = WorkflowsGrpcAsyncIOTransport + _transport_registry["rest"] = WorkflowsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WorkflowsTransport]: + """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 WorkflowsClient(metaclass=WorkflowsClientMeta): + """Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + """ + + @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 = "workflows.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "workflows.{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: + WorkflowsClient: 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: + WorkflowsClient: 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) -> WorkflowsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkflowsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def workflow_path(project: str,location: str,workflow: str,) -> str: + """Returns a fully-qualified workflow string.""" + return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + + @staticmethod + def parse_workflow_path(path: str) -> Dict[str,str]: + """Parses a workflow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = WorkflowsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = WorkflowsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WorkflowsClient._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 = WorkflowsClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = WorkflowsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + WorkflowsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, WorkflowsTransport, Callable[..., WorkflowsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workflows client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,WorkflowsTransport,Callable[..., WorkflowsTransport]]]): + 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 WorkflowsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WorkflowsClient._read_environment_variables() + self._client_cert_source = WorkflowsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = WorkflowsClient._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 + + 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, WorkflowsTransport) + if transport_provided: + # transport is a WorkflowsTransport 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(WorkflowsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + WorkflowsClient._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[WorkflowsTransport], Callable[..., WorkflowsTransport]] = ( + WorkflowsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WorkflowsTransport], 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, + ) + + def list_workflows(self, + request: Optional[Union[workflows.ListWorkflowsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkflowsPager: + r"""Lists Workflows in a given project and location. + The default order is not specified. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1beta + + def sample_list_workflows(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1beta.ListWorkflowsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workflows(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workflows_v1beta.types.ListWorkflowsRequest, dict]): + The request object. Request for the + [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] + method. + parent (str): + Required. Project and location from + which the workflows should be listed. + Format: + projects/{project}/locations/{location} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows_v1beta.services.workflows.pagers.ListWorkflowsPager: + Response for the + [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] + 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, workflows.ListWorkflowsRequest): + request = workflows.ListWorkflowsRequest(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_workflows] + + # Certain fields should be provided within 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.ListWorkflowsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_workflow(self, + request: Optional[Union[workflows.GetWorkflowRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workflows.Workflow: + r"""Gets details of a single Workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1beta + + def sample_get_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1beta.GetWorkflowRequest( + name="name_value", + ) + + # Make the request + response = client.get_workflow(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows_v1beta.types.GetWorkflowRequest, dict]): + The request object. Request for the + [GetWorkflow][google.cloud.workflows.v1beta.Workflows.GetWorkflow] + method. + name (str): + Required. Name of the workflow which + information should be retrieved. Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workflows_v1beta.types.Workflow: + Workflow program to be executed by + Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflows.GetWorkflowRequest): + request = workflows.GetWorkflowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workflow] + + # Certain fields should be provided within 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_workflow(self, + request: Optional[Union[workflows.CreateWorkflowRequest, dict]] = None, + *, + parent: Optional[str] = None, + workflow: Optional[workflows.Workflow] = None, + workflow_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workflow. If a workflow with the specified name + already exists in the specified project and location, the long + running operation will return + [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] 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.cloud import workflows_v1beta + + def sample_create_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + workflow = workflows_v1beta.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1beta.CreateWorkflowRequest( + parent="parent_value", + workflow=workflow, + workflow_id="workflow_id_value", + ) + + # Make the request + operation = client.create_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows_v1beta.types.CreateWorkflowRequest, dict]): + The request object. Request for the + [CreateWorkflow][google.cloud.workflows.v1beta.Workflows.CreateWorkflow] + method. + parent (str): + Required. Project and location in + which the workflow should be created. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workflow (google.cloud.workflows_v1beta.types.Workflow): + Required. Workflow to be created. + This corresponds to the ``workflow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workflow_id (str): + Required. The ID of the workflow to be created. It has + to fulfill the following requirements: + + - Must contain only letters, numbers, underscores and + hyphens. + - Must start with a letter. + - Must be between 1-64 characters. + - Must end with a number or a letter. + - Must be unique within the customer project and + location. + + This corresponds to the ``workflow_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workflows_v1beta.types.Workflow` + Workflow program to be executed by Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflow, workflow_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, workflows.CreateWorkflowRequest): + request = workflows.CreateWorkflowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workflow is not None: + request.workflow = workflow + if workflow_id is not None: + request.workflow_id = workflow_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workflow] + + # Certain fields should be provided within 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, + workflows.Workflow, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workflow(self, + request: Optional[Union[workflows.DeleteWorkflowRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a workflow with the specified name. + This method also cancels and deletes all running + executions of the workflow. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1beta + + def sample_delete_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1beta.DeleteWorkflowRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows_v1beta.types.DeleteWorkflowRequest, dict]): + The request object. Request for the + [DeleteWorkflow][google.cloud.workflows.v1beta.Workflows.DeleteWorkflow] + method. + name (str): + Required. Name of the workflow to be + deleted. Format: + projects/{project}/locations/{location}/workflows/{workflow} + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workflows.DeleteWorkflowRequest): + request = workflows.DeleteWorkflowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workflow] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workflow(self, + request: Optional[Union[workflows.UpdateWorkflowRequest, dict]] = None, + *, + workflow: Optional[workflows.Workflow] = 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, str]] = (), + ) -> operation.Operation: + r"""Updates an existing workflow. + Running this method has no impact on already running + executions of the workflow. A new revision of the + workflow may be created as a result of a successful + update operation. In that case, such revision will be + used in new workflow executions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workflows_v1beta + + def sample_update_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + workflow = workflows_v1beta.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1beta.UpdateWorkflowRequest( + workflow=workflow, + ) + + # Make the request + operation = client.update_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workflows_v1beta.types.UpdateWorkflowRequest, dict]): + The request object. Request for the + [UpdateWorkflow][google.cloud.workflows.v1beta.Workflows.UpdateWorkflow] + method. + workflow (google.cloud.workflows_v1beta.types.Workflow): + Required. Workflow to be updated. + This corresponds to the ``workflow`` 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 to be updated. If not + present, the entire workflow will 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workflows_v1beta.types.Workflow` + Workflow program to be executed by Workflows. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workflow, 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, workflows.UpdateWorkflowRequest): + request = workflows.UpdateWorkflowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workflow is not None: + request.workflow = workflow + 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_workflow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workflow.name", request.workflow.name), + )), + ) + + # 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, + workflows.Workflow, + metadata_type=workflows.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "WorkflowsClient": + 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__ = ( + "WorkflowsClient", +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/pagers.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/pagers.py new file mode 100644 index 000000000000..7b99f09196f5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows_v1beta.types import workflows + + +class ListWorkflowsPager: + """A pager for iterating through ``list_workflows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workflows_v1beta.types.ListWorkflowsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workflows`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkflows`` requests and continue to iterate + through the ``workflows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workflows_v1beta.types.ListWorkflowsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workflows.ListWorkflowsResponse], + request: workflows.ListWorkflowsRequest, + response: workflows.ListWorkflowsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workflows_v1beta.types.ListWorkflowsRequest): + The initial request object. + response (google.cloud.workflows_v1beta.types.ListWorkflowsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workflows.ListWorkflowsRequest(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[workflows.ListWorkflowsResponse]: + 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[workflows.Workflow]: + for page in self.pages: + yield from page.workflows + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkflowsAsyncPager: + """A pager for iterating through ``list_workflows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workflows_v1beta.types.ListWorkflowsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workflows`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkflows`` requests and continue to iterate + through the ``workflows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workflows_v1beta.types.ListWorkflowsResponse` + attributes are available on the 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[workflows.ListWorkflowsResponse]], + request: workflows.ListWorkflowsRequest, + response: workflows.ListWorkflowsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workflows_v1beta.types.ListWorkflowsRequest): + The initial request object. + response (google.cloud.workflows_v1beta.types.ListWorkflowsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workflows.ListWorkflowsRequest(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[workflows.ListWorkflowsResponse]: + 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[workflows.Workflow]: + async def async_generator(): + async for page in self.pages: + for response in page.workflows: + 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-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/README.rst b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/README.rst new file mode 100644 index 000000000000..f8fb5a859227 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`WorkflowsTransport` is the ABC for all transports. +- public child `WorkflowsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `WorkflowsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseWorkflowsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `WorkflowsRestTransport` 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-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/__init__.py new file mode 100644 index 000000000000..6ebe8b349db7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/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 WorkflowsTransport +from .grpc import WorkflowsGrpcTransport +from .grpc_asyncio import WorkflowsGrpcAsyncIOTransport +from .rest import WorkflowsRestTransport +from .rest import WorkflowsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WorkflowsTransport]] +_transport_registry['grpc'] = WorkflowsGrpcTransport +_transport_registry['grpc_asyncio'] = WorkflowsGrpcAsyncIOTransport +_transport_registry['rest'] = WorkflowsRestTransport + +__all__ = ( + 'WorkflowsTransport', + 'WorkflowsGrpcTransport', + 'WorkflowsGrpcAsyncIOTransport', + 'WorkflowsRestTransport', + 'WorkflowsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/base.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/base.py new file mode 100644 index 000000000000..a19a3ab2bc92 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/base.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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.workflows_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.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.cloud.workflows_v1beta.types import workflows +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WorkflowsTransport(abc.ABC): + """Abstract transport class for Workflows.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'workflows.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: 'workflows.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_workflows: gapic_v1.method.wrap_method( + self.list_workflows, + default_timeout=None, + client_info=client_info, + ), + self.get_workflow: gapic_v1.method.wrap_method( + self.get_workflow, + default_timeout=None, + client_info=client_info, + ), + self.create_workflow: gapic_v1.method.wrap_method( + self.create_workflow, + default_timeout=None, + client_info=client_info, + ), + self.delete_workflow: gapic_v1.method.wrap_method( + self.delete_workflow, + default_timeout=None, + client_info=client_info, + ), + self.update_workflow: gapic_v1.method.wrap_method( + self.update_workflow, + 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 list_workflows(self) -> Callable[ + [workflows.ListWorkflowsRequest], + Union[ + workflows.ListWorkflowsResponse, + Awaitable[workflows.ListWorkflowsResponse] + ]]: + raise NotImplementedError() + + @property + def get_workflow(self) -> Callable[ + [workflows.GetWorkflowRequest], + Union[ + workflows.Workflow, + Awaitable[workflows.Workflow] + ]]: + raise NotImplementedError() + + @property + def create_workflow(self) -> Callable[ + [workflows.CreateWorkflowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workflow(self) -> Callable[ + [workflows.DeleteWorkflowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workflow(self) -> Callable[ + [workflows.UpdateWorkflowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WorkflowsTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc.py new file mode 100644 index 000000000000..8603c89a0fe7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc.py @@ -0,0 +1,406 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.cloud.workflows_v1beta.types import workflows +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO + + +class WorkflowsGrpcTransport(WorkflowsTransport): + """gRPC backend transport for Workflows. + + Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workflows.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: 'workflows.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'workflows.googleapis.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.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_workflows(self) -> Callable[ + [workflows.ListWorkflowsRequest], + workflows.ListWorkflowsResponse]: + r"""Return a callable for the list workflows method over gRPC. + + Lists Workflows in a given project and location. + The default order is not specified. + + Returns: + Callable[[~.ListWorkflowsRequest], + ~.ListWorkflowsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workflows' not in self._stubs: + self._stubs['list_workflows'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/ListWorkflows', + request_serializer=workflows.ListWorkflowsRequest.serialize, + response_deserializer=workflows.ListWorkflowsResponse.deserialize, + ) + return self._stubs['list_workflows'] + + @property + def get_workflow(self) -> Callable[ + [workflows.GetWorkflowRequest], + workflows.Workflow]: + r"""Return a callable for the get workflow method over gRPC. + + Gets details of a single Workflow. + + Returns: + Callable[[~.GetWorkflowRequest], + ~.Workflow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workflow' not in self._stubs: + self._stubs['get_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/GetWorkflow', + request_serializer=workflows.GetWorkflowRequest.serialize, + response_deserializer=workflows.Workflow.deserialize, + ) + return self._stubs['get_workflow'] + + @property + def create_workflow(self) -> Callable[ + [workflows.CreateWorkflowRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workflow method over gRPC. + + Creates a new workflow. If a workflow with the specified name + already exists in the specified project and location, the long + running operation will return + [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error. + + Returns: + Callable[[~.CreateWorkflowRequest], + ~.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 'create_workflow' not in self._stubs: + self._stubs['create_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/CreateWorkflow', + request_serializer=workflows.CreateWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workflow'] + + @property + def delete_workflow(self) -> Callable[ + [workflows.DeleteWorkflowRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workflow method over gRPC. + + Deletes a workflow with the specified name. + This method also cancels and deletes all running + executions of the workflow. + + Returns: + Callable[[~.DeleteWorkflowRequest], + ~.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 'delete_workflow' not in self._stubs: + self._stubs['delete_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/DeleteWorkflow', + request_serializer=workflows.DeleteWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workflow'] + + @property + def update_workflow(self) -> Callable[ + [workflows.UpdateWorkflowRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workflow method over gRPC. + + Updates an existing workflow. + Running this method has no impact on already running + executions of the workflow. A new revision of the + workflow may be created as a result of a successful + update operation. In that case, such revision will be + used in new workflow executions. + + Returns: + Callable[[~.UpdateWorkflowRequest], + ~.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 'update_workflow' not in self._stubs: + self._stubs['update_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/UpdateWorkflow', + request_serializer=workflows.UpdateWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workflow'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WorkflowsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ce0f29c4c03b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc_asyncio.py @@ -0,0 +1,447 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.workflows_v1beta.types import workflows +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO +from .grpc import WorkflowsGrpcTransport + + +class WorkflowsGrpcAsyncIOTransport(WorkflowsTransport): + """gRPC AsyncIO backend transport for Workflows. + + Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workflows.googleapis.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 = 'workflows.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: 'workflows.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_workflows(self) -> Callable[ + [workflows.ListWorkflowsRequest], + Awaitable[workflows.ListWorkflowsResponse]]: + r"""Return a callable for the list workflows method over gRPC. + + Lists Workflows in a given project and location. + The default order is not specified. + + Returns: + Callable[[~.ListWorkflowsRequest], + Awaitable[~.ListWorkflowsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workflows' not in self._stubs: + self._stubs['list_workflows'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/ListWorkflows', + request_serializer=workflows.ListWorkflowsRequest.serialize, + response_deserializer=workflows.ListWorkflowsResponse.deserialize, + ) + return self._stubs['list_workflows'] + + @property + def get_workflow(self) -> Callable[ + [workflows.GetWorkflowRequest], + Awaitable[workflows.Workflow]]: + r"""Return a callable for the get workflow method over gRPC. + + Gets details of a single Workflow. + + Returns: + Callable[[~.GetWorkflowRequest], + Awaitable[~.Workflow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workflow' not in self._stubs: + self._stubs['get_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/GetWorkflow', + request_serializer=workflows.GetWorkflowRequest.serialize, + response_deserializer=workflows.Workflow.deserialize, + ) + return self._stubs['get_workflow'] + + @property + def create_workflow(self) -> Callable[ + [workflows.CreateWorkflowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workflow method over gRPC. + + Creates a new workflow. If a workflow with the specified name + already exists in the specified project and location, the long + running operation will return + [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error. + + Returns: + Callable[[~.CreateWorkflowRequest], + 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 'create_workflow' not in self._stubs: + self._stubs['create_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/CreateWorkflow', + request_serializer=workflows.CreateWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workflow'] + + @property + def delete_workflow(self) -> Callable[ + [workflows.DeleteWorkflowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workflow method over gRPC. + + Deletes a workflow with the specified name. + This method also cancels and deletes all running + executions of the workflow. + + Returns: + Callable[[~.DeleteWorkflowRequest], + 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 'delete_workflow' not in self._stubs: + self._stubs['delete_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/DeleteWorkflow', + request_serializer=workflows.DeleteWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workflow'] + + @property + def update_workflow(self) -> Callable[ + [workflows.UpdateWorkflowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workflow method over gRPC. + + Updates an existing workflow. + Running this method has no impact on already running + executions of the workflow. A new revision of the + workflow may be created as a result of a successful + update operation. In that case, such revision will be + used in new workflow executions. + + Returns: + Callable[[~.UpdateWorkflowRequest], + 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 'update_workflow' not in self._stubs: + self._stubs['update_workflow'] = self.grpc_channel.unary_unary( + '/google.cloud.workflows.v1beta.Workflows/UpdateWorkflow', + request_serializer=workflows.UpdateWorkflowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workflow'] + + 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_workflows: self._wrap_method( + self.list_workflows, + default_timeout=None, + client_info=client_info, + ), + self.get_workflow: self._wrap_method( + self.get_workflow, + default_timeout=None, + client_info=client_info, + ), + self.create_workflow: self._wrap_method( + self.create_workflow, + default_timeout=None, + client_info=client_info, + ), + self.delete_workflow: self._wrap_method( + self.delete_workflow, + default_timeout=None, + client_info=client_info, + ), + self.update_workflow: self._wrap_method( + self.update_workflow, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'WorkflowsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest.py new file mode 100644 index 000000000000..cd5fb32c8e3c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest.py @@ -0,0 +1,760 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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.cloud.workflows_v1beta.types import workflows +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseWorkflowsRestTransport +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 + + +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 WorkflowsRestInterceptor: + """Interceptor for Workflows. + + 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 WorkflowsRestTransport. + + .. code-block:: python + class MyCustomWorkflowsInterceptor(WorkflowsRestInterceptor): + def pre_create_workflow(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workflow(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workflow(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workflow(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workflow(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workflow(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workflows(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workflows(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workflow(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workflow(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WorkflowsRestTransport(interceptor=MyCustomWorkflowsInterceptor()) + client = WorkflowsClient(transport=transport) + + + """ + def pre_create_workflow(self, request: workflows.CreateWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.CreateWorkflowRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workflow + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_create_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workflow + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_delete_workflow(self, request: workflows.DeleteWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.DeleteWorkflowRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workflow + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_delete_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workflow + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_get_workflow(self, request: workflows.GetWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.GetWorkflowRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workflow + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_get_workflow(self, response: workflows.Workflow) -> workflows.Workflow: + """Post-rpc interceptor for get_workflow + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_list_workflows(self, request: workflows.ListWorkflowsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.ListWorkflowsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workflows + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_list_workflows(self, response: workflows.ListWorkflowsResponse) -> workflows.ListWorkflowsResponse: + """Post-rpc interceptor for list_workflows + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + def pre_update_workflow(self, request: workflows.UpdateWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.UpdateWorkflowRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workflow + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workflows server. + """ + return request, metadata + + def post_update_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workflow + + Override in a subclass to manipulate the response + after it is returned by the Workflows server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WorkflowsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WorkflowsRestInterceptor + + +class WorkflowsRestTransport(_BaseWorkflowsRestTransport): + """REST backend synchronous transport for Workflows. + + Workflows is used to deploy and execute workflow programs. + Workflows makes sure the program executes reliably, despite + hardware and networking interruptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'workflows.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[WorkflowsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'workflows.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 WorkflowsRestInterceptor() + 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.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta/{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="v1beta") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateWorkflow(_BaseWorkflowsRestTransport._BaseCreateWorkflow, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.CreateWorkflow") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workflows.CreateWorkflowRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workflow method over HTTP. + + Args: + request (~.workflows.CreateWorkflowRequest): + The request object. Request for the + [CreateWorkflow][google.cloud.workflows.v1beta.Workflows.CreateWorkflow] + method. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_http_options() + request, metadata = self._interceptor.pre_create_workflow(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_transcoded_request(http_options, request) + + body = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._CreateWorkflow._get_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_create_workflow(resp) + return resp + + class _DeleteWorkflow(_BaseWorkflowsRestTransport._BaseDeleteWorkflow, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.DeleteWorkflow") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workflows.DeleteWorkflowRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workflow method over HTTP. + + Args: + request (~.workflows.DeleteWorkflowRequest): + The request object. Request for the + [DeleteWorkflow][google.cloud.workflows.v1beta.Workflows.DeleteWorkflow] + method. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_http_options() + request, metadata = self._interceptor.pre_delete_workflow(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._DeleteWorkflow._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, 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_delete_workflow(resp) + return resp + + class _GetWorkflow(_BaseWorkflowsRestTransport._BaseGetWorkflow, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.GetWorkflow") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workflows.GetWorkflowRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workflows.Workflow: + r"""Call the get workflow method over HTTP. + + Args: + request (~.workflows.GetWorkflowRequest): + The request object. Request for the + [GetWorkflow][google.cloud.workflows.v1beta.Workflows.GetWorkflow] + method. + retry (google.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. + + Returns: + ~.workflows.Workflow: + Workflow program to be executed by + Workflows. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_http_options() + request, metadata = self._interceptor.pre_get_workflow(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._GetWorkflow._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workflows.Workflow() + pb_resp = workflows.Workflow.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workflow(resp) + return resp + + class _ListWorkflows(_BaseWorkflowsRestTransport._BaseListWorkflows, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.ListWorkflows") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workflows.ListWorkflowsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workflows.ListWorkflowsResponse: + r"""Call the list workflows method over HTTP. + + Args: + request (~.workflows.ListWorkflowsRequest): + The request object. Request for the + [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] + method. + retry (google.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. + + Returns: + ~.workflows.ListWorkflowsResponse: + Response for the + [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] + method. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseListWorkflows._get_http_options() + request, metadata = self._interceptor.pre_list_workflows(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseListWorkflows._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseListWorkflows._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._ListWorkflows._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workflows.ListWorkflowsResponse() + pb_resp = workflows.ListWorkflowsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workflows(resp) + return resp + + class _UpdateWorkflow(_BaseWorkflowsRestTransport._BaseUpdateWorkflow, WorkflowsRestStub): + def __hash__(self): + return hash("WorkflowsRestTransport.UpdateWorkflow") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workflows.UpdateWorkflowRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workflow method over HTTP. + + Args: + request (~.workflows.UpdateWorkflowRequest): + The request object. Request for the + [UpdateWorkflow][google.cloud.workflows.v1beta.Workflows.UpdateWorkflow] + method. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_http_options() + request, metadata = self._interceptor.pre_update_workflow(request, metadata) + transcoded_request = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_transcoded_request(http_options, request) + + body = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_query_params_json(transcoded_request) + + # Send the request + response = WorkflowsRestTransport._UpdateWorkflow._get_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_update_workflow(resp) + return resp + + @property + def create_workflow(self) -> Callable[ + [workflows.CreateWorkflowRequest], + 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._CreateWorkflow(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workflow(self) -> Callable[ + [workflows.DeleteWorkflowRequest], + 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._DeleteWorkflow(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workflow(self) -> Callable[ + [workflows.GetWorkflowRequest], + workflows.Workflow]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkflow(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workflows(self) -> Callable[ + [workflows.ListWorkflowsRequest], + workflows.ListWorkflowsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkflows(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workflow(self) -> Callable[ + [workflows.UpdateWorkflowRequest], + 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._UpdateWorkflow(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WorkflowsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest_base.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest_base.py new file mode 100644 index 000000000000..d8f04cdadc72 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/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 WorkflowsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.workflows_v1beta.types import workflows +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseWorkflowsRestTransport(WorkflowsTransport): + """Base REST backend transport for Workflows. + + 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 = 'workflows.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: 'workflows.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 _BaseCreateWorkflow: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workflowId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{parent=projects/*/locations/*}/workflows', + 'body': 'workflow', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.CreateWorkflowRequest.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(_BaseWorkflowsRestTransport._BaseCreateWorkflow._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteWorkflow: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workflows/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.DeleteWorkflowRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetWorkflow: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/workflows/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.GetWorkflowRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkflowsRestTransport._BaseGetWorkflow._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkflows: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*}/workflows', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.ListWorkflowsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkflowsRestTransport._BaseListWorkflows._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateWorkflow: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{workflow.name=projects/*/locations/*/workflows/*}', + 'body': 'workflow', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workflows.UpdateWorkflowRequest.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(_BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseWorkflowsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/__init__.py new file mode 100644 index 000000000000..99bb09e40279 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/__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 .workflows import ( + CreateWorkflowRequest, + DeleteWorkflowRequest, + GetWorkflowRequest, + ListWorkflowsRequest, + ListWorkflowsResponse, + OperationMetadata, + UpdateWorkflowRequest, + Workflow, +) + +__all__ = ( + 'CreateWorkflowRequest', + 'DeleteWorkflowRequest', + 'GetWorkflowRequest', + 'ListWorkflowsRequest', + 'ListWorkflowsResponse', + 'OperationMetadata', + 'UpdateWorkflowRequest', + 'Workflow', +) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/workflows.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/workflows.py new file mode 100644 index 000000000000..484981fdb84c --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/workflows.py @@ -0,0 +1,403 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.workflows.v1beta', + manifest={ + 'Workflow', + 'ListWorkflowsRequest', + 'ListWorkflowsResponse', + 'GetWorkflowRequest', + 'CreateWorkflowRequest', + 'DeleteWorkflowRequest', + 'UpdateWorkflowRequest', + 'OperationMetadata', + }, +) + + +class Workflow(proto.Message): + r"""Workflow program to be executed by Workflows. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The resource name of the workflow. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + description (str): + Description of the workflow provided by the + user. Must be at most 1000 unicode characters + long. + state (google.cloud.workflows_v1beta.types.Workflow.State): + Output only. State of the workflow + deployment. + revision_id (str): + Output only. The revision of the workflow. A new revision of + a workflow is created as a result of updating the following + fields of a workflow: + + - ``source_code`` + - ``service_account`` The format is "000001-a4d", where the + first 6 characters define the zero-padded revision + ordinal number. They are followed by a hyphen and 3 + hexadecimal random characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp of when the + workflow was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of the + workflow. + revision_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp that the latest + revision of the workflow was created. + labels (MutableMapping[str, str]): + Labels associated with this workflow. + Labels can contain at most 64 entries. Keys and + values can be no longer than 63 characters and + can only contain lowercase letters, numeric + characters, underscores and dashes. Label keys + must start with a letter. International + characters are allowed. + service_account (str): + Name of the service account associated with the latest + workflow version. This service account represents the + identity of the workflow and determines what permissions the + workflow has. Format: + projects/{project}/serviceAccounts/{account} + + Using ``-`` as a wildcard for the ``{project}`` will infer + the project from the account. The ``{account}`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + + If not provided, workflow will use the project's default + service account. Modifying this field for an existing + workflow results in a new workflow revision. + source_contents (str): + Workflow code to be executed. The size limit + is 32KB. + + This field is a member of `oneof`_ ``source_code``. + """ + class State(proto.Enum): + r"""Describes the current state of workflow deployment. More + states may be added in the future. + + Values: + STATE_UNSPECIFIED (0): + Invalid state. + ACTIVE (1): + The workflow has been deployed successfully + and is serving. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + revision_id: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + revision_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + service_account: str = proto.Field( + proto.STRING, + number=9, + ) + source_contents: str = proto.Field( + proto.STRING, + number=10, + oneof='source_code', + ) + + +class ListWorkflowsRequest(proto.Message): + r"""Request for the + [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] + method. + + Attributes: + parent (str): + Required. Project and location from which the + workflows should be listed. Format: + projects/{project}/locations/{location} + page_size (int): + Maximum number of workflows to return per + call. The service may return fewer than this + value. If the value is not specified, a default + value of 500 will be used. The maximum permitted + value is 1000 and values greater than 1000 will + be coerced down to 1000. + page_token (str): + A page token, received from a previous ``ListWorkflows`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListWorkflows`` must match the call that provided the page + token. + filter (str): + Filter to restrict results to specific + workflows. + order_by (str): + Comma-separated list of fields that that + specify the order of the results. Default + sorting order for a field is ascending. To + specify descending order for a field, append a " + desc" suffix. + If not specified, the results will be returned + in an unspecified order. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListWorkflowsResponse(proto.Message): + r"""Response for the + [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] + method. + + Attributes: + workflows (MutableSequence[google.cloud.workflows_v1beta.types.Workflow]): + The workflows which match the request. + 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. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workflows: MutableSequence['Workflow'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workflow', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetWorkflowRequest(proto.Message): + r"""Request for the + [GetWorkflow][google.cloud.workflows.v1beta.Workflows.GetWorkflow] + method. + + Attributes: + name (str): + Required. Name of the workflow which + information should be retrieved. Format: + projects/{project}/locations/{location}/workflows/{workflow} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateWorkflowRequest(proto.Message): + r"""Request for the + [CreateWorkflow][google.cloud.workflows.v1beta.Workflows.CreateWorkflow] + method. + + Attributes: + parent (str): + Required. Project and location in which the + workflow should be created. Format: + projects/{project}/locations/{location} + workflow (google.cloud.workflows_v1beta.types.Workflow): + Required. Workflow to be created. + workflow_id (str): + Required. The ID of the workflow to be created. It has to + fulfill the following requirements: + + - Must contain only letters, numbers, underscores and + hyphens. + - Must start with a letter. + - Must be between 1-64 characters. + - Must end with a number or a letter. + - Must be unique within the customer project and location. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workflow: 'Workflow' = proto.Field( + proto.MESSAGE, + number=2, + message='Workflow', + ) + workflow_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteWorkflowRequest(proto.Message): + r"""Request for the + [DeleteWorkflow][google.cloud.workflows.v1beta.Workflows.DeleteWorkflow] + method. + + Attributes: + name (str): + Required. Name of the workflow to be deleted. + Format: + projects/{project}/locations/{location}/workflows/{workflow} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateWorkflowRequest(proto.Message): + r"""Request for the + [UpdateWorkflow][google.cloud.workflows.v1beta.Workflows.UpdateWorkflow] + method. + + Attributes: + workflow (google.cloud.workflows_v1beta.types.Workflow): + Required. Workflow to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + List of fields to be updated. If not present, + the entire workflow will be updated. + """ + + workflow: 'Workflow' = proto.Field( + proto.MESSAGE, + number=1, + message='Workflow', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation was created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation finished running. + target (str): + Server-defined resource path for the target + of the operation. + verb (str): + Name of the verb executed by the operation. + api_version (str): + API version used to start the operation. + """ + + create_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, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + api_version: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/mypy.ini b/owl-bot-staging/google-cloud-workflows/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/noxfile.py b/owl-bot-staging/google-cloud-workflows/v1beta/noxfile.py new file mode 100644 index 000000000000..312ca9cfb58e --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows' + +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/cloud/workflows_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/cloud/workflows_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-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json new file mode 100644 index 000000000000..c486937ea17a --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json @@ -0,0 +1,667 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.workflows.executions.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-workflows-executions", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient", + "shortName": "ExecutionsAsyncClient" + }, + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient.cancel_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions.CancelExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions", + "shortName": "Executions" + }, + "shortName": "CancelExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1beta.types.CancelExecutionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", + "shortName": "cancel_execution" + }, + "description": "Sample for CancelExecution", + "file": "workflowexecutions_v1beta_generated_executions_cancel_execution_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1beta_generated_Executions_CancelExecution_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": "workflowexecutions_v1beta_generated_executions_cancel_execution_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient", + "shortName": "ExecutionsClient" + }, + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient.cancel_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions.CancelExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions", + "shortName": "Executions" + }, + "shortName": "CancelExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1beta.types.CancelExecutionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", + "shortName": "cancel_execution" + }, + "description": "Sample for CancelExecution", + "file": "workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1beta_generated_Executions_CancelExecution_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": "workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient", + "shortName": "ExecutionsAsyncClient" + }, + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient.create_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions.CreateExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions", + "shortName": "Executions" + }, + "shortName": "CreateExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1beta.types.CreateExecutionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "execution", + "type": "google.cloud.workflows.executions_v1beta.types.Execution" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", + "shortName": "create_execution" + }, + "description": "Sample for CreateExecution", + "file": "workflowexecutions_v1beta_generated_executions_create_execution_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1beta_generated_Executions_CreateExecution_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": "workflowexecutions_v1beta_generated_executions_create_execution_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient", + "shortName": "ExecutionsClient" + }, + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient.create_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions.CreateExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions", + "shortName": "Executions" + }, + "shortName": "CreateExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1beta.types.CreateExecutionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "execution", + "type": "google.cloud.workflows.executions_v1beta.types.Execution" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", + "shortName": "create_execution" + }, + "description": "Sample for CreateExecution", + "file": "workflowexecutions_v1beta_generated_executions_create_execution_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1beta_generated_Executions_CreateExecution_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": "workflowexecutions_v1beta_generated_executions_create_execution_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient", + "shortName": "ExecutionsAsyncClient" + }, + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient.get_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions.GetExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions", + "shortName": "Executions" + }, + "shortName": "GetExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1beta.types.GetExecutionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", + "shortName": "get_execution" + }, + "description": "Sample for GetExecution", + "file": "workflowexecutions_v1beta_generated_executions_get_execution_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1beta_generated_Executions_GetExecution_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": "workflowexecutions_v1beta_generated_executions_get_execution_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient", + "shortName": "ExecutionsClient" + }, + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient.get_execution", + "method": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions.GetExecution", + "service": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions", + "shortName": "Executions" + }, + "shortName": "GetExecution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1beta.types.GetExecutionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", + "shortName": "get_execution" + }, + "description": "Sample for GetExecution", + "file": "workflowexecutions_v1beta_generated_executions_get_execution_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1beta_generated_Executions_GetExecution_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": "workflowexecutions_v1beta_generated_executions_get_execution_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient", + "shortName": "ExecutionsAsyncClient" + }, + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient.list_executions", + "method": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions.ListExecutions", + "service": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions", + "shortName": "Executions" + }, + "shortName": "ListExecutions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1beta.services.executions.pagers.ListExecutionsAsyncPager", + "shortName": "list_executions" + }, + "description": "Sample for ListExecutions", + "file": "workflowexecutions_v1beta_generated_executions_list_executions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1beta_generated_Executions_ListExecutions_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": "workflowexecutions_v1beta_generated_executions_list_executions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient", + "shortName": "ExecutionsClient" + }, + "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient.list_executions", + "method": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions.ListExecutions", + "service": { + "fullName": "google.cloud.workflows.executions.v1beta.Executions", + "shortName": "Executions" + }, + "shortName": "ListExecutions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows.executions_v1beta.services.executions.pagers.ListExecutionsPager", + "shortName": "list_executions" + }, + "description": "Sample for ListExecutions", + "file": "workflowexecutions_v1beta_generated_executions_list_executions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflowexecutions_v1beta_generated_Executions_ListExecutions_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": "workflowexecutions_v1beta_generated_executions_list_executions_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json new file mode 100644 index 000000000000..e6e1022f77a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json @@ -0,0 +1,844 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.workflows.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-workflows", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.create_workflow", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.CreateWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "CreateWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.CreateWorkflowRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workflow", + "type": "google.cloud.workflows_v1beta.types.Workflow" + }, + { + "name": "workflow_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workflow" + }, + "description": "Sample for CreateWorkflow", + "file": "workflows_v1beta_generated_workflows_create_workflow_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_CreateWorkflow_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1beta_generated_workflows_create_workflow_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.create_workflow", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.CreateWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "CreateWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.CreateWorkflowRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workflow", + "type": "google.cloud.workflows_v1beta.types.Workflow" + }, + { + "name": "workflow_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workflow" + }, + "description": "Sample for CreateWorkflow", + "file": "workflows_v1beta_generated_workflows_create_workflow_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_CreateWorkflow_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1beta_generated_workflows_create_workflow_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.delete_workflow", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.DeleteWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "DeleteWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.DeleteWorkflowRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_workflow" + }, + "description": "Sample for DeleteWorkflow", + "file": "workflows_v1beta_generated_workflows_delete_workflow_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_DeleteWorkflow_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1beta_generated_workflows_delete_workflow_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.delete_workflow", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.DeleteWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "DeleteWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.DeleteWorkflowRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_workflow" + }, + "description": "Sample for DeleteWorkflow", + "file": "workflows_v1beta_generated_workflows_delete_workflow_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_DeleteWorkflow_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1beta_generated_workflows_delete_workflow_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.get_workflow", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.GetWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "GetWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.GetWorkflowRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows_v1beta.types.Workflow", + "shortName": "get_workflow" + }, + "description": "Sample for GetWorkflow", + "file": "workflows_v1beta_generated_workflows_get_workflow_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_GetWorkflow_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": "workflows_v1beta_generated_workflows_get_workflow_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.get_workflow", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.GetWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "GetWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.GetWorkflowRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows_v1beta.types.Workflow", + "shortName": "get_workflow" + }, + "description": "Sample for GetWorkflow", + "file": "workflows_v1beta_generated_workflows_get_workflow_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_GetWorkflow_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": "workflows_v1beta_generated_workflows_get_workflow_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.list_workflows", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.ListWorkflows", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "ListWorkflows" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.ListWorkflowsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows_v1beta.services.workflows.pagers.ListWorkflowsAsyncPager", + "shortName": "list_workflows" + }, + "description": "Sample for ListWorkflows", + "file": "workflows_v1beta_generated_workflows_list_workflows_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_ListWorkflows_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": "workflows_v1beta_generated_workflows_list_workflows_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.list_workflows", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.ListWorkflows", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "ListWorkflows" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.ListWorkflowsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workflows_v1beta.services.workflows.pagers.ListWorkflowsPager", + "shortName": "list_workflows" + }, + "description": "Sample for ListWorkflows", + "file": "workflows_v1beta_generated_workflows_list_workflows_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_ListWorkflows_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": "workflows_v1beta_generated_workflows_list_workflows_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", + "shortName": "WorkflowsAsyncClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.update_workflow", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.UpdateWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "UpdateWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.UpdateWorkflowRequest" + }, + { + "name": "workflow", + "type": "google.cloud.workflows_v1beta.types.Workflow" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_workflow" + }, + "description": "Sample for UpdateWorkflow", + "file": "workflows_v1beta_generated_workflows_update_workflow_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_UpdateWorkflow_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1beta_generated_workflows_update_workflow_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", + "shortName": "WorkflowsClient" + }, + "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.update_workflow", + "method": { + "fullName": "google.cloud.workflows.v1beta.Workflows.UpdateWorkflow", + "service": { + "fullName": "google.cloud.workflows.v1beta.Workflows", + "shortName": "Workflows" + }, + "shortName": "UpdateWorkflow" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workflows_v1beta.types.UpdateWorkflowRequest" + }, + { + "name": "workflow", + "type": "google.cloud.workflows_v1beta.types.Workflow" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_workflow" + }, + "description": "Sample for UpdateWorkflow", + "file": "workflows_v1beta_generated_workflows_update_workflow_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workflows_v1beta_generated_Workflows_UpdateWorkflow_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workflows_v1beta_generated_workflows_update_workflow_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_async.py new file mode 100644 index 000000000000..57077da8b609 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_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 CancelExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1beta_generated_Executions_CancelExecution_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1beta + + +async def sample_cancel_execution(): + # Create a client + client = executions_v1beta.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1beta.CancelExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.cancel_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1beta_generated_Executions_CancelExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py new file mode 100644 index 000000000000..8a127df8dd29 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_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 CancelExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1beta_generated_Executions_CancelExecution_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1beta + + +def sample_cancel_execution(): + # Create a client + client = executions_v1beta.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1beta.CancelExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.cancel_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1beta_generated_Executions_CancelExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_async.py new file mode 100644 index 000000000000..8486d9f53417 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_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 CreateExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1beta_generated_Executions_CreateExecution_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1beta + + +async def sample_create_execution(): + # Create a client + client = executions_v1beta.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1beta.CreateExecutionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1beta_generated_Executions_CreateExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_sync.py new file mode 100644 index 000000000000..57fa24a51891 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_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 CreateExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1beta_generated_Executions_CreateExecution_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1beta + + +def sample_create_execution(): + # Create a client + client = executions_v1beta.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1beta.CreateExecutionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1beta_generated_Executions_CreateExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_async.py new file mode 100644 index 000000000000..8779820f1c99 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_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 GetExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1beta_generated_Executions_GetExecution_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1beta + + +async def sample_get_execution(): + # Create a client + client = executions_v1beta.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1beta.GetExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1beta_generated_Executions_GetExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_sync.py new file mode 100644 index 000000000000..749dcd2bd082 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_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 GetExecution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1beta_generated_Executions_GetExecution_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1beta + + +def sample_get_execution(): + # Create a client + client = executions_v1beta.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1beta.GetExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.get_execution(request=request) + + # Handle the response + print(response) + +# [END workflowexecutions_v1beta_generated_Executions_GetExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_async.py new file mode 100644 index 000000000000..bdbc9b363786 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_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 ListExecutions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1beta_generated_Executions_ListExecutions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1beta + + +async def sample_list_executions(): + # Create a client + client = executions_v1beta.ExecutionsAsyncClient() + + # Initialize request argument(s) + request = executions_v1beta.ListExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_executions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workflowexecutions_v1beta_generated_Executions_ListExecutions_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_sync.py new file mode 100644 index 000000000000..18afcff69079 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_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 ListExecutions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows-executions + + +# [START workflowexecutions_v1beta_generated_Executions_ListExecutions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud.workflows import executions_v1beta + + +def sample_list_executions(): + # Create a client + client = executions_v1beta.ExecutionsClient() + + # Initialize request argument(s) + request = executions_v1beta.ListExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_executions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workflowexecutions_v1beta_generated_Executions_ListExecutions_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_async.py new file mode 100644 index 000000000000..bf8988582165 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_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 CreateWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_CreateWorkflow_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +async def sample_create_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + workflow = workflows_v1beta.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1beta.CreateWorkflowRequest( + parent="parent_value", + workflow=workflow, + workflow_id="workflow_id_value", + ) + + # Make the request + operation = client.create_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workflows_v1beta_generated_Workflows_CreateWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_sync.py new file mode 100644 index 000000000000..3b9aba651936 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_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 CreateWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_CreateWorkflow_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +def sample_create_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + workflow = workflows_v1beta.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1beta.CreateWorkflowRequest( + parent="parent_value", + workflow=workflow, + workflow_id="workflow_id_value", + ) + + # Make the request + operation = client.create_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workflows_v1beta_generated_Workflows_CreateWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_async.py new file mode 100644 index 000000000000..8422fac54b60 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_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 DeleteWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_DeleteWorkflow_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +async def sample_delete_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1beta.DeleteWorkflowRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workflows_v1beta_generated_Workflows_DeleteWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_sync.py new file mode 100644 index 000000000000..c474e3cbe6c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_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 DeleteWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_DeleteWorkflow_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +def sample_delete_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1beta.DeleteWorkflowRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workflows_v1beta_generated_Workflows_DeleteWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_async.py new file mode 100644 index 000000000000..96602f24aad9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_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 GetWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_GetWorkflow_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +async def sample_get_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1beta.GetWorkflowRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workflow(request=request) + + # Handle the response + print(response) + +# [END workflows_v1beta_generated_Workflows_GetWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_sync.py new file mode 100644 index 000000000000..2a96994f32a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_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 GetWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_GetWorkflow_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +def sample_get_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1beta.GetWorkflowRequest( + name="name_value", + ) + + # Make the request + response = client.get_workflow(request=request) + + # Handle the response + print(response) + +# [END workflows_v1beta_generated_Workflows_GetWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_async.py new file mode 100644 index 000000000000..4f85d7bebf66 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_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 ListWorkflows +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_ListWorkflows_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +async def sample_list_workflows(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + request = workflows_v1beta.ListWorkflowsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workflows(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workflows_v1beta_generated_Workflows_ListWorkflows_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_sync.py new file mode 100644 index 000000000000..e6b2ea2bf0f5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_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 ListWorkflows +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_ListWorkflows_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +def sample_list_workflows(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + request = workflows_v1beta.ListWorkflowsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workflows(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workflows_v1beta_generated_Workflows_ListWorkflows_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_async.py new file mode 100644 index 000000000000..a3e9b76ccfbe --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_UpdateWorkflow_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +async def sample_update_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsAsyncClient() + + # Initialize request argument(s) + workflow = workflows_v1beta.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1beta.UpdateWorkflowRequest( + workflow=workflow, + ) + + # Make the request + operation = client.update_workflow(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workflows_v1beta_generated_Workflows_UpdateWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_sync.py new file mode 100644 index 000000000000..95d82e6a4c91 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkflow +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workflows + + +# [START workflows_v1beta_generated_Workflows_UpdateWorkflow_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workflows_v1beta + + +def sample_update_workflow(): + # Create a client + client = workflows_v1beta.WorkflowsClient() + + # Initialize request argument(s) + workflow = workflows_v1beta.Workflow() + workflow.source_contents = "source_contents_value" + + request = workflows_v1beta.UpdateWorkflowRequest( + workflow=workflow, + ) + + # Make the request + operation = client.update_workflow(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workflows_v1beta_generated_Workflows_UpdateWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_executions_v1beta_keywords.py b/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_executions_v1beta_keywords.py new file mode 100644 index 000000000000..92c2e5d886c8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_executions_v1beta_keywords.py @@ -0,0 +1,179 @@ +#! /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 executionsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'cancel_execution': ('name', ), + 'create_execution': ('parent', 'execution', ), + 'get_execution': ('name', 'view', ), + 'list_executions': ('parent', 'page_size', 'page_token', 'view', ), + } + + 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=executionsCallTransformer(), +): + """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 executions 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-cloud-workflows/v1beta/scripts/fixup_workflows_v1beta_keywords.py b/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_workflows_v1beta_keywords.py new file mode 100644 index 000000000000..a0144dc0ff65 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_workflows_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 workflowsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_workflow': ('parent', 'workflow', 'workflow_id', ), + 'delete_workflow': ('name', ), + 'get_workflow': ('name', ), + 'list_workflows': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'update_workflow': ('workflow', '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=workflowsCallTransformer(), +): + """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 workflows 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-cloud-workflows/v1beta/setup.py b/owl-bot-staging/google-cloud-workflows/v1beta/setup.py new file mode 100644 index 000000000000..85ca80f0b4ea --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows' + + +description = "Google Cloud Workflows API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/workflows/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-cloud-workflows" + +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-cloud-workflows/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_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-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/test_executions.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/test_executions.py new file mode 100644 index 000000000000..065f19fcccb7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/test_executions.py @@ -0,0 +1,3145 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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.cloud.workflows.executions_v1beta.services.executions import ExecutionsAsyncClient +from google.cloud.workflows.executions_v1beta.services.executions import ExecutionsClient +from google.cloud.workflows.executions_v1beta.services.executions import pagers +from google.cloud.workflows.executions_v1beta.services.executions import transports +from google.cloud.workflows.executions_v1beta.types import executions +from google.oauth2 import service_account +from google.protobuf import timestamp_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 ExecutionsClient._get_default_mtls_endpoint(None) is None + assert ExecutionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ExecutionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ExecutionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ExecutionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ExecutionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ExecutionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ExecutionsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ExecutionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ExecutionsClient._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 ExecutionsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ExecutionsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ExecutionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ExecutionsClient._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 ExecutionsClient._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 ExecutionsClient._get_client_cert_source(None, False) is None + assert ExecutionsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ExecutionsClient._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 ExecutionsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ExecutionsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ExecutionsClient._DEFAULT_UNIVERSE + default_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ExecutionsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ExecutionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT + assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "always") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT + assert ExecutionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT + assert ExecutionsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ExecutionsClient._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 ExecutionsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ExecutionsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ExecutionsClient._get_universe_domain(None, None) == ExecutionsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ExecutionsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ExecutionsClient, "grpc"), + (ExecutionsAsyncClient, "grpc_asyncio"), +]) +def test_executions_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 == ( + 'workflowexecutions.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ExecutionsGrpcTransport, "grpc"), + (transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_executions_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", [ + (ExecutionsClient, "grpc"), + (ExecutionsAsyncClient, "grpc_asyncio"), +]) +def test_executions_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 == ( + 'workflowexecutions.googleapis.com:443' + ) + + +def test_executions_client_get_transport_class(): + transport = ExecutionsClient.get_transport_class() + available_transports = [ + transports.ExecutionsGrpcTransport, + ] + assert transport in available_transports + + transport = ExecutionsClient.get_transport_class("grpc") + assert transport == transports.ExecutionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) +def test_executions_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(ExecutionsClient, '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(ExecutionsClient, '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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", "true"), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", "false"), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_executions_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", [ + ExecutionsClient, ExecutionsAsyncClient +]) +@mock.patch.object(ExecutionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExecutionsAsyncClient)) +def test_executions_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", [ + ExecutionsClient, ExecutionsAsyncClient +]) +@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) +@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) +def test_executions_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ExecutionsClient._DEFAULT_UNIVERSE + default_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ExecutionsClient._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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_executions_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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", grpc_helpers), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_executions_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_executions_client_client_options_from_dict(): + with mock.patch('google.cloud.workflows.executions_v1beta.services.executions.transports.ExecutionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ExecutionsClient( + 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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", grpc_helpers), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_executions_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( + "workflowexecutions.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="workflowexecutions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + executions.ListExecutionsRequest, + dict, +]) +def test_list_executions(request_type, transport: str = 'grpc'): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.ListExecutionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = executions.ListExecutionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExecutionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_executions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = executions.ListExecutionsRequest( + 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_executions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_executions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == executions.ListExecutionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_executions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_executions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_executions] = mock_rpc + request = {} + client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_executions(request) + + # Establish that a new wrapper 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_executions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_executions in client._client._transport._wrapped_methods + + # 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_executions] = mock_rpc + + request = {} + await client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_executions(request) + + # Establish that a new wrapper 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_executions_async(transport: str = 'grpc_asyncio', request_type=executions.ListExecutionsRequest): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = executions.ListExecutionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExecutionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_executions_async_from_dict(): + await test_list_executions_async(request_type=dict) + +def test_list_executions_field_headers(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.ListExecutionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + call.return_value = executions.ListExecutionsResponse() + client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_executions_field_headers_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.ListExecutionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse()) + await client.list_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_executions_flattened(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.ListExecutionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_executions( + 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_executions_flattened_error(): + client = ExecutionsClient( + credentials=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_executions( + executions.ListExecutionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_executions_flattened_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.ListExecutionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_executions( + 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_executions_flattened_error_async(): + client = ExecutionsAsyncClient( + credentials=async_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_executions( + executions.ListExecutionsRequest(), + parent='parent_value', + ) + + +def test_list_executions_pager(transport_name: str = "grpc"): + client = ExecutionsClient( + 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_executions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + executions.Execution(), + ], + next_page_token='abc', + ), + executions.ListExecutionsResponse( + executions=[], + next_page_token='def', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + ], + next_page_token='ghi', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_executions(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, executions.Execution) + for i in results) +def test_list_executions_pages(transport_name: str = "grpc"): + client = ExecutionsClient( + 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_executions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + executions.Execution(), + ], + next_page_token='abc', + ), + executions.ListExecutionsResponse( + executions=[], + next_page_token='def', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + ], + next_page_token='ghi', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + ], + ), + RuntimeError, + ) + pages = list(client.list_executions(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_executions_async_pager(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + executions.Execution(), + ], + next_page_token='abc', + ), + executions.ListExecutionsResponse( + executions=[], + next_page_token='def', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + ], + next_page_token='ghi', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_executions(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, executions.Execution) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_executions_async_pages(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + executions.Execution(), + ], + next_page_token='abc', + ), + executions.ListExecutionsResponse( + executions=[], + next_page_token='def', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + ], + next_page_token='ghi', + ), + executions.ListExecutionsResponse( + executions=[ + executions.Execution(), + executions.Execution(), + ], + ), + 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_executions(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", [ + executions.CreateExecutionRequest, + dict, +]) +def test_create_execution(request_type, transport: str = 'grpc'): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + ) + response = client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = executions.CreateExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + + +def test_create_execution_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = executions.CreateExecutionRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_execution(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == executions.CreateExecutionRequest( + parent='parent_value', + ) + +def test_create_execution_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_execution in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_execution] = mock_rpc + request = {} + client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_execution(request) + + # Establish that a new wrapper 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_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_execution in client._client._transport._wrapped_methods + + # 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_execution] = mock_rpc + + request = {} + await client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_execution(request) + + # Establish that a new wrapper 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_execution_async(transport: str = 'grpc_asyncio', request_type=executions.CreateExecutionRequest): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + )) + response = await client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = executions.CreateExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + + +@pytest.mark.asyncio +async def test_create_execution_async_from_dict(): + await test_create_execution_async(request_type=dict) + +def test_create_execution_field_headers(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.CreateExecutionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_execution_field_headers_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.CreateExecutionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + await client.create_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_execution_flattened(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_execution( + parent='parent_value', + execution=executions.Execution(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].execution + mock_val = executions.Execution(name='name_value') + assert arg == mock_val + + +def test_create_execution_flattened_error(): + client = ExecutionsClient( + credentials=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_execution( + executions.CreateExecutionRequest(), + parent='parent_value', + execution=executions.Execution(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_execution_flattened_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_execution( + parent='parent_value', + execution=executions.Execution(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].execution + mock_val = executions.Execution(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_execution_flattened_error_async(): + client = ExecutionsAsyncClient( + credentials=async_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_execution( + executions.CreateExecutionRequest(), + parent='parent_value', + execution=executions.Execution(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + executions.GetExecutionRequest, + dict, +]) +def test_get_execution(request_type, transport: str = 'grpc'): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + ) + response = client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = executions.GetExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + + +def test_get_execution_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = executions.GetExecutionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_execution(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == executions.GetExecutionRequest( + name='name_value', + ) + +def test_get_execution_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_execution in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_execution] = mock_rpc + request = {} + client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_execution(request) + + # Establish that a new wrapper 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_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_execution in client._client._transport._wrapped_methods + + # 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_execution] = mock_rpc + + request = {} + await client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_execution(request) + + # Establish that a new wrapper 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_execution_async(transport: str = 'grpc_asyncio', request_type=executions.GetExecutionRequest): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + )) + response = await client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = executions.GetExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + + +@pytest.mark.asyncio +async def test_get_execution_async_from_dict(): + await test_get_execution_async(request_type=dict) + +def test_get_execution_field_headers(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.GetExecutionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_execution_field_headers_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.GetExecutionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + await client.get_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_execution_flattened(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_execution( + 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_execution_flattened_error(): + client = ExecutionsClient( + credentials=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_execution( + executions.GetExecutionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_execution_flattened_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_execution( + 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_execution_flattened_error_async(): + client = ExecutionsAsyncClient( + credentials=async_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_execution( + executions.GetExecutionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + executions.CancelExecutionRequest, + dict, +]) +def test_cancel_execution(request_type, transport: str = 'grpc'): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + ) + response = client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = executions.CancelExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + + +def test_cancel_execution_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = executions.CancelExecutionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.cancel_execution(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == executions.CancelExecutionRequest( + name='name_value', + ) + +def test_cancel_execution_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.cancel_execution in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.cancel_execution] = mock_rpc + request = {} + client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.cancel_execution(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_cancel_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.cancel_execution in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.cancel_execution] = mock_rpc + + request = {} + await client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.cancel_execution(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_cancel_execution_async(transport: str = 'grpc_asyncio', request_type=executions.CancelExecutionRequest): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + )) + response = await client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = executions.CancelExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, executions.Execution) + assert response.name == 'name_value' + assert response.state == executions.Execution.State.ACTIVE + assert response.argument == 'argument_value' + assert response.result == 'result_value' + assert response.workflow_revision_id == 'workflow_revision_id_value' + + +@pytest.mark.asyncio +async def test_cancel_execution_async_from_dict(): + await test_cancel_execution_async(request_type=dict) + +def test_cancel_execution_field_headers(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.CancelExecutionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_cancel_execution_field_headers_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = executions.CancelExecutionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + await client.cancel_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_cancel_execution_flattened(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.cancel_execution( + 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_cancel_execution_flattened_error(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.cancel_execution( + executions.CancelExecutionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_cancel_execution_flattened_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = executions.Execution() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.cancel_execution( + 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_cancel_execution_flattened_error_async(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.cancel_execution( + executions.CancelExecutionRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExecutionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ExecutionsClient( + 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 = ExecutionsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExecutionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ExecutionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExecutionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ExecutionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ExecutionsGrpcTransport, + transports.ExecutionsGrpcAsyncIOTransport, +]) +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 = ExecutionsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ExecutionsClient( + 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_executions_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + call.return_value = executions.ListExecutionsResponse() + client.list_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.ListExecutionsRequest() + + assert args[0] == request_msg + + +# This 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_execution_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.create_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.CreateExecutionRequest() + + assert args[0] == request_msg + + +# This 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_execution_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.get_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.GetExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_cancel_execution_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + call.return_value = executions.Execution() + client.cancel_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.CancelExecutionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ExecutionsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ExecutionsAsyncClient( + 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_executions_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_executions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse( + next_page_token='next_page_token_value', + )) + await client.list_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.ListExecutionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_execution_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + )) + await client.create_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.CreateExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_execution_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + )) + await client.get_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.GetExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_cancel_execution_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_execution), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( + name='name_value', + state=executions.Execution.State.ACTIVE, + argument='argument_value', + result='result_value', + workflow_revision_id='workflow_revision_id_value', + )) + await client.cancel_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = executions.CancelExecutionRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ExecutionsGrpcTransport, + ) + +def test_executions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ExecutionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_executions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.workflows.executions_v1beta.services.executions.transports.ExecutionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ExecutionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_executions', + 'create_execution', + 'get_execution', + 'cancel_execution', + ) + 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_executions_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workflows.executions_v1beta.services.executions.transports.ExecutionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExecutionsTransport( + 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_executions_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workflows.executions_v1beta.services.executions.transports.ExecutionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExecutionsTransport() + adc.assert_called_once() + + +def test_executions_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) + ExecutionsClient() + 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.ExecutionsGrpcTransport, + transports.ExecutionsGrpcAsyncIOTransport, + ], +) +def test_executions_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.ExecutionsGrpcTransport, + transports.ExecutionsGrpcAsyncIOTransport, + ], +) +def test_executions_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.ExecutionsGrpcTransport, grpc_helpers), + (transports.ExecutionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_executions_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( + "workflowexecutions.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="workflowexecutions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) +def test_executions_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_executions_host_no_port(transport_name): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workflowexecutions.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workflowexecutions.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_executions_host_with_port(transport_name): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workflowexecutions.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workflowexecutions.googleapis.com:8000' + ) + +def test_executions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExecutionsGrpcTransport( + 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_executions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExecutionsGrpcAsyncIOTransport( + 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.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) +def test_executions_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.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) +def test_executions_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_execution_path(): + project = "squid" + location = "clam" + workflow = "whelk" + execution = "octopus" + expected = "projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}".format(project=project, location=location, workflow=workflow, execution=execution, ) + actual = ExecutionsClient.execution_path(project, location, workflow, execution) + assert expected == actual + + +def test_parse_execution_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "workflow": "cuttlefish", + "execution": "mussel", + } + path = ExecutionsClient.execution_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_execution_path(path) + assert expected == actual + +def test_workflow_path(): + project = "winkle" + location = "nautilus" + workflow = "scallop" + expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + actual = ExecutionsClient.workflow_path(project, location, workflow) + assert expected == actual + + +def test_parse_workflow_path(): + expected = { + "project": "abalone", + "location": "squid", + "workflow": "clam", + } + path = ExecutionsClient.workflow_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_workflow_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ExecutionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ExecutionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ExecutionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ExecutionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ExecutionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ExecutionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ExecutionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ExecutionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.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 = ExecutionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ExecutionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ExecutionsClient.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.ExecutionsTransport, '_prep_wrapped_messages') as prep: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ExecutionsTransport, '_prep_wrapped_messages') as prep: + transport_class = ExecutionsClient.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 = ExecutionsClient( + 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 = ExecutionsAsyncClient( + 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_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ExecutionsClient( + 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", [ + (ExecutionsClient, transports.ExecutionsGrpcTransport), + (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport), +]) +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-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_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-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/test_workflows.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/test_workflows.py new file mode 100644 index 000000000000..f63551e82c3b --- /dev/null +++ b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/test_workflows.py @@ -0,0 +1,5286 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workflows_v1beta.services.workflows import WorkflowsAsyncClient +from google.cloud.workflows_v1beta.services.workflows import WorkflowsClient +from google.cloud.workflows_v1beta.services.workflows import pagers +from google.cloud.workflows_v1beta.services.workflows import transports +from google.cloud.workflows_v1beta.types import workflows +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +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 WorkflowsClient._get_default_mtls_endpoint(None) is None + assert WorkflowsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WorkflowsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WorkflowsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WorkflowsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WorkflowsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert WorkflowsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WorkflowsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WorkflowsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + WorkflowsClient._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 WorkflowsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WorkflowsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WorkflowsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WorkflowsClient._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 WorkflowsClient._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 WorkflowsClient._get_client_cert_source(None, False) is None + assert WorkflowsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert WorkflowsClient._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 WorkflowsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert WorkflowsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WorkflowsClient._DEFAULT_UNIVERSE + default_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert WorkflowsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert WorkflowsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT + assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "always") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT + assert WorkflowsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT + assert WorkflowsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + WorkflowsClient._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 WorkflowsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert WorkflowsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert WorkflowsClient._get_universe_domain(None, None) == WorkflowsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + WorkflowsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WorkflowsClient, "grpc"), + (WorkflowsAsyncClient, "grpc_asyncio"), + (WorkflowsClient, "rest"), +]) +def test_workflows_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 == ( + 'workflows.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workflows.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WorkflowsGrpcTransport, "grpc"), + (transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WorkflowsRestTransport, "rest"), +]) +def test_workflows_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", [ + (WorkflowsClient, "grpc"), + (WorkflowsAsyncClient, "grpc_asyncio"), + (WorkflowsClient, "rest"), +]) +def test_workflows_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 == ( + 'workflows.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workflows.googleapis.com' + ) + + +def test_workflows_client_get_transport_class(): + transport = WorkflowsClient.get_transport_class() + available_transports = [ + transports.WorkflowsGrpcTransport, + transports.WorkflowsRestTransport, + ] + assert transport in available_transports + + transport = WorkflowsClient.get_transport_class("grpc") + assert transport == transports.WorkflowsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), +]) +@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) +def test_workflows_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(WorkflowsClient, '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(WorkflowsClient, '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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", "true"), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", "false"), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest", "true"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest", "false"), +]) +@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_workflows_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", [ + WorkflowsClient, WorkflowsAsyncClient +]) +@mock.patch.object(WorkflowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkflowsAsyncClient)) +def test_workflows_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", [ + WorkflowsClient, WorkflowsAsyncClient +]) +@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) +@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) +def test_workflows_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WorkflowsClient._DEFAULT_UNIVERSE + default_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WorkflowsClient._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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), +]) +def test_workflows_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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", grpc_helpers), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WorkflowsClient, transports.WorkflowsRestTransport, "rest", None), +]) +def test_workflows_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_workflows_client_client_options_from_dict(): + with mock.patch('google.cloud.workflows_v1beta.services.workflows.transports.WorkflowsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WorkflowsClient( + 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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", grpc_helpers), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_workflows_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( + "workflows.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="workflows.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + workflows.ListWorkflowsRequest, + dict, +]) +def test_list_workflows(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.ListWorkflowsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.ListWorkflowsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkflowsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workflows_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.ListWorkflowsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workflows(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.ListWorkflowsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_workflows_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflows in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflows] = mock_rpc + request = {} + client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workflows(request) + + # Establish that a new wrapper 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_workflows_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflows in client._client._transport._wrapped_methods + + # 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_workflows] = mock_rpc + + request = {} + await client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workflows(request) + + # Establish that a new wrapper 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_workflows_async(transport: str = 'grpc_asyncio', request_type=workflows.ListWorkflowsRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.ListWorkflowsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkflowsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workflows_async_from_dict(): + await test_list_workflows_async(request_type=dict) + +def test_list_workflows_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.ListWorkflowsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + call.return_value = workflows.ListWorkflowsResponse() + client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflows_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.ListWorkflowsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse()) + await client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflows_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.ListWorkflowsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workflows( + 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_workflows_flattened_error(): + client = WorkflowsClient( + credentials=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_workflows( + workflows.ListWorkflowsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workflows_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.ListWorkflowsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workflows( + 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_workflows_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflows( + workflows.ListWorkflowsRequest(), + parent='parent_value', + ) + + +def test_list_workflows_pager(transport_name: str = "grpc"): + client = WorkflowsClient( + 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_workflows), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workflows(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, workflows.Workflow) + for i in results) +def test_list_workflows_pages(transport_name: str = "grpc"): + client = WorkflowsClient( + 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_workflows), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workflows(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_workflows_async_pager(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workflows(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, workflows.Workflow) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workflows_async_pages(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + 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_workflows(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", [ + workflows.GetWorkflowRequest, + dict, +]) +def test_get_workflow(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.Workflow( + name='name_value', + description='description_value', + state=workflows.Workflow.State.ACTIVE, + revision_id='revision_id_value', + service_account='service_account_value', + source_contents='source_contents_value', + ) + response = client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.GetWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workflows.Workflow) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == workflows.Workflow.State.ACTIVE + assert response.revision_id == 'revision_id_value' + assert response.service_account == 'service_account_value' + + +def test_get_workflow_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.GetWorkflowRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_workflow(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.GetWorkflowRequest( + name='name_value', + ) + +def test_get_workflow_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workflow] = mock_rpc + request = {} + client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workflow(request) + + # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflow in client._client._transport._wrapped_methods + + # 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_workflow] = mock_rpc + + request = {} + await client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_workflow(request) + + # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.GetWorkflowRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow( + name='name_value', + description='description_value', + state=workflows.Workflow.State.ACTIVE, + revision_id='revision_id_value', + service_account='service_account_value', + )) + response = await client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.GetWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workflows.Workflow) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == workflows.Workflow.State.ACTIVE + assert response.revision_id == 'revision_id_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_workflow_async_from_dict(): + await test_get_workflow_async(request_type=dict) + +def test_get_workflow_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.GetWorkflowRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + call.return_value = workflows.Workflow() + client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.GetWorkflowRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow()) + await client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.Workflow() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workflow( + 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_workflow_flattened_error(): + client = WorkflowsClient( + credentials=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_workflow( + workflows.GetWorkflowRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workflow_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workflows.Workflow() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workflow( + 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_workflow_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflow( + workflows.GetWorkflowRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workflows.CreateWorkflowRequest, + dict, +]) +def test_create_workflow(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.CreateWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workflow_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.CreateWorkflowRequest( + parent='parent_value', + workflow_id='workflow_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_workflow(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.CreateWorkflowRequest( + parent='parent_value', + workflow_id='workflow_id_value', + ) + +def test_create_workflow_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + request = {} + client.create_workflow(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.create_workflow(request) + + # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflow in client._client._transport._wrapped_methods + + # 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_workflow] = mock_rpc + + request = {} + await client.create_workflow(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.create_workflow(request) + + # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.CreateWorkflowRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__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.create_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.CreateWorkflowRequest() + 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_create_workflow_async_from_dict(): + await test_create_workflow_async(request_type=dict) + +def test_create_workflow_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.CreateWorkflowRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.CreateWorkflowRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_workflow( + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_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].workflow + mock_val = workflows.Workflow(name='name_value') + assert arg == mock_val + arg = args[0].workflow_id + mock_val = 'workflow_id_value' + assert arg == mock_val + + +def test_create_workflow_flattened_error(): + client = WorkflowsClient( + credentials=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_workflow( + workflows.CreateWorkflowRequest(), + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workflow_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_workflow( + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_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].workflow + mock_val = workflows.Workflow(name='name_value') + assert arg == mock_val + arg = args[0].workflow_id + mock_val = 'workflow_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workflow_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflow( + workflows.CreateWorkflowRequest(), + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workflows.DeleteWorkflowRequest, + dict, +]) +def test_delete_workflow(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.DeleteWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workflow_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.DeleteWorkflowRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_workflow(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.DeleteWorkflowRequest( + name='name_value', + ) + +def test_delete_workflow_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + request = {} + client.delete_workflow(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.delete_workflow(request) + + # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflow in client._client._transport._wrapped_methods + + # 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_workflow] = mock_rpc + + request = {} + await client.delete_workflow(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.delete_workflow(request) + + # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.DeleteWorkflowRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__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.delete_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.DeleteWorkflowRequest() + 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_delete_workflow_async_from_dict(): + await test_delete_workflow_async(request_type=dict) + +def test_delete_workflow_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.DeleteWorkflowRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.DeleteWorkflowRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workflow_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_workflow( + 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_workflow_flattened_error(): + client = WorkflowsClient( + credentials=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_workflow( + workflows.DeleteWorkflowRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workflow_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_workflow( + 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_workflow_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflow( + workflows.DeleteWorkflowRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workflows.UpdateWorkflowRequest, + dict, +]) +def test_update_workflow(request_type, transport: str = 'grpc'): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workflows.UpdateWorkflowRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workflow_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workflows.UpdateWorkflowRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_workflow(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workflows.UpdateWorkflowRequest( + ) + +def test_update_workflow_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + request = {} + client.update_workflow(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.update_workflow(request) + + # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workflow in client._client._transport._wrapped_methods + + # 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_workflow] = mock_rpc + + request = {} + await client.update_workflow(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.update_workflow(request) + + # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.UpdateWorkflowRequest): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workflow), + '__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.update_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workflows.UpdateWorkflowRequest() + 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_update_workflow_async_from_dict(): + await test_update_workflow_async(request_type=dict) + +def test_update_workflow_field_headers(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.UpdateWorkflowRequest() + + request.workflow.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workflow.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workflow_field_headers_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workflows.UpdateWorkflowRequest() + + request.workflow.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workflow.name=name_value', + ) in kw['metadata'] + + +def test_update_workflow_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_workflow( + workflow=workflows.Workflow(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].workflow + mock_val = workflows.Workflow(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_workflow_flattened_error(): + client = WorkflowsClient( + credentials=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_workflow( + workflows.UpdateWorkflowRequest(), + workflow=workflows.Workflow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workflow_flattened_async(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_workflow( + workflow=workflows.Workflow(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].workflow + mock_val = workflows.Workflow(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_workflow_flattened_error_async(): + client = WorkflowsAsyncClient( + credentials=async_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_workflow( + workflows.UpdateWorkflowRequest(), + workflow=workflows.Workflow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_workflows_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflows in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflows] = mock_rpc + + request = {} + client.list_workflows(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workflows(request) + + # Establish 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_workflows_rest_required_fields(request_type=workflows.ListWorkflowsRequest): + transport_class = transports.WorkflowsRestTransport + + 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_workflows._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_workflows._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "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 = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workflows.ListWorkflowsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workflows.ListWorkflowsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_workflows(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workflows_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workflows._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workflows_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workflows.ListWorkflowsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/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 = workflows.ListWorkflowsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_workflows(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workflows" % client.transport._host, args[1]) + + +def test_list_workflows_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflows( + workflows.ListWorkflowsRequest(), + parent='parent_value', + ) + + +def test_list_workflows_rest_pager(transport: str = 'rest'): + client = WorkflowsClient( + 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 = ( + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + workflows.Workflow(), + ], + next_page_token='abc', + ), + workflows.ListWorkflowsResponse( + workflows=[], + next_page_token='def', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + ], + next_page_token='ghi', + ), + workflows.ListWorkflowsResponse( + workflows=[ + workflows.Workflow(), + workflows.Workflow(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workflows.ListWorkflowsResponse.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/locations/sample2'} + + pager = client.list_workflows(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workflows.Workflow) + for i in results) + + pages = list(client.list_workflows(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_workflow_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workflow] = mock_rpc + + request = {} + client.get_workflow(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workflow(request) + + # Establish 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_workflow_rest_required_fields(request_type=workflows.GetWorkflowRequest): + transport_class = transports.WorkflowsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workflow._get_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_workflow._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workflows.Workflow() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workflows.Workflow.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_workflow(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workflow_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workflow._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_workflow_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workflows.Workflow() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workflows/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 = workflows.Workflow.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_workflow(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workflows/*}" % client.transport._host, args[1]) + + +def test_get_workflow_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflow( + workflows.GetWorkflowRequest(), + name='name_value', + ) + + +def test_create_workflow_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + + request = {} + client.create_workflow(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.create_workflow(request) + + # Establish 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_workflow_rest_required_fields(request_type=workflows.CreateWorkflowRequest): + transport_class = transports.WorkflowsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workflow_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 "workflowId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workflow._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workflowId" in jsonified_request + assert jsonified_request["workflowId"] == request_init["workflow_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workflowId"] = 'workflow_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workflow._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("workflow_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 "workflowId" in jsonified_request + assert jsonified_request["workflowId"] == 'workflow_id_value' + + client = WorkflowsClient( + 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 + + response = client.create_workflow(request) + + expected_params = [ + ( + "workflowId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workflow_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workflow._get_unset_required_fields({}) + assert set(unset_fields) == (set(("workflowId", )) & set(("parent", "workflow", "workflowId", ))) + + +def test_create_workflow_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workflow(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workflows" % client.transport._host, args[1]) + + +def test_create_workflow_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflow( + workflows.CreateWorkflowRequest(), + parent='parent_value', + workflow=workflows.Workflow(name='name_value'), + workflow_id='workflow_id_value', + ) + + +def test_delete_workflow_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + + request = {} + client.delete_workflow(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.delete_workflow(request) + + # Establish 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_workflow_rest_required_fields(request_type=workflows.DeleteWorkflowRequest): + transport_class = transports.WorkflowsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workflow._get_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_workflow._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkflowsClient( + 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': "delete", + '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 + + response = client.delete_workflow(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workflow_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workflow._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_workflow_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workflows/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workflow(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workflows/*}" % client.transport._host, args[1]) + + +def test_delete_workflow_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflow( + workflows.DeleteWorkflowRequest(), + name='name_value', + ) + + +def test_update_workflow_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workflow in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workflow] = mock_rpc + + request = {} + client.update_workflow(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.update_workflow(request) + + # Establish 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_workflow_rest_required_fields(request_type=workflows.UpdateWorkflowRequest): + transport_class = transports.WorkflowsRestTransport + + 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_workflow._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_workflow._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 = WorkflowsClient( + 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': "patch", + '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 + + response = client.update_workflow(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workflow_rest_unset_required_fields(): + transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workflow._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("workflow", ))) + + +def test_update_workflow_rest_flattened(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + workflow=workflows.Workflow(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_workflow(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{workflow.name=projects/*/locations/*/workflows/*}" % client.transport._host, args[1]) + + +def test_update_workflow_rest_flattened_error(transport: str = 'rest'): + client = WorkflowsClient( + credentials=ga_credentials.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_workflow( + workflows.UpdateWorkflowRequest(), + workflow=workflows.Workflow(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.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkflowsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WorkflowsClient( + 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 = WorkflowsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkflowsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WorkflowsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkflowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WorkflowsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WorkflowsGrpcTransport, + transports.WorkflowsGrpcAsyncIOTransport, + transports.WorkflowsRestTransport, +]) +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 = WorkflowsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = WorkflowsClient( + 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_workflows_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + call.return_value = workflows.ListWorkflowsResponse() + client.list_workflows(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.ListWorkflowsRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + call.return_value = workflows.Workflow() + client.get_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.GetWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.CreateWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.DeleteWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_grpc(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.UpdateWorkflowRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = WorkflowsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = WorkflowsAsyncClient( + 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_workflows_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_workflows(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.ListWorkflowsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow( + name='name_value', + description='description_value', + state=workflows.Workflow.State.ACTIVE, + revision_id='revision_id_value', + service_account='service_account_value', + )) + await client.get_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.GetWorkflowRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__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.create_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.CreateWorkflowRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__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.delete_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.DeleteWorkflowRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): + client = WorkflowsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__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.update_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.UpdateWorkflowRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = WorkflowsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_workflows_rest_bad_request(request_type=workflows.ListWorkflowsRequest): + client = WorkflowsClient( + 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 + client.list_workflows(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.ListWorkflowsRequest, + dict, +]) +def test_list_workflows_rest_call_success(request_type): + client = WorkflowsClient( + 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 = workflows.ListWorkflowsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workflows.ListWorkflowsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_workflows(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkflowsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workflows_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "post_list_workflows") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_list_workflows") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.ListWorkflowsRequest.pb(workflows.ListWorkflowsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workflows.ListWorkflowsResponse.to_json(workflows.ListWorkflowsResponse()) + req.return_value.content = return_value + + request = workflows.ListWorkflowsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workflows.ListWorkflowsResponse() + + client.list_workflows(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workflow_rest_bad_request(request_type=workflows.GetWorkflowRequest): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 + client.get_workflow(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.GetWorkflowRequest, + dict, +]) +def test_get_workflow_rest_call_success(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 = workflows.Workflow( + name='name_value', + description='description_value', + state=workflows.Workflow.State.ACTIVE, + revision_id='revision_id_value', + service_account='service_account_value', + source_contents='source_contents_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 = workflows.Workflow.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_workflow(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workflows.Workflow) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == workflows.Workflow.State.ACTIVE + assert response.revision_id == 'revision_id_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workflow_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "post_get_workflow") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_get_workflow") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.GetWorkflowRequest.pb(workflows.GetWorkflowRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workflows.Workflow.to_json(workflows.Workflow()) + req.return_value.content = return_value + + request = workflows.GetWorkflowRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workflows.Workflow() + + client.get_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workflow_rest_bad_request(request_type=workflows.CreateWorkflowRequest): + client = WorkflowsClient( + 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 + client.create_workflow(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.CreateWorkflowRequest, + dict, +]) +def test_create_workflow_rest_call_success(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["workflow"] = {'name': 'name_value', 'description': 'description_value', 'state': 1, 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'revision_create_time': {}, 'labels': {}, 'service_account': 'service_account_value', 'source_contents': 'source_contents_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 = workflows.CreateWorkflowRequest.meta.fields["workflow"] + + 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["workflow"].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["workflow"][field])): + del request_init["workflow"][field][i][subfield] + else: + del request_init["workflow"][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 = 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 + response = client.create_workflow(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_create_workflow_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_create_workflow") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_create_workflow") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.CreateWorkflowRequest.pb(workflows.CreateWorkflowRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workflows.CreateWorkflowRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workflow_rest_bad_request(request_type=workflows.DeleteWorkflowRequest): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 + client.delete_workflow(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.DeleteWorkflowRequest, + dict, +]) +def test_delete_workflow_rest_call_success(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 = 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 + response = client.delete_workflow(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_delete_workflow_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_delete_workflow") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_delete_workflow") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.DeleteWorkflowRequest.pb(workflows.DeleteWorkflowRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workflows.DeleteWorkflowRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workflow_rest_bad_request(request_type=workflows.UpdateWorkflowRequest): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/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 + client.update_workflow(request) + + +@pytest.mark.parametrize("request_type", [ + workflows.UpdateWorkflowRequest, + dict, +]) +def test_update_workflow_rest_call_success(request_type): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/sample3'}} + request_init["workflow"] = {'name': 'projects/sample1/locations/sample2/workflows/sample3', 'description': 'description_value', 'state': 1, 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'revision_create_time': {}, 'labels': {}, 'service_account': 'service_account_value', 'source_contents': 'source_contents_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 = workflows.UpdateWorkflowRequest.meta.fields["workflow"] + + 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["workflow"].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["workflow"][field])): + del request_init["workflow"][field][i][subfield] + else: + del request_init["workflow"][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 = 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 + response = client.update_workflow(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_update_workflow_rest_interceptors(null_interceptor): + transport = transports.WorkflowsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), + ) + client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_update_workflow") as post, \ + mock.patch.object(transports.WorkflowsRestInterceptor, "pre_update_workflow") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workflows.UpdateWorkflowRequest.pb(workflows.UpdateWorkflowRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workflows.UpdateWorkflowRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = WorkflowsClient( + 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_workflows_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workflows), + '__call__') as call: + client.list_workflows(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.ListWorkflowsRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workflow), + '__call__') as call: + client.get_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.GetWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workflow), + '__call__') as call: + client.create_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.CreateWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workflow), + '__call__') as call: + client.delete_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.DeleteWorkflowRequest() + + assert args[0] == request_msg + + +# This 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_workflow_empty_call_rest(): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workflow), + '__call__') as call: + client.update_workflow(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workflows.UpdateWorkflowRequest() + + assert args[0] == request_msg + + +def test_workflows_rest_lro_client(): + client = WorkflowsClient( + 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 = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WorkflowsGrpcTransport, + ) + +def test_workflows_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WorkflowsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_workflows_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.workflows_v1beta.services.workflows.transports.WorkflowsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WorkflowsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_workflows', + 'get_workflow', + 'create_workflow', + 'delete_workflow', + 'update_workflow', + ) + 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_workflows_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workflows_v1beta.services.workflows.transports.WorkflowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkflowsTransport( + 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_workflows_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workflows_v1beta.services.workflows.transports.WorkflowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkflowsTransport() + adc.assert_called_once() + + +def test_workflows_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) + WorkflowsClient() + 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.WorkflowsGrpcTransport, + transports.WorkflowsGrpcAsyncIOTransport, + ], +) +def test_workflows_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.WorkflowsGrpcTransport, + transports.WorkflowsGrpcAsyncIOTransport, + transports.WorkflowsRestTransport, + ], +) +def test_workflows_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.WorkflowsGrpcTransport, grpc_helpers), + (transports.WorkflowsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_workflows_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( + "workflows.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="workflows.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) +def test_workflows_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_workflows_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.WorkflowsRestTransport ( + 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_workflows_host_no_port(transport_name): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workflows.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workflows.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workflows.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_workflows_host_with_port(transport_name): + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workflows.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workflows.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workflows.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_workflows_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WorkflowsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WorkflowsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_workflows._session + session2 = client2.transport.list_workflows._session + assert session1 != session2 + session1 = client1.transport.get_workflow._session + session2 = client2.transport.get_workflow._session + assert session1 != session2 + session1 = client1.transport.create_workflow._session + session2 = client2.transport.create_workflow._session + assert session1 != session2 + session1 = client1.transport.delete_workflow._session + session2 = client2.transport.delete_workflow._session + assert session1 != session2 + session1 = client1.transport.update_workflow._session + session2 = client2.transport.update_workflow._session + assert session1 != session2 +def test_workflows_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkflowsGrpcTransport( + 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_workflows_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkflowsGrpcAsyncIOTransport( + 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.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) +def test_workflows_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.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) +def test_workflows_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_workflows_grpc_lro_client(): + client = WorkflowsClient( + 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_workflows_grpc_lro_async_client(): + client = WorkflowsAsyncClient( + 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_workflow_path(): + project = "squid" + location = "clam" + workflow = "whelk" + expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + actual = WorkflowsClient.workflow_path(project, location, workflow) + assert expected == actual + + +def test_parse_workflow_path(): + expected = { + "project": "octopus", + "location": "oyster", + "workflow": "nudibranch", + } + path = WorkflowsClient.workflow_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.parse_workflow_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WorkflowsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = WorkflowsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = WorkflowsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = WorkflowsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WorkflowsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = WorkflowsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = WorkflowsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = WorkflowsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.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 = WorkflowsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = WorkflowsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WorkflowsClient.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.WorkflowsTransport, '_prep_wrapped_messages') as prep: + client = WorkflowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WorkflowsTransport, '_prep_wrapped_messages') as prep: + transport_class = WorkflowsClient.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 = WorkflowsClient( + 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 = WorkflowsAsyncClient( + 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 = WorkflowsClient( + 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 = WorkflowsClient( + 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", [ + (WorkflowsClient, transports.WorkflowsGrpcTransport), + (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport), +]) +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-cloud-workstations/v1/.coveragerc b/owl-bot-staging/google-cloud-workstations/v1/.coveragerc new file mode 100644 index 000000000000..ee1a17c3e2ca --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/workstations/__init__.py + google/cloud/workstations/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-cloud-workstations/v1/.flake8 b/owl-bot-staging/google-cloud-workstations/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1/MANIFEST.in b/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in new file mode 100644 index 000000000000..81d49b157276 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/workstations *.py +recursive-include google/cloud/workstations_v1 *.py diff --git a/owl-bot-staging/google-cloud-workstations/v1/README.rst b/owl-bot-staging/google-cloud-workstations/v1/README.rst new file mode 100644 index 000000000000..48a711be018f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Workstations 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 Cloud Workstations 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-cloud-workstations/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-workstations/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/conf.py b/owl-bot-staging/google-cloud-workstations/v1/docs/conf.py new file mode 100644 index 000000000000..65ff2ad5ae85 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations 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-cloud-workstations" +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 Cloud 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-cloud-workstations-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-cloud-workstations.tex", + u"google-cloud-workstations 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-cloud-workstations", + u"Google Cloud Workstations 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-cloud-workstations", + u"google-cloud-workstations Documentation", + author, + "google-cloud-workstations", + "GAPIC library for Google Cloud Workstations 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-cloud-workstations/v1/docs/index.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst new file mode 100644 index 000000000000..48bce1a5d563 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + workstations_v1/services_ + workstations_v1/types_ diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services_.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services_.rst new file mode 100644 index 000000000000..4d34f8795a80 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Workstations v1 API +============================================= +.. toctree:: + :maxdepth: 2 + + workstations diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types_.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types_.rst new file mode 100644 index 000000000000..f2d1f8aae76b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Workstations v1 API +========================================== + +.. automodule:: google.cloud.workstations_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst new file mode 100644 index 000000000000..1a3ded4d683d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst @@ -0,0 +1,10 @@ +Workstations +------------------------------ + +.. automodule:: google.cloud.workstations_v1.services.workstations + :members: + :inherited-members: + +.. automodule:: google.cloud.workstations_v1.services.workstations.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py new file mode 100644 index 000000000000..6323e1047e2f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workstations import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.workstations_v1.services.workstations.client import WorkstationsClient +from google.cloud.workstations_v1.services.workstations.async_client import WorkstationsAsyncClient + +from google.cloud.workstations_v1.types.workstations import CreateWorkstationClusterRequest +from google.cloud.workstations_v1.types.workstations import CreateWorkstationConfigRequest +from google.cloud.workstations_v1.types.workstations import CreateWorkstationRequest +from google.cloud.workstations_v1.types.workstations import DeleteWorkstationClusterRequest +from google.cloud.workstations_v1.types.workstations import DeleteWorkstationConfigRequest +from google.cloud.workstations_v1.types.workstations import DeleteWorkstationRequest +from google.cloud.workstations_v1.types.workstations import GenerateAccessTokenRequest +from google.cloud.workstations_v1.types.workstations import GenerateAccessTokenResponse +from google.cloud.workstations_v1.types.workstations import GetWorkstationClusterRequest +from google.cloud.workstations_v1.types.workstations import GetWorkstationConfigRequest +from google.cloud.workstations_v1.types.workstations import GetWorkstationRequest +from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationConfigsRequest +from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationConfigsResponse +from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationsRequest +from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationsResponse +from google.cloud.workstations_v1.types.workstations import ListWorkstationClustersRequest +from google.cloud.workstations_v1.types.workstations import ListWorkstationClustersResponse +from google.cloud.workstations_v1.types.workstations import ListWorkstationConfigsRequest +from google.cloud.workstations_v1.types.workstations import ListWorkstationConfigsResponse +from google.cloud.workstations_v1.types.workstations import ListWorkstationsRequest +from google.cloud.workstations_v1.types.workstations import ListWorkstationsResponse +from google.cloud.workstations_v1.types.workstations import OperationMetadata +from google.cloud.workstations_v1.types.workstations import StartWorkstationRequest +from google.cloud.workstations_v1.types.workstations import StopWorkstationRequest +from google.cloud.workstations_v1.types.workstations import UpdateWorkstationClusterRequest +from google.cloud.workstations_v1.types.workstations import UpdateWorkstationConfigRequest +from google.cloud.workstations_v1.types.workstations import UpdateWorkstationRequest +from google.cloud.workstations_v1.types.workstations import Workstation +from google.cloud.workstations_v1.types.workstations import WorkstationCluster +from google.cloud.workstations_v1.types.workstations import WorkstationConfig + +__all__ = ('WorkstationsClient', + 'WorkstationsAsyncClient', + 'CreateWorkstationClusterRequest', + 'CreateWorkstationConfigRequest', + 'CreateWorkstationRequest', + 'DeleteWorkstationClusterRequest', + 'DeleteWorkstationConfigRequest', + 'DeleteWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GetWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'OperationMetadata', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'UpdateWorkstationClusterRequest', + 'UpdateWorkstationConfigRequest', + 'UpdateWorkstationRequest', + 'Workstation', + 'WorkstationCluster', + 'WorkstationConfig', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/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-cloud-workstations/v1/google/cloud/workstations/py.typed b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed new file mode 100644 index 000000000000..04170223dff9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py new file mode 100644 index 000000000000..50e519bf99c1 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workstations_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.workstations import WorkstationsClient +from .services.workstations import WorkstationsAsyncClient + +from .types.workstations import CreateWorkstationClusterRequest +from .types.workstations import CreateWorkstationConfigRequest +from .types.workstations import CreateWorkstationRequest +from .types.workstations import DeleteWorkstationClusterRequest +from .types.workstations import DeleteWorkstationConfigRequest +from .types.workstations import DeleteWorkstationRequest +from .types.workstations import GenerateAccessTokenRequest +from .types.workstations import GenerateAccessTokenResponse +from .types.workstations import GetWorkstationClusterRequest +from .types.workstations import GetWorkstationConfigRequest +from .types.workstations import GetWorkstationRequest +from .types.workstations import ListUsableWorkstationConfigsRequest +from .types.workstations import ListUsableWorkstationConfigsResponse +from .types.workstations import ListUsableWorkstationsRequest +from .types.workstations import ListUsableWorkstationsResponse +from .types.workstations import ListWorkstationClustersRequest +from .types.workstations import ListWorkstationClustersResponse +from .types.workstations import ListWorkstationConfigsRequest +from .types.workstations import ListWorkstationConfigsResponse +from .types.workstations import ListWorkstationsRequest +from .types.workstations import ListWorkstationsResponse +from .types.workstations import OperationMetadata +from .types.workstations import StartWorkstationRequest +from .types.workstations import StopWorkstationRequest +from .types.workstations import UpdateWorkstationClusterRequest +from .types.workstations import UpdateWorkstationConfigRequest +from .types.workstations import UpdateWorkstationRequest +from .types.workstations import Workstation +from .types.workstations import WorkstationCluster +from .types.workstations import WorkstationConfig + +__all__ = ( + 'WorkstationsAsyncClient', +'CreateWorkstationClusterRequest', +'CreateWorkstationConfigRequest', +'CreateWorkstationRequest', +'DeleteWorkstationClusterRequest', +'DeleteWorkstationConfigRequest', +'DeleteWorkstationRequest', +'GenerateAccessTokenRequest', +'GenerateAccessTokenResponse', +'GetWorkstationClusterRequest', +'GetWorkstationConfigRequest', +'GetWorkstationRequest', +'ListUsableWorkstationConfigsRequest', +'ListUsableWorkstationConfigsResponse', +'ListUsableWorkstationsRequest', +'ListUsableWorkstationsResponse', +'ListWorkstationClustersRequest', +'ListWorkstationClustersResponse', +'ListWorkstationConfigsRequest', +'ListWorkstationConfigsResponse', +'ListWorkstationsRequest', +'ListWorkstationsResponse', +'OperationMetadata', +'StartWorkstationRequest', +'StopWorkstationRequest', +'UpdateWorkstationClusterRequest', +'UpdateWorkstationConfigRequest', +'UpdateWorkstationRequest', +'Workstation', +'WorkstationCluster', +'WorkstationConfig', +'WorkstationsClient', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json new file mode 100644 index 000000000000..27a21c6d848b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json @@ -0,0 +1,328 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.workstations_v1", + "protoPackage": "google.cloud.workstations.v1", + "schema": "1.0", + "services": { + "Workstations": { + "clients": { + "grpc": { + "libraryClient": "WorkstationsClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WorkstationsAsyncClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + }, + "rest": { + "libraryClient": "WorkstationsClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_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-cloud-workstations/v1/google/cloud/workstations_v1/py.typed b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed new file mode 100644 index 000000000000..04170223dff9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_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-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py new file mode 100644 index 000000000000..e8958d8c0d6d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__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 WorkstationsClient +from .async_client import WorkstationsAsyncClient + +__all__ = ( + 'WorkstationsClient', + 'WorkstationsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py new file mode 100644 index 000000000000..1cd023b1e894 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py @@ -0,0 +1,3183 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.workstations_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.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.services.workstations import pagers +from google.cloud.workstations_v1.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .client import WorkstationsClient + + +class WorkstationsAsyncClient: + """Service for interacting with Cloud Workstations.""" + + _client: WorkstationsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WorkstationsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WorkstationsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WorkstationsClient._DEFAULT_UNIVERSE + + workstation_path = staticmethod(WorkstationsClient.workstation_path) + parse_workstation_path = staticmethod(WorkstationsClient.parse_workstation_path) + workstation_cluster_path = staticmethod(WorkstationsClient.workstation_cluster_path) + parse_workstation_cluster_path = staticmethod(WorkstationsClient.parse_workstation_cluster_path) + workstation_config_path = staticmethod(WorkstationsClient.workstation_config_path) + parse_workstation_config_path = staticmethod(WorkstationsClient.parse_workstation_config_path) + common_billing_account_path = staticmethod(WorkstationsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WorkstationsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WorkstationsClient.common_folder_path) + parse_common_folder_path = staticmethod(WorkstationsClient.parse_common_folder_path) + common_organization_path = staticmethod(WorkstationsClient.common_organization_path) + parse_common_organization_path = staticmethod(WorkstationsClient.parse_common_organization_path) + common_project_path = staticmethod(WorkstationsClient.common_project_path) + parse_common_project_path = staticmethod(WorkstationsClient.parse_common_project_path) + common_location_path = staticmethod(WorkstationsClient.common_location_path) + parse_common_location_path = staticmethod(WorkstationsClient.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: + WorkstationsAsyncClient: The constructed client. + """ + return WorkstationsClient.from_service_account_info.__func__(WorkstationsAsyncClient, 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: + WorkstationsAsyncClient: The constructed client. + """ + return WorkstationsClient.from_service_account_file.__func__(WorkstationsAsyncClient, 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 WorkstationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WorkstationsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkstationsTransport: 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 = WorkstationsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WorkstationsTransport, Callable[..., WorkstationsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workstations 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,WorkstationsTransport,Callable[..., WorkstationsTransport]]]): + 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 WorkstationsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WorkstationsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_workstation_cluster(self, + request: Optional[Union[workstations.GetWorkstationClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.WorkstationCluster: + r"""Returns the requested workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationClusterRequest, dict]]): + The request object. Request message for + GetWorkstationCluster. + name (:class:`str`): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.types.WorkstationCluster: + A workstation cluster resource in the + Cloud Workstations API. + Defines a group of workstations in a + particular region and the VPC network + they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationClusterRequest): + request = workstations.GetWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_cluster] + + # Certain fields should be provided within 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_workstation_clusters(self, + request: Optional[Union[workstations.ListWorkstationClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationClustersAsyncPager: + r"""Returns all workstation clusters in the specified + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationClustersRequest, dict]]): + The request object. Request message for + ListWorkstationClusters. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationClustersAsyncPager: + Response message for + ListWorkstationClusters. + 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, workstations.ListWorkstationClustersRequest): + request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] + + # Certain fields should be provided within 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.ListWorkstationClustersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation_cluster(self, + request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_cluster: Optional[workstations.WorkstationCluster] = None, + workstation_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationClusterRequest, dict]]): + The request object. Message for creating a + CreateWorkstationCluster. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster (:class:`google.cloud.workstations_v1.types.WorkstationCluster`): + Required. Workstation cluster to + create. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster_id (:class:`str`): + Required. ID to use for the + workstation cluster. + + This corresponds to the ``workstation_cluster_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation_cluster, workstation_cluster_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, workstations.CreateWorkstationClusterRequest): + request = workstations.CreateWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + if workstation_cluster_id is not None: + request.workstation_cluster_id = workstation_cluster_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_workstation_cluster] + + # Certain fields should be provided within 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation_cluster(self, + request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, + *, + workstation_cluster: Optional[workstations.WorkstationCluster] = 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, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an existing workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest, dict]]): + The request object. Request message for + UpdateWorkstationCluster. + workstation_cluster (:class:`google.cloud.workstations_v1.types.WorkstationCluster`): + Required. Workstation cluster to + update. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask that specifies which + fields in the workstation cluster should + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_cluster, 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, workstations.UpdateWorkstationClusterRequest): + request = workstations.UpdateWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + 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_workstation_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_cluster.name", request.workstation_cluster.name), + )), + ) + + # 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation_cluster(self, + request: Optional[Union[workstations.DeleteWorkstationClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest, dict]]): + The request object. Message for deleting a workstation + cluster. + name (:class:`str`): + Required. Name of the workstation + cluster to delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationClusterRequest): + request = workstations.DeleteWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_cluster] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_workstation_config(self, + request: Optional[Union[workstations.GetWorkstationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.WorkstationConfig: + r"""Returns the requested workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_get_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationConfigRequest, dict]]): + The request object. Request message for + GetWorkstationConfig. + name (:class:`str`): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.types.WorkstationConfig: + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationConfigRequest): + request = workstations.GetWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_config] + + # Certain fields should be provided within 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_workstation_configs(self, + request: Optional[Union[workstations.ListWorkstationConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationConfigsAsyncPager: + r"""Returns all workstation configurations in the + specified cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationConfigsRequest, dict]]): + The request object. Request message for + ListWorkstationConfigs. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationConfigsAsyncPager: + Response message for + ListWorkstationConfigs. + 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, workstations.ListWorkstationConfigsRequest): + request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] + + # Certain fields should be provided within 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.ListWorkstationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_usable_workstation_configs(self, + request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUsableWorkstationConfigsAsyncPager: + r"""Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest, dict]]): + The request object. Request message for + ListUsableWorkstationConfigs. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager: + Response message for + ListUsableWorkstationConfigs. + 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, workstations.ListUsableWorkstationConfigsRequest): + request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] + + # Certain fields should be provided within 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.ListUsableWorkstationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation_config(self, + request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_config: Optional[workstations.WorkstationConfig] = None, + workstation_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_create_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationConfigRequest, dict]]): + The request object. Message for creating a + CreateWorkstationConfig. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config (:class:`google.cloud.workstations_v1.types.WorkstationConfig`): + Required. Config to create. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config_id (:class:`str`): + Required. ID to use for the + workstation configuration. + + This corresponds to the ``workstation_config_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation_config, workstation_config_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, workstations.CreateWorkstationConfigRequest): + request = workstations.CreateWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_config is not None: + request.workstation_config = workstation_config + if workstation_config_id is not None: + request.workstation_config_id = workstation_config_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_workstation_config] + + # Certain fields should be provided within 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation_config(self, + request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, + *, + workstation_config: Optional[workstations.WorkstationConfig] = 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, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an existing workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_update_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest, dict]]): + The request object. Request message for + UpdateWorkstationConfig. + workstation_config (:class:`google.cloud.workstations_v1.types.WorkstationConfig`): + Required. Config to update. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask specifying which + fields in the workstation configuration + should 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_config, 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, workstations.UpdateWorkstationConfigRequest): + request = workstations.UpdateWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_config is not None: + request.workstation_config = workstation_config + 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_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_config.name", request.workstation_config.name), + )), + ) + + # 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation_config(self, + request: Optional[Union[workstations.DeleteWorkstationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_delete_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest, dict]]): + The request object. Message for deleting a workstation + configuration. + name (:class:`str`): + Required. Name of the workstation + configuration to delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationConfigRequest): + request = workstations.DeleteWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_config] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_workstation(self, + request: Optional[Union[workstations.GetWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.Workstation: + r"""Returns the requested workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_get_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationRequest, dict]]): + The request object. Request message for GetWorkstation. + name (:class:`str`): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.types.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationRequest): + request = workstations.GetWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation] + + # Certain fields should be provided within 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_workstations(self, + request: Optional[Union[workstations.ListWorkstationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationsAsyncPager: + r"""Returns all Workstations using the specified + workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_workstations(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationsRequest, dict]]): + The request object. Request message for ListWorkstations. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationsAsyncPager: + Response message for + ListWorkstations. + 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, workstations.ListWorkstationsRequest): + request = workstations.ListWorkstationsRequest(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_workstations] + + # Certain fields should be provided within 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.ListWorkstationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_usable_workstations(self, + request: Optional[Union[workstations.ListUsableWorkstationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUsableWorkstationsAsyncPager: + r"""Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_usable_workstations(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListUsableWorkstationsRequest, dict]]): + The request object. Request message for + ListUsableWorkstations. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationsAsyncPager: + Response message for + ListUsableWorkstations. + 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, workstations.ListUsableWorkstationsRequest): + request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] + + # Certain fields should be provided within 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.ListUsableWorkstationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation(self, + request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation: Optional[workstations.Workstation] = None, + workstation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_create_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationRequest, dict]]): + The request object. Message for creating a + CreateWorkstation. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation (:class:`google.cloud.workstations_v1.types.Workstation`): + Required. Workstation to create. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_id (:class:`str`): + Required. ID to use for the + workstation. + + This corresponds to the ``workstation_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation, workstation_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, workstations.CreateWorkstationRequest): + request = workstations.CreateWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation is not None: + request.workstation = workstation + if workstation_id is not None: + request.workstation_id = workstation_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_workstation] + + # Certain fields should be provided within 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation(self, + request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, + *, + workstation: Optional[workstations.Workstation] = 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, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an existing workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_update_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationRequest, dict]]): + The request object. Request message for + UpdateWorkstation. + workstation (:class:`google.cloud.workstations_v1.types.Workstation`): + Required. Workstation to update. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask specifying which + fields in the workstation configuration + should 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation, 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, workstations.UpdateWorkstationRequest): + request = workstations.UpdateWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + 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_workstation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation.name", request.workstation.name), + )), + ) + + # 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation(self, + request: Optional[Union[workstations.DeleteWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_delete_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationRequest, dict]]): + The request object. Request message for + DeleteWorkstation. + name (:class:`str`): + Required. Name of the workstation to + delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationRequest): + request = workstations.DeleteWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def start_workstation(self, + request: Optional[Union[workstations.StartWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts running a workstation so that users can + connect to it. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_start_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.StartWorkstationRequest, dict]]): + The request object. Request message for StartWorkstation. + name (:class:`str`): + Required. Name of the workstation to + start. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.StartWorkstationRequest): + request = workstations.StartWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.start_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def stop_workstation(self, + request: Optional[Union[workstations.StopWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Stops running a workstation, reducing costs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_stop_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.StopWorkstationRequest, dict]]): + The request object. Request message for StopWorkstation. + name (:class:`str`): + Required. Name of the workstation to + stop. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.StopWorkstationRequest): + request = workstations.StopWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.stop_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_access_token(self, + request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, + *, + workstation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.GenerateAccessTokenResponse: + r"""Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_generate_access_token(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = await client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.GenerateAccessTokenRequest, dict]]): + The request object. Request message for + GenerateAccessToken. + workstation (:class:`str`): + Required. Name of the workstation for + which the access token should be + generated. + + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_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. + + Returns: + google.cloud.workstations_v1.types.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, workstations.GenerateAccessTokenRequest): + request = workstations.GenerateAccessTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation", request.workstation), + )), + ) + + # Validate the universe domain. + self._client._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_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # 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.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within 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_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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # 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.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # 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.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._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_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._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) -> "WorkstationsAsyncClient": + 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__ = ( + "WorkstationsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py new file mode 100644 index 000000000000..61b0aa5acd49 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py @@ -0,0 +1,3536 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.workstations_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 + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.services.workstations import pagers +from google.cloud.workstations_v1.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WorkstationsGrpcTransport +from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .transports.rest import WorkstationsRestTransport + + +class WorkstationsClientMeta(type): + """Metaclass for the Workstations 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[WorkstationsTransport]] + _transport_registry["grpc"] = WorkstationsGrpcTransport + _transport_registry["grpc_asyncio"] = WorkstationsGrpcAsyncIOTransport + _transport_registry["rest"] = WorkstationsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WorkstationsTransport]: + """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 WorkstationsClient(metaclass=WorkstationsClientMeta): + """Service for interacting with Cloud Workstations.""" + + @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 = "workstations.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "workstations.{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: + WorkstationsClient: 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: + WorkstationsClient: 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) -> WorkstationsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkstationsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def workstation_path(project: str,location: str,workstation_cluster: str,workstation_config: str,workstation: str,) -> str: + """Returns a fully-qualified workstation string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) + + @staticmethod + def parse_workstation_path(path: str) -> Dict[str,str]: + """Parses a workstation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?P.+?)/workstations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workstation_cluster_path(project: str,location: str,workstation_cluster: str,) -> str: + """Returns a fully-qualified workstation_cluster string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) + + @staticmethod + def parse_workstation_cluster_path(path: str) -> Dict[str,str]: + """Parses a workstation_cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workstation_config_path(project: str,location: str,workstation_cluster: str,workstation_config: str,) -> str: + """Returns a fully-qualified workstation_config string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) + + @staticmethod + def parse_workstation_config_path(path: str) -> Dict[str,str]: + """Parses a workstation_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?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 = WorkstationsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = WorkstationsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WorkstationsClient._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 = WorkstationsClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = WorkstationsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + WorkstationsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, WorkstationsTransport, Callable[..., WorkstationsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workstations client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,WorkstationsTransport,Callable[..., WorkstationsTransport]]]): + 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 WorkstationsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WorkstationsClient._read_environment_variables() + self._client_cert_source = WorkstationsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = WorkstationsClient._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 + + 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, WorkstationsTransport) + if transport_provided: + # transport is a WorkstationsTransport 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(WorkstationsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + WorkstationsClient._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[WorkstationsTransport], Callable[..., WorkstationsTransport]] = ( + WorkstationsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WorkstationsTransport], 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, + ) + + def get_workstation_cluster(self, + request: Optional[Union[workstations.GetWorkstationClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.WorkstationCluster: + r"""Returns the requested workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.GetWorkstationClusterRequest, dict]): + The request object. Request message for + GetWorkstationCluster. + name (str): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.types.WorkstationCluster: + A workstation cluster resource in the + Cloud Workstations API. + Defines a group of workstations in a + particular region and the VPC network + they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationClusterRequest): + request = workstations.GetWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_cluster] + + # Certain fields should be provided within 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_workstation_clusters(self, + request: Optional[Union[workstations.ListWorkstationClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationClustersPager: + r"""Returns all workstation clusters in the specified + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListWorkstationClustersRequest, dict]): + The request object. Request message for + ListWorkstationClusters. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationClustersPager: + Response message for + ListWorkstationClusters. + 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, workstations.ListWorkstationClustersRequest): + request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] + + # Certain fields should be provided within 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.ListWorkstationClustersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation_cluster(self, + request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_cluster: Optional[workstations.WorkstationCluster] = None, + workstation_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.CreateWorkstationClusterRequest, dict]): + The request object. Message for creating a + CreateWorkstationCluster. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): + Required. Workstation cluster to + create. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster_id (str): + Required. ID to use for the + workstation cluster. + + This corresponds to the ``workstation_cluster_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation_cluster, workstation_cluster_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, workstations.CreateWorkstationClusterRequest): + request = workstations.CreateWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + if workstation_cluster_id is not None: + request.workstation_cluster_id = workstation_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation_cluster] + + # Certain fields should be provided within 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation_cluster(self, + request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, + *, + workstation_cluster: Optional[workstations.WorkstationCluster] = 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, str]] = (), + ) -> operation.Operation: + r"""Updates an existing workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest, dict]): + The request object. Request message for + UpdateWorkstationCluster. + workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): + Required. Workstation cluster to + update. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask that specifies which + fields in the workstation cluster should + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_cluster, 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, workstations.UpdateWorkstationClusterRequest): + request = workstations.UpdateWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + 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_workstation_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_cluster.name", request.workstation_cluster.name), + )), + ) + + # 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation_cluster(self, + request: Optional[Union[workstations.DeleteWorkstationClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest, dict]): + The request object. Message for deleting a workstation + cluster. + name (str): + Required. Name of the workstation + cluster to delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationClusterRequest): + request = workstations.DeleteWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_cluster] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_workstation_config(self, + request: Optional[Union[workstations.GetWorkstationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.WorkstationConfig: + r"""Returns the requested workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_get_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.GetWorkstationConfigRequest, dict]): + The request object. Request message for + GetWorkstationConfig. + name (str): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.types.WorkstationConfig: + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationConfigRequest): + request = workstations.GetWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_config] + + # Certain fields should be provided within 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_workstation_configs(self, + request: Optional[Union[workstations.ListWorkstationConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationConfigsPager: + r"""Returns all workstation configurations in the + specified cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListWorkstationConfigsRequest, dict]): + The request object. Request message for + ListWorkstationConfigs. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationConfigsPager: + Response message for + ListWorkstationConfigs. + 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, workstations.ListWorkstationConfigsRequest): + request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] + + # Certain fields should be provided within 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.ListWorkstationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_usable_workstation_configs(self, + request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUsableWorkstationConfigsPager: + r"""Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest, dict]): + The request object. Request message for + ListUsableWorkstationConfigs. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsPager: + Response message for + ListUsableWorkstationConfigs. + 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, workstations.ListUsableWorkstationConfigsRequest): + request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] + + # Certain fields should be provided within 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.ListUsableWorkstationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation_config(self, + request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_config: Optional[workstations.WorkstationConfig] = None, + workstation_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_create_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.CreateWorkstationConfigRequest, dict]): + The request object. Message for creating a + CreateWorkstationConfig. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): + Required. Config to create. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config_id (str): + Required. ID to use for the + workstation configuration. + + This corresponds to the ``workstation_config_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation_config, workstation_config_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, workstations.CreateWorkstationConfigRequest): + request = workstations.CreateWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_config is not None: + request.workstation_config = workstation_config + if workstation_config_id is not None: + request.workstation_config_id = workstation_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation_config] + + # Certain fields should be provided within 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation_config(self, + request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, + *, + workstation_config: Optional[workstations.WorkstationConfig] = 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, str]] = (), + ) -> operation.Operation: + r"""Updates an existing workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_update_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest, dict]): + The request object. Request message for + UpdateWorkstationConfig. + workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): + Required. Config to update. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which + fields in the workstation configuration + should 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_config, 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, workstations.UpdateWorkstationConfigRequest): + request = workstations.UpdateWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_config is not None: + request.workstation_config = workstation_config + 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_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_config.name", request.workstation_config.name), + )), + ) + + # 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation_config(self, + request: Optional[Union[workstations.DeleteWorkstationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_delete_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest, dict]): + The request object. Message for deleting a workstation + configuration. + name (str): + Required. Name of the workstation + configuration to delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationConfigRequest): + request = workstations.DeleteWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_config] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_workstation(self, + request: Optional[Union[workstations.GetWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.Workstation: + r"""Returns the requested workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_get_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.GetWorkstationRequest, dict]): + The request object. Request message for GetWorkstation. + name (str): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.types.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationRequest): + request = workstations.GetWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation] + + # Certain fields should be provided within 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_workstations(self, + request: Optional[Union[workstations.ListWorkstationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationsPager: + r"""Returns all Workstations using the specified + workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_workstations(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListWorkstationsRequest, dict]): + The request object. Request message for ListWorkstations. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationsPager: + Response message for + ListWorkstations. + 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, workstations.ListWorkstationsRequest): + request = workstations.ListWorkstationsRequest(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_workstations] + + # Certain fields should be provided within 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.ListWorkstationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_usable_workstations(self, + request: Optional[Union[workstations.ListUsableWorkstationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUsableWorkstationsPager: + r"""Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_usable_workstations(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListUsableWorkstationsRequest, dict]): + The request object. Request message for + ListUsableWorkstations. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationsPager: + Response message for + ListUsableWorkstations. + 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, workstations.ListUsableWorkstationsRequest): + request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] + + # Certain fields should be provided within 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.ListUsableWorkstationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation(self, + request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation: Optional[workstations.Workstation] = None, + workstation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_create_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.CreateWorkstationRequest, dict]): + The request object. Message for creating a + CreateWorkstation. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation (google.cloud.workstations_v1.types.Workstation): + Required. Workstation to create. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_id (str): + Required. ID to use for the + workstation. + + This corresponds to the ``workstation_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation, workstation_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, workstations.CreateWorkstationRequest): + request = workstations.CreateWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation is not None: + request.workstation = workstation + if workstation_id is not None: + request.workstation_id = workstation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation] + + # Certain fields should be provided within 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation(self, + request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, + *, + workstation: Optional[workstations.Workstation] = 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, str]] = (), + ) -> operation.Operation: + r"""Updates an existing workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_update_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.UpdateWorkstationRequest, dict]): + The request object. Request message for + UpdateWorkstation. + workstation (google.cloud.workstations_v1.types.Workstation): + Required. Workstation to update. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which + fields in the workstation configuration + should 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation, 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, workstations.UpdateWorkstationRequest): + request = workstations.UpdateWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + 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_workstation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation.name", request.workstation.name), + )), + ) + + # 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation(self, + request: Optional[Union[workstations.DeleteWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_delete_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.DeleteWorkstationRequest, dict]): + The request object. Request message for + DeleteWorkstation. + name (str): + Required. Name of the workstation to + delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationRequest): + request = workstations.DeleteWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def start_workstation(self, + request: Optional[Union[workstations.StartWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts running a workstation so that users can + connect to it. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_start_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.StartWorkstationRequest, dict]): + The request object. Request message for StartWorkstation. + name (str): + Required. Name of the workstation to + start. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.StartWorkstationRequest): + request = workstations.StartWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.start_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def stop_workstation(self, + request: Optional[Union[workstations.StopWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Stops running a workstation, reducing costs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_stop_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.StopWorkstationRequest, dict]): + The request object. Request message for StopWorkstation. + name (str): + Required. Name of the workstation to + stop. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.StopWorkstationRequest): + request = workstations.StopWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.stop_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_access_token(self, + request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, + *, + workstation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.GenerateAccessTokenResponse: + r"""Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_generate_access_token(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.GenerateAccessTokenRequest, dict]): + The request object. Request message for + GenerateAccessToken. + workstation (str): + Required. Name of the workstation for + which the access token should be + generated. + + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.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. + + Returns: + google.cloud.workstations_v1.types.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, workstations.GenerateAccessTokenRequest): + request = workstations.GenerateAccessTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation", request.workstation), + )), + ) + + # Validate the universe 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) -> "WorkstationsClient": + 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 list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.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. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # 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.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within 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_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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.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. + Returns: + None + """ + # 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.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.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. + Returns: + None + """ + # 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.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.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. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe 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_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.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. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.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. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the 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__ = ( + "WorkstationsClient", +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py new file mode 100644 index 000000000000..8ab2db0999ce --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py @@ -0,0 +1,702 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workstations_v1.types import workstations + + +class ListWorkstationClustersPager: + """A pager for iterating through ``list_workstation_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstationClusters`` requests and continue to iterate + through the ``workstation_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListWorkstationClustersResponse], + request: workstations.ListWorkstationClustersRequest, + response: workstations.ListWorkstationClustersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListWorkstationClustersRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationClustersResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationClustersRequest(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[workstations.ListWorkstationClustersResponse]: + 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[workstations.WorkstationCluster]: + for page in self.pages: + yield from page.workstation_clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationClustersAsyncPager: + """A pager for iterating through ``list_workstation_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstationClusters`` requests and continue to iterate + through the ``workstation_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` + attributes are available on the 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[workstations.ListWorkstationClustersResponse]], + request: workstations.ListWorkstationClustersRequest, + response: workstations.ListWorkstationClustersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListWorkstationClustersRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationClustersResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationClustersRequest(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[workstations.ListWorkstationClustersResponse]: + 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[workstations.WorkstationCluster]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationConfigsPager: + """A pager for iterating through ``list_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListWorkstationConfigsResponse], + request: workstations.ListWorkstationConfigsRequest, + response: workstations.ListWorkstationConfigsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationConfigsRequest(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[workstations.ListWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + for page in self.pages: + yield from page.workstation_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationConfigsAsyncPager: + """A pager for iterating through ``list_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` + attributes are available on the 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[workstations.ListWorkstationConfigsResponse]], + request: workstations.ListWorkstationConfigsRequest, + response: workstations.ListWorkstationConfigsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationConfigsRequest(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[workstations.ListWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationConfigsPager: + """A pager for iterating through ``list_usable_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsableWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListUsableWorkstationConfigsResponse], + request: workstations.ListUsableWorkstationConfigsRequest, + response: workstations.ListUsableWorkstationConfigsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListUsableWorkstationConfigsRequest(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[workstations.ListUsableWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + for page in self.pages: + yield from page.workstation_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationConfigsAsyncPager: + """A pager for iterating through ``list_usable_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsableWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` + attributes are available on the 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[workstations.ListUsableWorkstationConfigsResponse]], + request: workstations.ListUsableWorkstationConfigsRequest, + response: workstations.ListUsableWorkstationConfigsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListUsableWorkstationConfigsRequest(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[workstations.ListUsableWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationsPager: + """A pager for iterating through ``list_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListWorkstationsResponse], + request: workstations.ListWorkstationsRequest, + response: workstations.ListWorkstationsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationsRequest(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[workstations.ListWorkstationsResponse]: + 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[workstations.Workstation]: + for page in self.pages: + yield from page.workstations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationsAsyncPager: + """A pager for iterating through ``list_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` + attributes are available on the 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[workstations.ListWorkstationsResponse]], + request: workstations.ListWorkstationsRequest, + response: workstations.ListWorkstationsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationsRequest(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[workstations.ListWorkstationsResponse]: + 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[workstations.Workstation]: + async def async_generator(): + async for page in self.pages: + for response in page.workstations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationsPager: + """A pager for iterating through ``list_usable_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsableWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListUsableWorkstationsResponse], + request: workstations.ListUsableWorkstationsRequest, + response: workstations.ListUsableWorkstationsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListUsableWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListUsableWorkstationsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListUsableWorkstationsRequest(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[workstations.ListUsableWorkstationsResponse]: + 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[workstations.Workstation]: + for page in self.pages: + yield from page.workstations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationsAsyncPager: + """A pager for iterating through ``list_usable_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsableWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` + attributes are available on the 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[workstations.ListUsableWorkstationsResponse]], + request: workstations.ListUsableWorkstationsRequest, + response: workstations.ListUsableWorkstationsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1.types.ListUsableWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListUsableWorkstationsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListUsableWorkstationsRequest(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[workstations.ListUsableWorkstationsResponse]: + 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[workstations.Workstation]: + async def async_generator(): + async for page in self.pages: + for response in page.workstations: + 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-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/README.rst b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/README.rst new file mode 100644 index 000000000000..e25a7cc4b1cf --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`WorkstationsTransport` is the ABC for all transports. +- public child `WorkstationsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `WorkstationsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseWorkstationsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `WorkstationsRestTransport` 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-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py new file mode 100644 index 000000000000..3ae547e57985 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/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 WorkstationsTransport +from .grpc import WorkstationsGrpcTransport +from .grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .rest import WorkstationsRestTransport +from .rest import WorkstationsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WorkstationsTransport]] +_transport_registry['grpc'] = WorkstationsGrpcTransport +_transport_registry['grpc_asyncio'] = WorkstationsGrpcAsyncIOTransport +_transport_registry['rest'] = WorkstationsRestTransport + +__all__ = ( + 'WorkstationsTransport', + 'WorkstationsGrpcTransport', + 'WorkstationsGrpcAsyncIOTransport', + 'WorkstationsRestTransport', + 'WorkstationsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py new file mode 100644 index 000000000000..dbd5003a5aab --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.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 abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.workstations_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.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WorkstationsTransport(abc.ABC): + """Abstract transport class for Workstations.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'workstations.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: 'workstations.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_workstation_cluster: gapic_v1.method.wrap_method( + self.get_workstation_cluster, + 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_workstation_clusters: gapic_v1.method.wrap_method( + self.list_workstation_clusters, + 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.create_workstation_cluster: gapic_v1.method.wrap_method( + self.create_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_cluster: gapic_v1.method.wrap_method( + self.update_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_cluster: gapic_v1.method.wrap_method( + self.delete_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation_config: gapic_v1.method.wrap_method( + self.get_workstation_config, + 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_workstation_configs: gapic_v1.method.wrap_method( + self.list_workstation_configs, + 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_usable_workstation_configs: gapic_v1.method.wrap_method( + self.list_usable_workstation_configs, + 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.create_workstation_config: gapic_v1.method.wrap_method( + self.create_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_config: gapic_v1.method.wrap_method( + self.update_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_config: gapic_v1.method.wrap_method( + self.delete_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation: gapic_v1.method.wrap_method( + self.get_workstation, + 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_workstations: gapic_v1.method.wrap_method( + self.list_workstations, + 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_usable_workstations: gapic_v1.method.wrap_method( + self.list_usable_workstations, + 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.create_workstation: gapic_v1.method.wrap_method( + self.create_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation: gapic_v1.method.wrap_method( + self.update_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation: gapic_v1.method.wrap_method( + self.delete_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.start_workstation: gapic_v1.method.wrap_method( + self.start_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.stop_workstation: gapic_v1.method.wrap_method( + self.stop_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_access_token: gapic_v1.method.wrap_method( + self.generate_access_token, + 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_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + 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, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + 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 get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + Union[ + workstations.WorkstationCluster, + Awaitable[workstations.WorkstationCluster] + ]]: + raise NotImplementedError() + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + Union[ + workstations.ListWorkstationClustersResponse, + Awaitable[workstations.ListWorkstationClustersResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + Union[ + workstations.WorkstationConfig, + Awaitable[workstations.WorkstationConfig] + ]]: + raise NotImplementedError() + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + Union[ + workstations.ListWorkstationConfigsResponse, + Awaitable[workstations.ListWorkstationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + Union[ + workstations.ListUsableWorkstationConfigsResponse, + Awaitable[workstations.ListUsableWorkstationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + Union[ + workstations.Workstation, + Awaitable[workstations.Workstation] + ]]: + raise NotImplementedError() + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + Union[ + workstations.ListWorkstationsResponse, + Awaitable[workstations.ListWorkstationsResponse] + ]]: + raise NotImplementedError() + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + Union[ + workstations.ListUsableWorkstationsResponse, + Awaitable[workstations.ListUsableWorkstationsResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + Union[ + workstations.GenerateAccessTokenResponse, + Awaitable[workstations.GenerateAccessTokenResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WorkstationsTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py new file mode 100644 index 000000000000..aa0262c75a33 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py @@ -0,0 +1,948 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO + + +class WorkstationsGrpcTransport(WorkstationsTransport): + """gRPC backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workstations.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: 'workstations.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'workstations.googleapis.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.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + workstations.WorkstationCluster]: + r"""Return a callable for the get workstation cluster method over gRPC. + + Returns the requested workstation cluster. + + Returns: + Callable[[~.GetWorkstationClusterRequest], + ~.WorkstationCluster]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstationCluster', + request_serializer=workstations.GetWorkstationClusterRequest.serialize, + response_deserializer=workstations.WorkstationCluster.deserialize, + ) + return self._stubs['get_workstation_cluster'] + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + workstations.ListWorkstationClustersResponse]: + r"""Return a callable for the list workstation clusters method over gRPC. + + Returns all workstation clusters in the specified + location. + + Returns: + Callable[[~.ListWorkstationClustersRequest], + ~.ListWorkstationClustersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: + self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstationClusters', + request_serializer=workstations.ListWorkstationClustersRequest.serialize, + response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, + ) + return self._stubs['list_workstation_clusters'] + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation cluster method over gRPC. + + Creates a new workstation cluster. + + Returns: + Callable[[~.CreateWorkstationClusterRequest], + ~.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 'create_workstation_cluster' not in self._stubs: + self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstationCluster', + request_serializer=workstations.CreateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_cluster'] + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation cluster method over gRPC. + + Updates an existing workstation cluster. + + Returns: + Callable[[~.UpdateWorkstationClusterRequest], + ~.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 'update_workstation_cluster' not in self._stubs: + self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstationCluster', + request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_cluster'] + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation cluster method over gRPC. + + Deletes the specified workstation cluster. + + Returns: + Callable[[~.DeleteWorkstationClusterRequest], + ~.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 'delete_workstation_cluster' not in self._stubs: + self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstationCluster', + request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_cluster'] + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + workstations.WorkstationConfig]: + r"""Return a callable for the get workstation config method over gRPC. + + Returns the requested workstation configuration. + + Returns: + Callable[[~.GetWorkstationConfigRequest], + ~.WorkstationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstationConfig', + request_serializer=workstations.GetWorkstationConfigRequest.serialize, + response_deserializer=workstations.WorkstationConfig.deserialize, + ) + return self._stubs['get_workstation_config'] + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + workstations.ListWorkstationConfigsResponse]: + r"""Return a callable for the list workstation configs method over gRPC. + + Returns all workstation configurations in the + specified cluster. + + Returns: + Callable[[~.ListWorkstationConfigsRequest], + ~.ListWorkstationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: + self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstationConfigs', + request_serializer=workstations.ListWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_workstation_configs'] + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + workstations.ListUsableWorkstationConfigsResponse]: + r"""Return a callable for the list usable workstation + configs method over gRPC. + + Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + Returns: + Callable[[~.ListUsableWorkstationConfigsRequest], + ~.ListUsableWorkstationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: + self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListUsableWorkstationConfigs', + request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_usable_workstation_configs'] + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation config method over gRPC. + + Creates a new workstation configuration. + + Returns: + Callable[[~.CreateWorkstationConfigRequest], + ~.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 'create_workstation_config' not in self._stubs: + self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstationConfig', + request_serializer=workstations.CreateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_config'] + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation config method over gRPC. + + Updates an existing workstation configuration. + + Returns: + Callable[[~.UpdateWorkstationConfigRequest], + ~.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 'update_workstation_config' not in self._stubs: + self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstationConfig', + request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_config'] + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation config method over gRPC. + + Deletes the specified workstation configuration. + + Returns: + Callable[[~.DeleteWorkstationConfigRequest], + ~.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 'delete_workstation_config' not in self._stubs: + self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstationConfig', + request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_config'] + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + workstations.Workstation]: + r"""Return a callable for the get workstation method over gRPC. + + Returns the requested workstation. + + Returns: + Callable[[~.GetWorkstationRequest], + ~.Workstation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['get_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstation', + request_serializer=workstations.GetWorkstationRequest.serialize, + response_deserializer=workstations.Workstation.deserialize, + ) + return self._stubs['get_workstation'] + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + workstations.ListWorkstationsResponse]: + r"""Return a callable for the list workstations method over gRPC. + + Returns all Workstations using the specified + workstation configuration. + + Returns: + Callable[[~.ListWorkstationsRequest], + ~.ListWorkstationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstations' not in self._stubs: + self._stubs['list_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstations', + request_serializer=workstations.ListWorkstationsRequest.serialize, + response_deserializer=workstations.ListWorkstationsResponse.deserialize, + ) + return self._stubs['list_workstations'] + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + workstations.ListUsableWorkstationsResponse]: + r"""Return a callable for the list usable workstations method over gRPC. + + Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + Returns: + Callable[[~.ListUsableWorkstationsRequest], + ~.ListUsableWorkstationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: + self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListUsableWorkstations', + request_serializer=workstations.ListUsableWorkstationsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, + ) + return self._stubs['list_usable_workstations'] + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation method over gRPC. + + Creates a new workstation. + + Returns: + Callable[[~.CreateWorkstationRequest], + ~.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 'create_workstation' not in self._stubs: + self._stubs['create_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstation', + request_serializer=workstations.CreateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation'] + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation method over gRPC. + + Updates an existing workstation. + + Returns: + Callable[[~.UpdateWorkstationRequest], + ~.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 'update_workstation' not in self._stubs: + self._stubs['update_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstation', + request_serializer=workstations.UpdateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation'] + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation method over gRPC. + + Deletes the specified workstation. + + Returns: + Callable[[~.DeleteWorkstationRequest], + ~.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 'delete_workstation' not in self._stubs: + self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstation', + request_serializer=workstations.DeleteWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation'] + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the start workstation method over gRPC. + + Starts running a workstation so that users can + connect to it. + + Returns: + Callable[[~.StartWorkstationRequest], + ~.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 'start_workstation' not in self._stubs: + self._stubs['start_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/StartWorkstation', + request_serializer=workstations.StartWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['start_workstation'] + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the stop workstation method over gRPC. + + Stops running a workstation, reducing costs. + + Returns: + Callable[[~.StopWorkstationRequest], + ~.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 'stop_workstation' not in self._stubs: + self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/StopWorkstation', + request_serializer=workstations.StopWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['stop_workstation'] + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + workstations.GenerateAccessTokenResponse]: + r"""Return a callable for the generate access token method over gRPC. + + Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + ~.GenerateAccessTokenResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GenerateAccessToken', + request_serializer=workstations.GenerateAccessTokenRequest.serialize, + response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs['generate_access_token'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @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.grpc_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 list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WorkstationsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py new file mode 100644 index 000000000000..27b09102ef5f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py @@ -0,0 +1,1180 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .grpc import WorkstationsGrpcTransport + + +class WorkstationsGrpcAsyncIOTransport(WorkstationsTransport): + """gRPC AsyncIO backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workstations.googleapis.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 = 'workstations.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: 'workstations.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + Awaitable[workstations.WorkstationCluster]]: + r"""Return a callable for the get workstation cluster method over gRPC. + + Returns the requested workstation cluster. + + Returns: + Callable[[~.GetWorkstationClusterRequest], + Awaitable[~.WorkstationCluster]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstationCluster', + request_serializer=workstations.GetWorkstationClusterRequest.serialize, + response_deserializer=workstations.WorkstationCluster.deserialize, + ) + return self._stubs['get_workstation_cluster'] + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + Awaitable[workstations.ListWorkstationClustersResponse]]: + r"""Return a callable for the list workstation clusters method over gRPC. + + Returns all workstation clusters in the specified + location. + + Returns: + Callable[[~.ListWorkstationClustersRequest], + Awaitable[~.ListWorkstationClustersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: + self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstationClusters', + request_serializer=workstations.ListWorkstationClustersRequest.serialize, + response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, + ) + return self._stubs['list_workstation_clusters'] + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation cluster method over gRPC. + + Creates a new workstation cluster. + + Returns: + Callable[[~.CreateWorkstationClusterRequest], + 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 'create_workstation_cluster' not in self._stubs: + self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstationCluster', + request_serializer=workstations.CreateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_cluster'] + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation cluster method over gRPC. + + Updates an existing workstation cluster. + + Returns: + Callable[[~.UpdateWorkstationClusterRequest], + 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 'update_workstation_cluster' not in self._stubs: + self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstationCluster', + request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_cluster'] + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation cluster method over gRPC. + + Deletes the specified workstation cluster. + + Returns: + Callable[[~.DeleteWorkstationClusterRequest], + 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 'delete_workstation_cluster' not in self._stubs: + self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstationCluster', + request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_cluster'] + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + Awaitable[workstations.WorkstationConfig]]: + r"""Return a callable for the get workstation config method over gRPC. + + Returns the requested workstation configuration. + + Returns: + Callable[[~.GetWorkstationConfigRequest], + Awaitable[~.WorkstationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstationConfig', + request_serializer=workstations.GetWorkstationConfigRequest.serialize, + response_deserializer=workstations.WorkstationConfig.deserialize, + ) + return self._stubs['get_workstation_config'] + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + Awaitable[workstations.ListWorkstationConfigsResponse]]: + r"""Return a callable for the list workstation configs method over gRPC. + + Returns all workstation configurations in the + specified cluster. + + Returns: + Callable[[~.ListWorkstationConfigsRequest], + Awaitable[~.ListWorkstationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: + self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstationConfigs', + request_serializer=workstations.ListWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_workstation_configs'] + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + Awaitable[workstations.ListUsableWorkstationConfigsResponse]]: + r"""Return a callable for the list usable workstation + configs method over gRPC. + + Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + Returns: + Callable[[~.ListUsableWorkstationConfigsRequest], + Awaitable[~.ListUsableWorkstationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: + self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListUsableWorkstationConfigs', + request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_usable_workstation_configs'] + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation config method over gRPC. + + Creates a new workstation configuration. + + Returns: + Callable[[~.CreateWorkstationConfigRequest], + 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 'create_workstation_config' not in self._stubs: + self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstationConfig', + request_serializer=workstations.CreateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_config'] + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation config method over gRPC. + + Updates an existing workstation configuration. + + Returns: + Callable[[~.UpdateWorkstationConfigRequest], + 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 'update_workstation_config' not in self._stubs: + self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstationConfig', + request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_config'] + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation config method over gRPC. + + Deletes the specified workstation configuration. + + Returns: + Callable[[~.DeleteWorkstationConfigRequest], + 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 'delete_workstation_config' not in self._stubs: + self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstationConfig', + request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_config'] + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + Awaitable[workstations.Workstation]]: + r"""Return a callable for the get workstation method over gRPC. + + Returns the requested workstation. + + Returns: + Callable[[~.GetWorkstationRequest], + Awaitable[~.Workstation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['get_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstation', + request_serializer=workstations.GetWorkstationRequest.serialize, + response_deserializer=workstations.Workstation.deserialize, + ) + return self._stubs['get_workstation'] + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + Awaitable[workstations.ListWorkstationsResponse]]: + r"""Return a callable for the list workstations method over gRPC. + + Returns all Workstations using the specified + workstation configuration. + + Returns: + Callable[[~.ListWorkstationsRequest], + Awaitable[~.ListWorkstationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstations' not in self._stubs: + self._stubs['list_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstations', + request_serializer=workstations.ListWorkstationsRequest.serialize, + response_deserializer=workstations.ListWorkstationsResponse.deserialize, + ) + return self._stubs['list_workstations'] + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + Awaitable[workstations.ListUsableWorkstationsResponse]]: + r"""Return a callable for the list usable workstations method over gRPC. + + Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + Returns: + Callable[[~.ListUsableWorkstationsRequest], + Awaitable[~.ListUsableWorkstationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: + self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListUsableWorkstations', + request_serializer=workstations.ListUsableWorkstationsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, + ) + return self._stubs['list_usable_workstations'] + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation method over gRPC. + + Creates a new workstation. + + Returns: + Callable[[~.CreateWorkstationRequest], + 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 'create_workstation' not in self._stubs: + self._stubs['create_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstation', + request_serializer=workstations.CreateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation'] + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation method over gRPC. + + Updates an existing workstation. + + Returns: + Callable[[~.UpdateWorkstationRequest], + 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 'update_workstation' not in self._stubs: + self._stubs['update_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstation', + request_serializer=workstations.UpdateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation'] + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation method over gRPC. + + Deletes the specified workstation. + + Returns: + Callable[[~.DeleteWorkstationRequest], + 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 'delete_workstation' not in self._stubs: + self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstation', + request_serializer=workstations.DeleteWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation'] + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the start workstation method over gRPC. + + Starts running a workstation so that users can + connect to it. + + Returns: + Callable[[~.StartWorkstationRequest], + 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 'start_workstation' not in self._stubs: + self._stubs['start_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/StartWorkstation', + request_serializer=workstations.StartWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['start_workstation'] + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the stop workstation method over gRPC. + + Stops running a workstation, reducing costs. + + Returns: + Callable[[~.StopWorkstationRequest], + 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 'stop_workstation' not in self._stubs: + self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/StopWorkstation', + request_serializer=workstations.StopWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['stop_workstation'] + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + Awaitable[workstations.GenerateAccessTokenResponse]]: + r"""Return a callable for the generate access token method over gRPC. + + Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + Awaitable[~.GenerateAccessTokenResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GenerateAccessToken', + request_serializer=workstations.GenerateAccessTokenRequest.serialize, + response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs['generate_access_token'] + + 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_workstation_cluster: self._wrap_method( + self.get_workstation_cluster, + 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_workstation_clusters: self._wrap_method( + self.list_workstation_clusters, + 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.create_workstation_cluster: self._wrap_method( + self.create_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_cluster: self._wrap_method( + self.update_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_cluster: self._wrap_method( + self.delete_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation_config: self._wrap_method( + self.get_workstation_config, + 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_workstation_configs: self._wrap_method( + self.list_workstation_configs, + 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_usable_workstation_configs: self._wrap_method( + self.list_usable_workstation_configs, + 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.create_workstation_config: self._wrap_method( + self.create_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_config: self._wrap_method( + self.update_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_config: self._wrap_method( + self.delete_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation: self._wrap_method( + self.get_workstation, + 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_workstations: self._wrap_method( + self.list_workstations, + 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_usable_workstations: self._wrap_method( + self.list_usable_workstations, + 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.create_workstation: self._wrap_method( + self.create_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation: self._wrap_method( + self.update_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation: self._wrap_method( + self.delete_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.start_workstation: self._wrap_method( + self.start_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.stop_workstation: self._wrap_method( + self.stop_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_access_token: self._wrap_method( + self.generate_access_token, + 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_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @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.grpc_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 list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'WorkstationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py new file mode 100644 index 000000000000..456fb9226990 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py @@ -0,0 +1,3048 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.workstations_v1.types import workstations +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseWorkstationsRestTransport +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 + + +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 WorkstationsRestInterceptor: + """Interceptor for Workstations. + + 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 WorkstationsRestTransport. + + .. code-block:: python + class MyCustomWorkstationsInterceptor(WorkstationsRestInterceptor): + def pre_create_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_access_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_access_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_usable_workstation_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_usable_workstation_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_usable_workstations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_usable_workstations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstation_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstation_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstation_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstation_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WorkstationsRestTransport(interceptor=MyCustomWorkstationsInterceptor()) + client = WorkstationsClient(transport=transport) + + + """ + def pre_create_workstation(self, request: workstations.CreateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_create_workstation_cluster(self, request: workstations.CreateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_create_workstation_config(self, request: workstations.CreateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_delete_workstation(self, request: workstations.DeleteWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_delete_workstation_cluster(self, request: workstations.DeleteWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_delete_workstation_config(self, request: workstations.DeleteWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_generate_access_token(self, request: workstations.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_generate_access_token(self, response: workstations.GenerateAccessTokenResponse) -> workstations.GenerateAccessTokenResponse: + """Post-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_workstation(self, request: workstations.GetWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation(self, response: workstations.Workstation) -> workstations.Workstation: + """Post-rpc interceptor for get_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_workstation_cluster(self, request: workstations.GetWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation_cluster(self, response: workstations.WorkstationCluster) -> workstations.WorkstationCluster: + """Post-rpc interceptor for get_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_workstation_config(self, request: workstations.GetWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation_config(self, response: workstations.WorkstationConfig) -> workstations.WorkstationConfig: + """Post-rpc interceptor for get_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_usable_workstation_configs(self, request: workstations.ListUsableWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_usable_workstation_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_usable_workstation_configs(self, response: workstations.ListUsableWorkstationConfigsResponse) -> workstations.ListUsableWorkstationConfigsResponse: + """Post-rpc interceptor for list_usable_workstation_configs + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_usable_workstations(self, request: workstations.ListUsableWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_usable_workstations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_usable_workstations(self, response: workstations.ListUsableWorkstationsResponse) -> workstations.ListUsableWorkstationsResponse: + """Post-rpc interceptor for list_usable_workstations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_workstation_clusters(self, request: workstations.ListWorkstationClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationClustersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstation_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstation_clusters(self, response: workstations.ListWorkstationClustersResponse) -> workstations.ListWorkstationClustersResponse: + """Post-rpc interceptor for list_workstation_clusters + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_workstation_configs(self, request: workstations.ListWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstation_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstation_configs(self, response: workstations.ListWorkstationConfigsResponse) -> workstations.ListWorkstationConfigsResponse: + """Post-rpc interceptor for list_workstation_configs + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_workstations(self, request: workstations.ListWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstations(self, response: workstations.ListWorkstationsResponse) -> workstations.ListWorkstationsResponse: + """Post-rpc interceptor for list_workstations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_start_workstation(self, request: workstations.StartWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StartWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_start_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for start_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_stop_workstation(self, request: workstations.StopWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StopWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_stop_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for stop_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_update_workstation(self, request: workstations.UpdateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_update_workstation_cluster(self, request: workstations.UpdateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_update_workstation_config(self, request: workstations.UpdateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations 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 Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WorkstationsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WorkstationsRestInterceptor + + +class WorkstationsRestTransport(_BaseWorkstationsRestTransport): + """REST backend synchronous transport for Workstations. + + Service for interacting with Cloud Workstations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'workstations.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[WorkstationsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'workstations.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 WorkstationsRestInterceptor() + 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.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + '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 _CreateWorkstation(_BaseWorkstationsRestTransport._BaseCreateWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.CreateWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.CreateWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation method over HTTP. + + Args: + request (~.workstations.CreateWorkstationRequest): + The request object. Message for creating a + CreateWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_http_options() + request, metadata = self._interceptor.pre_create_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._CreateWorkstation._get_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_create_workstation(resp) + return resp + + class _CreateWorkstationCluster(_BaseWorkstationsRestTransport._BaseCreateWorkstationCluster, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.CreateWorkstationCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.CreateWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation + cluster method over HTTP. + + Args: + request (~.workstations.CreateWorkstationClusterRequest): + The request object. Message for creating a + CreateWorkstationCluster. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_http_options() + request, metadata = self._interceptor.pre_create_workstation_cluster(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._CreateWorkstationCluster._get_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_create_workstation_cluster(resp) + return resp + + class _CreateWorkstationConfig(_BaseWorkstationsRestTransport._BaseCreateWorkstationConfig, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.CreateWorkstationConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.CreateWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation config method over HTTP. + + Args: + request (~.workstations.CreateWorkstationConfigRequest): + The request object. Message for creating a + CreateWorkstationConfig. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_http_options() + request, metadata = self._interceptor.pre_create_workstation_config(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._CreateWorkstationConfig._get_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_create_workstation_config(resp) + return resp + + class _DeleteWorkstation(_BaseWorkstationsRestTransport._BaseDeleteWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.DeleteWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.DeleteWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationRequest): + The request object. Request message for + DeleteWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_http_options() + request, metadata = self._interceptor.pre_delete_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._DeleteWorkstation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, 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_delete_workstation(resp) + return resp + + class _DeleteWorkstationCluster(_BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.DeleteWorkstationCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.DeleteWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation + cluster method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationClusterRequest): + The request object. Message for deleting a workstation + cluster. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_http_options() + request, metadata = self._interceptor.pre_delete_workstation_cluster(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._DeleteWorkstationCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, 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_delete_workstation_cluster(resp) + return resp + + class _DeleteWorkstationConfig(_BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.DeleteWorkstationConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.DeleteWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation config method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationConfigRequest): + The request object. Message for deleting a workstation + configuration. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_http_options() + request, metadata = self._interceptor.pre_delete_workstation_config(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._DeleteWorkstationConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, 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_delete_workstation_config(resp) + return resp + + class _GenerateAccessToken(_BaseWorkstationsRestTransport._BaseGenerateAccessToken, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GenerateAccessToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.GenerateAccessTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.GenerateAccessTokenResponse: + r"""Call the generate access token method over HTTP. + + Args: + request (~.workstations.GenerateAccessTokenRequest): + The request object. Request message for + GenerateAccessToken. + retry (google.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. + + Returns: + ~.workstations.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_http_options() + request, metadata = self._interceptor.pre_generate_access_token(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GenerateAccessToken._get_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 = workstations.GenerateAccessTokenResponse() + pb_resp = workstations.GenerateAccessTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_access_token(resp) + return resp + + class _GetWorkstation(_BaseWorkstationsRestTransport._BaseGetWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GetWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.GetWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.Workstation: + r"""Call the get workstation method over HTTP. + + Args: + request (~.workstations.GetWorkstationRequest): + The request object. Request message for GetWorkstation. + retry (google.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. + + Returns: + ~.workstations.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_http_options() + request, metadata = self._interceptor.pre_get_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GetWorkstation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.Workstation() + pb_resp = workstations.Workstation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation(resp) + return resp + + class _GetWorkstationCluster(_BaseWorkstationsRestTransport._BaseGetWorkstationCluster, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GetWorkstationCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.GetWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.WorkstationCluster: + r"""Call the get workstation cluster method over HTTP. + + Args: + request (~.workstations.GetWorkstationClusterRequest): + The request object. Request message for + GetWorkstationCluster. + retry (google.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. + + Returns: + ~.workstations.WorkstationCluster: + A workstation cluster resource in the + Cloud Workstations API. + Defines a group of workstations in a + particular region and the VPC network + they're attached to. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_http_options() + request, metadata = self._interceptor.pre_get_workstation_cluster(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GetWorkstationCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.WorkstationCluster() + pb_resp = workstations.WorkstationCluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation_cluster(resp) + return resp + + class _GetWorkstationConfig(_BaseWorkstationsRestTransport._BaseGetWorkstationConfig, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GetWorkstationConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.GetWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.WorkstationConfig: + r"""Call the get workstation config method over HTTP. + + Args: + request (~.workstations.GetWorkstationConfigRequest): + The request object. Request message for + GetWorkstationConfig. + retry (google.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. + + Returns: + ~.workstations.WorkstationConfig: + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to use, + and more. Administrators and platform teams can also use + `Identity and Access Management + (IAM) `__ + rules to grant access to teams or to individual + developers. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_http_options() + request, metadata = self._interceptor.pre_get_workstation_config(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GetWorkstationConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.WorkstationConfig() + pb_resp = workstations.WorkstationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation_config(resp) + return resp + + class _ListUsableWorkstationConfigs(_BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListUsableWorkstationConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListUsableWorkstationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListUsableWorkstationConfigsResponse: + r"""Call the list usable workstation + configs method over HTTP. + + Args: + request (~.workstations.ListUsableWorkstationConfigsRequest): + The request object. Request message for + ListUsableWorkstationConfigs. + retry (google.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. + + Returns: + ~.workstations.ListUsableWorkstationConfigsResponse: + Response message for + ListUsableWorkstationConfigs. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_http_options() + request, metadata = self._interceptor.pre_list_usable_workstation_configs(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListUsableWorkstationConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListUsableWorkstationConfigsResponse() + pb_resp = workstations.ListUsableWorkstationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_usable_workstation_configs(resp) + return resp + + class _ListUsableWorkstations(_BaseWorkstationsRestTransport._BaseListUsableWorkstations, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListUsableWorkstations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListUsableWorkstationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListUsableWorkstationsResponse: + r"""Call the list usable workstations method over HTTP. + + Args: + request (~.workstations.ListUsableWorkstationsRequest): + The request object. Request message for + ListUsableWorkstations. + retry (google.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. + + Returns: + ~.workstations.ListUsableWorkstationsResponse: + Response message for + ListUsableWorkstations. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_http_options() + request, metadata = self._interceptor.pre_list_usable_workstations(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListUsableWorkstations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListUsableWorkstationsResponse() + pb_resp = workstations.ListUsableWorkstationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_usable_workstations(resp) + return resp + + class _ListWorkstationClusters(_BaseWorkstationsRestTransport._BaseListWorkstationClusters, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListWorkstationClusters") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListWorkstationClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationClustersResponse: + r"""Call the list workstation clusters method over HTTP. + + Args: + request (~.workstations.ListWorkstationClustersRequest): + The request object. Request message for + ListWorkstationClusters. + retry (google.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. + + Returns: + ~.workstations.ListWorkstationClustersResponse: + Response message for + ListWorkstationClusters. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_http_options() + request, metadata = self._interceptor.pre_list_workstation_clusters(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListWorkstationClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListWorkstationClustersResponse() + pb_resp = workstations.ListWorkstationClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstation_clusters(resp) + return resp + + class _ListWorkstationConfigs(_BaseWorkstationsRestTransport._BaseListWorkstationConfigs, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListWorkstationConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListWorkstationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationConfigsResponse: + r"""Call the list workstation configs method over HTTP. + + Args: + request (~.workstations.ListWorkstationConfigsRequest): + The request object. Request message for + ListWorkstationConfigs. + retry (google.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. + + Returns: + ~.workstations.ListWorkstationConfigsResponse: + Response message for + ListWorkstationConfigs. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_http_options() + request, metadata = self._interceptor.pre_list_workstation_configs(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListWorkstationConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListWorkstationConfigsResponse() + pb_resp = workstations.ListWorkstationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstation_configs(resp) + return resp + + class _ListWorkstations(_BaseWorkstationsRestTransport._BaseListWorkstations, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListWorkstations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListWorkstationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationsResponse: + r"""Call the list workstations method over HTTP. + + Args: + request (~.workstations.ListWorkstationsRequest): + The request object. Request message for ListWorkstations. + retry (google.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. + + Returns: + ~.workstations.ListWorkstationsResponse: + Response message for + ListWorkstations. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListWorkstations._get_http_options() + request, metadata = self._interceptor.pre_list_workstations(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListWorkstations._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListWorkstations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListWorkstationsResponse() + pb_resp = workstations.ListWorkstationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstations(resp) + return resp + + class _StartWorkstation(_BaseWorkstationsRestTransport._BaseStartWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.StartWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.StartWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the start workstation method over HTTP. + + Args: + request (~.workstations.StartWorkstationRequest): + The request object. Request message for StartWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_http_options() + request, metadata = self._interceptor.pre_start_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._StartWorkstation._get_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_start_workstation(resp) + return resp + + class _StopWorkstation(_BaseWorkstationsRestTransport._BaseStopWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.StopWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.StopWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the stop workstation method over HTTP. + + Args: + request (~.workstations.StopWorkstationRequest): + The request object. Request message for StopWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_http_options() + request, metadata = self._interceptor.pre_stop_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._StopWorkstation._get_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_stop_workstation(resp) + return resp + + class _UpdateWorkstation(_BaseWorkstationsRestTransport._BaseUpdateWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.UpdateWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.UpdateWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationRequest): + The request object. Request message for + UpdateWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_http_options() + request, metadata = self._interceptor.pre_update_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._UpdateWorkstation._get_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_update_workstation(resp) + return resp + + class _UpdateWorkstationCluster(_BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.UpdateWorkstationCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.UpdateWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation + cluster method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationClusterRequest): + The request object. Request message for + UpdateWorkstationCluster. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_http_options() + request, metadata = self._interceptor.pre_update_workstation_cluster(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._UpdateWorkstationCluster._get_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_update_workstation_cluster(resp) + return resp + + class _UpdateWorkstationConfig(_BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.UpdateWorkstationConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.UpdateWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation config method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationConfigRequest): + The request object. Request message for + UpdateWorkstationConfig. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_http_options() + request, metadata = self._interceptor.pre_update_workstation_config(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._UpdateWorkstationConfig._get_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_update_workstation_config(resp) + return resp + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + 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._CreateWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + 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._CreateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + 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._CreateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + 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._DeleteWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + 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._DeleteWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + 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._DeleteWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + workstations.GenerateAccessTokenResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + workstations.Workstation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + workstations.WorkstationCluster]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + workstations.WorkstationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + workstations.ListUsableWorkstationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsableWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + workstations.ListUsableWorkstationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsableWorkstations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + workstations.ListWorkstationClustersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstationClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + workstations.ListWorkstationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + workstations.ListWorkstationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstations(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + 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._StartWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + 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._StopWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + 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._UpdateWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + 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._UpdateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + 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._UpdateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseWorkstationsRestTransport._BaseGetIamPolicy, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.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. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseWorkstationsRestTransport._BaseSetIamPolicy, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.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. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._SetIamPolicy._get_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) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseWorkstationsRestTransport._BaseTestIamPermissions, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.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. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._TestIamPermissions._get_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) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseWorkstationsRestTransport._BaseCancelOperation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.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. + """ + + http_options = _BaseWorkstationsRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._CancelOperation._get_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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseWorkstationsRestTransport._BaseDeleteOperation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(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.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.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. + """ + + http_options = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseWorkstationsRestTransport._BaseGetOperation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._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) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseWorkstationsRestTransport._BaseListOperations, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(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.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.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. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WorkstationsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest_base.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest_base.py new file mode 100644 index 000000000000..4156ac1fa50d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest_base.py @@ -0,0 +1,1129 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.workstations_v1.types import workstations +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseWorkstationsRestTransport(WorkstationsTransport): + """Base REST backend transport for Workstations. + + 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 = 'workstations.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: 'workstations.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 _BaseCreateWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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/*/workstationClusters/*/workstationConfigs/*}/workstations', + 'body': 'workstation', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.CreateWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateWorkstationCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationClusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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/*}/workstationClusters', + 'body': 'workstation_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.CreateWorkstationClusterRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateWorkstationConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationConfigId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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/*/workstationClusters/*}/workstationConfigs', + 'body': 'workstation_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.CreateWorkstationConfigRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.DeleteWorkstationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteWorkstationCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.DeleteWorkstationClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteWorkstationConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.DeleteWorkstationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGenerateAccessToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.GenerateAccessTokenRequest.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(_BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.GetWorkstationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetWorkstationCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.GetWorkstationClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetWorkstationConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.GetWorkstationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUsableWorkstationConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListUsableWorkstationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUsableWorkstations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListUsableWorkstationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkstationClusters: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/workstationClusters', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListWorkstationClustersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkstationConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListWorkstationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkstations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListWorkstationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstations._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStartWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.StartWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseStartWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStopWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.StopWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseStopWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateWorkstation: + 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': '/v1/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + 'body': 'workstation', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.UpdateWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateWorkstationCluster: + 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': '/v1/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}', + 'body': 'workstation_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.UpdateWorkstationClusterRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateWorkstationConfig: + 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': '/v1/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + 'body': 'workstation_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.UpdateWorkstationConfigRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + 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/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:getIamPolicy', + }, + ] + 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 + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:setIamPolicy', + 'body': '*', + }, + ] + 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_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:testIamPermissions', + 'body': '*', + }, + ] + 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_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + 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_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + '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 + + 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 + + class _BaseListOperations: + 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__=( + '_BaseWorkstationsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py new file mode 100644 index 000000000000..74244c2b3708 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .workstations import ( + CreateWorkstationClusterRequest, + CreateWorkstationConfigRequest, + CreateWorkstationRequest, + DeleteWorkstationClusterRequest, + DeleteWorkstationConfigRequest, + DeleteWorkstationRequest, + GenerateAccessTokenRequest, + GenerateAccessTokenResponse, + GetWorkstationClusterRequest, + GetWorkstationConfigRequest, + GetWorkstationRequest, + ListUsableWorkstationConfigsRequest, + ListUsableWorkstationConfigsResponse, + ListUsableWorkstationsRequest, + ListUsableWorkstationsResponse, + ListWorkstationClustersRequest, + ListWorkstationClustersResponse, + ListWorkstationConfigsRequest, + ListWorkstationConfigsResponse, + ListWorkstationsRequest, + ListWorkstationsResponse, + OperationMetadata, + StartWorkstationRequest, + StopWorkstationRequest, + UpdateWorkstationClusterRequest, + UpdateWorkstationConfigRequest, + UpdateWorkstationRequest, + Workstation, + WorkstationCluster, + WorkstationConfig, +) + +__all__ = ( + 'CreateWorkstationClusterRequest', + 'CreateWorkstationConfigRequest', + 'CreateWorkstationRequest', + 'DeleteWorkstationClusterRequest', + 'DeleteWorkstationConfigRequest', + 'DeleteWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GetWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'OperationMetadata', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'UpdateWorkstationClusterRequest', + 'UpdateWorkstationConfigRequest', + 'UpdateWorkstationRequest', + 'Workstation', + 'WorkstationCluster', + 'WorkstationConfig', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py new file mode 100644 index 000000000000..ef51fb4cc435 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py @@ -0,0 +1,1953 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.workstations.v1', + manifest={ + 'WorkstationCluster', + 'WorkstationConfig', + 'Workstation', + 'GetWorkstationClusterRequest', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'CreateWorkstationClusterRequest', + 'UpdateWorkstationClusterRequest', + 'DeleteWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'CreateWorkstationConfigRequest', + 'UpdateWorkstationConfigRequest', + 'DeleteWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'CreateWorkstationRequest', + 'UpdateWorkstationRequest', + 'DeleteWorkstationRequest', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'OperationMetadata', + }, +) + + +class WorkstationCluster(proto.Message): + r"""A workstation cluster resource in the Cloud Workstations API. + + Defines a group of workstations in a particular region and the + VPC network they're attached to. + + Attributes: + name (str): + Full name of this workstation cluster. + display_name (str): + Optional. Human-readable name for this + workstation cluster. + uid (str): + Output only. A system-assigned unique + identifier for this workstation cluster. + reconciling (bool): + Output only. Indicates whether this + workstation cluster is currently being updated + to match its intended state. + annotations (MutableMapping[str, str]): + Optional. Client-specified annotations. + labels (MutableMapping[str, str]): + Optional. + `Labels `__ + that are applied to the workstation cluster and that are + also propagated to the underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + cluster was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + cluster was most recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + cluster was soft-deleted. + etag (str): + Optional. Checksum computed by the server. + May be sent on update and delete requests to + make sure that the client has an up-to-date + value before proceeding. + network (str): + Immutable. Name of the Compute Engine network + in which instances associated with this + workstation cluster will be created. + subnetwork (str): + Immutable. Name of the Compute Engine + subnetwork in which instances associated with + this workstation cluster will be created. Must + be part of the subnetwork specified for this + workstation cluster. + control_plane_ip (str): + Output only. The private IP address of the + control plane for this workstation cluster. + Workstation VMs need access to this IP address + to work with the service, so make sure that your + firewall rules allow egress from the workstation + VMs to this address. + private_cluster_config (google.cloud.workstations_v1.types.WorkstationCluster.PrivateClusterConfig): + Optional. Configuration for private + workstation cluster. + degraded (bool): + Output only. Whether this workstation cluster is in degraded + mode, in which case it may require user action to restore + full functionality. Details can be found in + [conditions][google.cloud.workstations.v1.WorkstationCluster.conditions]. + conditions (MutableSequence[google.rpc.status_pb2.Status]): + Output only. Status conditions describing the + workstation cluster's current state. + """ + + class PrivateClusterConfig(proto.Message): + r"""Configuration options for private workstation clusters. + + Attributes: + enable_private_endpoint (bool): + Immutable. Whether Workstations endpoint is + private. + cluster_hostname (str): + Output only. Hostname for the workstation + cluster. This field will be populated only when + private endpoint is enabled. To access + workstations in the workstation cluster, create + a new DNS zone mapping this domain name to an + internal IP address and a forwarding rule + mapping that address to the service attachment. + service_attachment_uri (str): + Output only. Service attachment URI for the workstation + cluster. The service attachemnt is created when private + endpoint is enabled. To access workstations in the + workstation cluster, configure access to the managed service + using `Private Service + Connect `__. + allowed_projects (MutableSequence[str]): + Optional. Additional projects that are + allowed to attach to the workstation cluster's + service attachment. By default, the workstation + cluster's project and the VPC host project (if + different) are allowed. + """ + + enable_private_endpoint: bool = proto.Field( + proto.BOOL, + number=1, + ) + cluster_hostname: str = proto.Field( + proto.STRING, + number=2, + ) + service_attachment_uri: str = proto.Field( + proto.STRING, + number=3, + ) + allowed_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + 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, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + ) + network: str = proto.Field( + proto.STRING, + number=10, + ) + subnetwork: str = proto.Field( + proto.STRING, + number=11, + ) + control_plane_ip: str = proto.Field( + proto.STRING, + number=16, + ) + private_cluster_config: PrivateClusterConfig = proto.Field( + proto.MESSAGE, + number=12, + message=PrivateClusterConfig, + ) + degraded: bool = proto.Field( + proto.BOOL, + number=13, + ) + conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=status_pb2.Status, + ) + + +class WorkstationConfig(proto.Message): + r"""A workstation configuration resource in the Cloud Workstations API. + + Workstation configurations act as templates for workstations. The + workstation configuration defines details such as the workstation + virtual machine (VM) instance type, persistent storage, container + image defining environment, which IDE or Code Editor to use, and + more. Administrators and platform teams can also use `Identity and + Access Management + (IAM) `__ rules to grant + access to teams or to individual developers. + + Attributes: + name (str): + Full name of this workstation configuration. + display_name (str): + Optional. Human-readable name for this + workstation configuration. + uid (str): + Output only. A system-assigned unique + identifier for this workstation configuration. + reconciling (bool): + Output only. Indicates whether this + workstation configuration is currently being + updated to match its intended state. + annotations (MutableMapping[str, str]): + Optional. Client-specified annotations. + labels (MutableMapping[str, str]): + Optional. + `Labels `__ + that are applied to the workstation configuration and that + are also propagated to the underlying Compute Engine + resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + configuration was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + configuration was most recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + configuration was soft-deleted. + etag (str): + Optional. Checksum computed by the server. + May be sent on update and delete requests to + make sure that the client has an up-to-date + value before proceeding. + idle_timeout (google.protobuf.duration_pb2.Duration): + Optional. Number of seconds to wait before automatically + stopping a workstation after it last received user traffic. + + A value of ``"0s"`` indicates that Cloud Workstations VMs + created with this configuration should never time out due to + idleness. Provide + `duration `__ + terminated by ``s`` for seconds—for example, ``"7200s"`` (2 + hours). The default is ``"1200s"`` (20 minutes). + running_timeout (google.protobuf.duration_pb2.Duration): + Optional. Number of seconds that a workstation can run until + it is automatically shut down. We recommend that + workstations be shut down daily to reduce costs and so that + security updates can be applied upon restart. The + [idle_timeout][google.cloud.workstations.v1.WorkstationConfig.idle_timeout] + and + [running_timeout][google.cloud.workstations.v1.WorkstationConfig.running_timeout] + fields are independent of each other. Note that the + [running_timeout][google.cloud.workstations.v1.WorkstationConfig.running_timeout] + field shuts down VMs after the specified time, regardless of + whether or not the VMs are idle. + + Provide duration terminated by ``s`` for seconds—for + example, ``"54000s"`` (15 hours). Defaults to ``"43200s"`` + (12 hours). A value of ``"0s"`` indicates that workstations + using this configuration should never time out. If + [encryption_key][google.cloud.workstations.v1.WorkstationConfig.encryption_key] + is set, it must be greater than ``"0s"`` and less than + ``"86400s"`` (24 hours). + + Warning: A value of ``"0s"`` indicates that Cloud + Workstations VMs created with this configuration have no + maximum running time. This is strongly discouraged because + you incur costs and will not pick up security updates. + host (google.cloud.workstations_v1.types.WorkstationConfig.Host): + Optional. Runtime host for the workstation. + persistent_directories (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory]): + Optional. Directories to persist across + workstation sessions. + container (google.cloud.workstations_v1.types.WorkstationConfig.Container): + Optional. Container that runs upon startup + for each workstation using this workstation + configuration. + encryption_key (google.cloud.workstations_v1.types.WorkstationConfig.CustomerEncryptionKey): + Immutable. Encrypts resources of this + workstation configuration using a + customer-managed encryption key (CMEK). + + If specified, the boot disk of the Compute + Engine instance and the persistent disk are + encrypted using this encryption key. If this + field is not set, the disks are encrypted using + a generated key. Customer-managed encryption + keys do not protect disk metadata. + + If the customer-managed encryption key is + rotated, when the workstation instance is + stopped, the system attempts to recreate the + persistent disk with the new version of the key. + Be sure to keep older versions of the key until + the persistent disk is recreated. Otherwise, + data on the persistent disk might be lost. + + If the encryption key is revoked, the + workstation session automatically stops within 7 + hours. + + Immutable after the workstation configuration is + created. + readiness_checks (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig.ReadinessCheck]): + Optional. Readiness checks to perform when + starting a workstation using this workstation + configuration. Mark a workstation as running + only after all specified readiness checks return + 200 status codes. + replica_zones (MutableSequence[str]): + Optional. Immutable. Specifies the zones used to replicate + the VM and disk resources within the region. If set, exactly + two zones within the workstation cluster's region must be + specified—for example, + ``['us-central1-a', 'us-central1-f']``. If this field is + empty, two default zones within the region are used. + + Immutable after the workstation configuration is created. + degraded (bool): + Output only. Whether this resource is degraded, in which + case it may require user action to restore full + functionality. See also the + [conditions][google.cloud.workstations.v1.WorkstationConfig.conditions] + field. + conditions (MutableSequence[google.rpc.status_pb2.Status]): + Output only. Status conditions describing the + current resource state. + """ + + class Host(proto.Message): + r"""Runtime host for a workstation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gce_instance (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance): + Specifies a Compute Engine instance as the + host. + + This field is a member of `oneof`_ ``config``. + """ + + class GceInstance(proto.Message): + r"""A runtime using a Compute Engine instance. + + Attributes: + machine_type (str): + Optional. The type of machine to use for VM instances—for + example, ``"e2-standard-4"``. For more information about + machine types that Cloud Workstations supports, see the list + of `available machine + types `__. + service_account (str): + Optional. The email address of the service account for Cloud + Workstations VMs created with this configuration. When + specified, be sure that the service account has + ``logginglogEntries.create`` permission on the project so it + can write logs out to Cloud Logging. If using a custom + container image, the service account must have permissions + to pull the specified image. + + If you as the administrator want to be able to ``ssh`` into + the underlying VM, you need to set this value to a service + account for which you have the ``iam.serviceAccounts.actAs`` + permission. Conversely, if you don't want anyone to be able + to ``ssh`` into the underlying VM, use a service account + where no one has that permission. + + If not set, VMs run with a service account provided by the + Cloud Workstations service, and the image must be publicly + accessible. + service_account_scopes (MutableSequence[str]): + Optional. Scopes to grant to the + [service_account][google.cloud.workstations.v1.WorkstationConfig.Host.GceInstance.service_account]. + Various scopes are automatically added based on feature + usage. When specified, users of workstations under this + configuration must have ``iam.serviceAccounts.actAs`` on the + service account. + tags (MutableSequence[str]): + Optional. Network tags to add to the Compute Engine VMs + backing the workstations. This option applies `network + tags `__ + to VMs created with this configuration. These network tags + enable the creation of `firewall + rules `__. + pool_size (int): + Optional. The number of VMs that the system should keep idle + so that new workstations can be started quickly for new + users. Defaults to ``0`` in the API. + pooled_instances (int): + Output only. Number of instances currently + available in the pool for faster workstation + startup. + disable_public_ip_addresses (bool): + Optional. When set to true, disables public IP addresses for + VMs. If you disable public IP addresses, you must set up + Private Google Access or Cloud NAT on your network. If you + use Private Google Access and you use + ``private.googleapis.com`` or ``restricted.googleapis.com`` + for Container Registry and Artifact Registry, make sure that + you set up DNS records for domains ``*.gcr.io`` and + ``*.pkg.dev``. Defaults to false (VMs have public IP + addresses). + enable_nested_virtualization (bool): + Optional. Whether to enable nested virtualization on Cloud + Workstations VMs created under this workstation + configuration. + + Nested virtualization lets you run virtual machine (VM) + instances inside your workstation. Before enabling nested + virtualization, consider the following important + considerations. Cloud Workstations instances are subject to + the `same restrictions as Compute Engine + instances `__: + + - **Organization policy**: projects, folders, or + organizations may be restricted from creating nested VMs + if the **Disable VM nested virtualization** constraint is + enforced in the organization policy. For more + information, see the Compute Engine section, `Checking + whether nested virtualization is + allowed `__. + - **Performance**: nested VMs might experience a 10% or + greater decrease in performance for workloads that are + CPU-bound and possibly greater than a 10% decrease for + workloads that are input/output bound. + - **Machine Type**: nested virtualization can only be + enabled on workstation configurations that specify a + [machine_type][google.cloud.workstations.v1.WorkstationConfig.Host.GceInstance.machine_type] + in the N1 or N2 machine series. + - **GPUs**: nested virtualization may not be enabled on + workstation configurations with accelerators. + - **Operating System**: Because `Container-Optimized + OS `__ + does not support nested virtualization, when nested + virtualization is enabled, the underlying Compute Engine + VM instances boot from an `Ubuntu + LTS `__ + image. + shielded_instance_config (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig): + Optional. A set of Compute Engine Shielded + instance options. + confidential_instance_config (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig): + Optional. A set of Compute Engine + Confidential VM instance options. + boot_disk_size_gb (int): + Optional. The size of the boot disk for the VM in gigabytes + (GB). The minimum boot disk size is ``30`` GB. Defaults to + ``50`` GB. + """ + + class GceShieldedInstanceConfig(proto.Message): + r"""A set of Compute Engine Shielded instance options. + + Attributes: + enable_secure_boot (bool): + Optional. Whether the instance has Secure + Boot enabled. + enable_vtpm (bool): + Optional. Whether the instance has the vTPM + enabled. + enable_integrity_monitoring (bool): + Optional. Whether the instance has integrity + monitoring enabled. + """ + + enable_secure_boot: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_vtpm: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_integrity_monitoring: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class GceConfidentialInstanceConfig(proto.Message): + r"""A set of Compute Engine Confidential VM instance options. + + Attributes: + enable_confidential_compute (bool): + Optional. Whether the instance has + confidential compute enabled. + """ + + enable_confidential_compute: bool = proto.Field( + proto.BOOL, + number=1, + ) + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + service_account: str = proto.Field( + proto.STRING, + number=2, + ) + service_account_scopes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + pool_size: int = proto.Field( + proto.INT32, + number=5, + ) + pooled_instances: int = proto.Field( + proto.INT32, + number=12, + ) + disable_public_ip_addresses: bool = proto.Field( + proto.BOOL, + number=6, + ) + enable_nested_virtualization: bool = proto.Field( + proto.BOOL, + number=7, + ) + shielded_instance_config: 'WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig' = proto.Field( + proto.MESSAGE, + number=8, + message='WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig', + ) + confidential_instance_config: 'WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig' = proto.Field( + proto.MESSAGE, + number=10, + message='WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig', + ) + boot_disk_size_gb: int = proto.Field( + proto.INT32, + number=9, + ) + + gce_instance: 'WorkstationConfig.Host.GceInstance' = proto.Field( + proto.MESSAGE, + number=1, + oneof='config', + message='WorkstationConfig.Host.GceInstance', + ) + + class PersistentDirectory(proto.Message): + r"""A directory to persist across workstation sessions. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gce_pd (google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk): + A PersistentDirectory backed by a Compute + Engine persistent disk. + + This field is a member of `oneof`_ ``directory_type``. + mount_path (str): + Optional. Location of this directory in the + running workstation. + """ + + class GceRegionalPersistentDisk(proto.Message): + r"""A PersistentDirectory backed by a Compute Engine regional persistent + disk. The + [persistent_directories][google.cloud.workstations.v1.WorkstationConfig.persistent_directories] + field is repeated, but it may contain only one entry. It creates a + `persistent + disk `__ + that mounts to the workstation VM at ``/home`` when the session + starts and detaches when the session ends. If this field is empty, + workstations created with this configuration do not have a + persistent home directory. + + Attributes: + size_gb (int): + Optional. The GB capacity of a persistent home directory for + each workstation created with this configuration. Must be + empty if + [source_snapshot][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.source_snapshot] + is set. + + Valid values are ``10``, ``50``, ``100``, ``200``, ``500``, + or ``1000``. Defaults to ``200``. If less than ``200`` GB, + the + [disk_type][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.disk_type] + must be ``"pd-balanced"`` or ``"pd-ssd"``. + fs_type (str): + Optional. Type of file system that the disk should be + formatted with. The workstation image must support this file + system type. Must be empty if + [source_snapshot][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.source_snapshot] + is set. Defaults to ``"ext4"``. + disk_type (str): + Optional. The `type of the persistent + disk `__ + for the home directory. Defaults to ``"pd-standard"``. + source_snapshot (str): + Optional. Name of the snapshot to use as the source for the + disk. If set, + [size_gb][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.size_gb] + and + [fs_type][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.fs_type] + must be empty. + reclaim_policy (google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy): + Optional. Whether the persistent disk should be deleted when + the workstation is deleted. Valid values are ``DELETE`` and + ``RETAIN``. Defaults to ``DELETE``. + """ + class ReclaimPolicy(proto.Enum): + r"""Value representing what should happen to the disk after the + workstation is deleted. + + Values: + RECLAIM_POLICY_UNSPECIFIED (0): + Do not use. + DELETE (1): + Delete the persistent disk when deleting the + workstation. + RETAIN (2): + Keep the persistent disk when deleting the + workstation. An administrator must manually + delete the disk. + """ + RECLAIM_POLICY_UNSPECIFIED = 0 + DELETE = 1 + RETAIN = 2 + + size_gb: int = proto.Field( + proto.INT32, + number=1, + ) + fs_type: str = proto.Field( + proto.STRING, + number=2, + ) + disk_type: str = proto.Field( + proto.STRING, + number=3, + ) + source_snapshot: str = proto.Field( + proto.STRING, + number=5, + ) + reclaim_policy: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy' = proto.Field( + proto.ENUM, + number=4, + enum='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy', + ) + + gce_pd: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk' = proto.Field( + proto.MESSAGE, + number=2, + oneof='directory_type', + message='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk', + ) + mount_path: str = proto.Field( + proto.STRING, + number=1, + ) + + class Container(proto.Message): + r"""A Docker container. + + Attributes: + image (str): + Optional. A Docker container image that defines a custom + environment. + + Cloud Workstations provides a number of `preconfigured + images `__, + but you can create your own `custom container + images `__. + If using a private image, the + ``host.gceInstance.serviceAccount`` field must be specified + in the workstation configuration and must have permission to + pull the specified image. Otherwise, the image must be + publicly accessible. + command (MutableSequence[str]): + Optional. If set, overrides the default + ENTRYPOINT specified by the image. + args (MutableSequence[str]): + Optional. Arguments passed to the entrypoint. + env (MutableMapping[str, str]): + Optional. Environment variables passed to the + container's entrypoint. + working_dir (str): + Optional. If set, overrides the default DIR + specified by the image. + run_as_user (int): + Optional. If set, overrides the USER + specified in the image with the given uid. + """ + + image: str = proto.Field( + proto.STRING, + number=1, + ) + command: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + env: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + working_dir: str = proto.Field( + proto.STRING, + number=5, + ) + run_as_user: int = proto.Field( + proto.INT32, + number=6, + ) + + class CustomerEncryptionKey(proto.Message): + r"""A customer-managed encryption key (CMEK) for the Compute Engine + resources of the associated workstation configuration. Specify the + name of your Cloud KMS encryption key and the default service + account. We recommend that you use a separate service account and + follow `Cloud KMS best + practices `__. + + Attributes: + kms_key (str): + Immutable. The name of the Google Cloud KMS encryption key. + For example, + ``"projects/PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY_NAME"``. + The key must be in the same region as the workstation + configuration. + kms_key_service_account (str): + Immutable. The service account to use with the specified KMS + key. We recommend that you use a separate service account + and follow KMS best practices. For more information, see + `Separation of + duties `__ + and ``gcloud kms keys add-iam-policy-binding`` + ```--member`` `__. + """ + + kms_key: str = proto.Field( + proto.STRING, + number=1, + ) + kms_key_service_account: str = proto.Field( + proto.STRING, + number=2, + ) + + class ReadinessCheck(proto.Message): + r"""A readiness check to be performed on a workstation. + + Attributes: + path (str): + Optional. Path to which the request should be + sent. + port (int): + Optional. Port to which the request should be + sent. + """ + + path: str = proto.Field( + proto.STRING, + number=1, + ) + port: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=18, + ) + 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, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + ) + idle_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + message=duration_pb2.Duration, + ) + running_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=11, + message=duration_pb2.Duration, + ) + host: Host = proto.Field( + proto.MESSAGE, + number=12, + message=Host, + ) + persistent_directories: MutableSequence[PersistentDirectory] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=PersistentDirectory, + ) + container: Container = proto.Field( + proto.MESSAGE, + number=14, + message=Container, + ) + encryption_key: CustomerEncryptionKey = proto.Field( + proto.MESSAGE, + number=17, + message=CustomerEncryptionKey, + ) + readiness_checks: MutableSequence[ReadinessCheck] = proto.RepeatedField( + proto.MESSAGE, + number=19, + message=ReadinessCheck, + ) + replica_zones: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=23, + ) + degraded: bool = proto.Field( + proto.BOOL, + number=15, + ) + conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message=status_pb2.Status, + ) + + +class Workstation(proto.Message): + r"""A single instance of a developer workstation with its own + persistent storage. + + Attributes: + name (str): + Full name of this workstation. + display_name (str): + Optional. Human-readable name for this + workstation. + uid (str): + Output only. A system-assigned unique + identifier for this workstation. + reconciling (bool): + Output only. Indicates whether this + workstation is currently being updated to match + its intended state. + annotations (MutableMapping[str, str]): + Optional. Client-specified annotations. + labels (MutableMapping[str, str]): + Optional. + `Labels `__ + that are applied to the workstation and that are also + propagated to the underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation was + most recently updated. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation was + most recently successfully started, regardless + of the workstation's initial state. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation was + soft-deleted. + etag (str): + Optional. Checksum computed by the server. + May be sent on update and delete requests to + make sure that the client has an up-to-date + value before proceeding. + state (google.cloud.workstations_v1.types.Workstation.State): + Output only. Current state of the + workstation. + host (str): + Output only. Host to which clients can send HTTPS traffic + that will be received by the workstation. Authorized traffic + will be received to the workstation as HTTP on port 80. To + send traffic to a different port, clients may prefix the + host with the destination port in the format + ``{port}-{host}``. + """ + class State(proto.Enum): + r"""Whether a workstation is running and ready to receive user + requests. + + Values: + STATE_UNSPECIFIED (0): + Do not use. + STATE_STARTING (1): + The workstation is not yet ready to accept + requests from users but will be soon. + STATE_RUNNING (2): + The workstation is ready to accept requests + from users. + STATE_STOPPING (3): + The workstation is being stopped. + STATE_STOPPED (4): + The workstation is stopped and will not be + able to receive requests until it is started. + """ + STATE_UNSPECIFIED = 0 + STATE_STARTING = 1 + STATE_RUNNING = 2 + STATE_STOPPING = 3 + STATE_STOPPED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + 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, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=14, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + host: str = proto.Field( + proto.STRING, + number=11, + ) + + +class GetWorkstationClusterRequest(proto.Message): + r"""Request message for GetWorkstationCluster. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationClustersRequest(proto.Message): + r"""Request message for ListWorkstationClusters. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListWorkstationClustersResponse(proto.Message): + r"""Response message for ListWorkstationClusters. + + Attributes: + workstation_clusters (MutableSequence[google.cloud.workstations_v1.types.WorkstationCluster]): + The requested workstation clusters. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_clusters: MutableSequence['WorkstationCluster'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationCluster', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationClusterRequest(proto.Message): + r"""Message for creating a CreateWorkstationCluster. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_cluster_id (str): + Required. ID to use for the workstation + cluster. + workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): + Required. Workstation cluster to create. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation_cluster: 'WorkstationCluster' = proto.Field( + proto.MESSAGE, + number=3, + message='WorkstationCluster', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationClusterRequest(proto.Message): + r"""Request message for UpdateWorkstationCluster. + + Attributes: + workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): + Required. Workstation cluster to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask that specifies which fields in + the workstation cluster should be updated. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + allow_missing (bool): + Optional. If set, and the workstation cluster is not found, + a new workstation cluster will be created. In this + situation, update_mask is ignored. + """ + + workstation_cluster: 'WorkstationCluster' = proto.Field( + proto.MESSAGE, + number=1, + message='WorkstationCluster', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationClusterRequest(proto.Message): + r"""Message for deleting a workstation cluster. + + Attributes: + name (str): + Required. Name of the workstation cluster to + delete. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not apply it. + etag (str): + Optional. If set, the request will be + rejected if the latest version of the + workstation cluster on the server does not have + this ETag. + force (bool): + Optional. If set, any workstation + configurations and workstations in the + workstation cluster are also deleted. Otherwise, + the request only works if the workstation + cluster has no configurations or workstations. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetWorkstationConfigRequest(proto.Message): + r"""Request message for GetWorkstationConfig. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationConfigsRequest(proto.Message): + r"""Request message for ListWorkstationConfigs. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListWorkstationConfigsResponse(proto.Message): + r"""Response message for ListWorkstationConfigs. + + Attributes: + workstation_configs (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig]): + The requested configs. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationConfigsRequest(proto.Message): + r"""Request message for ListUsableWorkstationConfigs. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListUsableWorkstationConfigsResponse(proto.Message): + r"""Response message for ListUsableWorkstationConfigs. + + Attributes: + workstation_configs (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig]): + The requested configs. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationConfigRequest(proto.Message): + r"""Message for creating a CreateWorkstationConfig. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_config_id (str): + Required. ID to use for the workstation + configuration. + workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): + Required. Config to create. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_config_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation_config: 'WorkstationConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='WorkstationConfig', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationConfigRequest(proto.Message): + r"""Request message for UpdateWorkstationConfig. + + Attributes: + workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): + Required. Config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which fields in the + workstation configuration should be updated. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + allow_missing (bool): + Optional. If set and the workstation configuration is not + found, a new workstation configuration will be created. In + this situation, update_mask is ignored. + """ + + workstation_config: 'WorkstationConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationConfigRequest(proto.Message): + r"""Message for deleting a workstation configuration. + + Attributes: + name (str): + Required. Name of the workstation + configuration to delete. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + etag (str): + Optional. If set, the request is rejected if + the latest version of the workstation + configuration on the server does not have this + ETag. + force (bool): + Optional. If set, any workstations in the + workstation configuration are also deleted. + Otherwise, the request works only if the + workstation configuration has no workstations. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetWorkstationRequest(proto.Message): + r"""Request message for GetWorkstation. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationsRequest(proto.Message): + r"""Request message for ListWorkstations. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListWorkstationsResponse(proto.Message): + r"""Response message for ListWorkstations. + + Attributes: + workstations (MutableSequence[google.cloud.workstations_v1.types.Workstation]): + The requested workstations. + next_page_token (str): + Optional. Token to retrieve the next page of + results, or empty if there are no more results + in the list. + unreachable (MutableSequence[str]): + Optional. Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstations: MutableSequence['Workstation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workstation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationsRequest(proto.Message): + r"""Request message for ListUsableWorkstations. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListUsableWorkstationsResponse(proto.Message): + r"""Response message for ListUsableWorkstations. + + Attributes: + workstations (MutableSequence[google.cloud.workstations_v1.types.Workstation]): + The requested workstations. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstations: MutableSequence['Workstation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workstation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationRequest(proto.Message): + r"""Message for creating a CreateWorkstation. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_id (str): + Required. ID to use for the workstation. + workstation (google.cloud.workstations_v1.types.Workstation): + Required. Workstation to create. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation: 'Workstation' = proto.Field( + proto.MESSAGE, + number=3, + message='Workstation', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationRequest(proto.Message): + r"""Request message for UpdateWorkstation. + + Attributes: + workstation (google.cloud.workstations_v1.types.Workstation): + Required. Workstation to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which fields in the + workstation configuration should be updated. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + allow_missing (bool): + Optional. If set and the workstation configuration is not + found, a new workstation configuration is created. In this + situation, update_mask is ignored. + """ + + workstation: 'Workstation' = proto.Field( + proto.MESSAGE, + number=1, + message='Workstation', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationRequest(proto.Message): + r"""Request message for DeleteWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to delete. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + etag (str): + Optional. If set, the request will be + rejected if the latest version of the + workstation on the server does not have this + ETag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class StartWorkstationRequest(proto.Message): + r"""Request message for StartWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to start. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + etag (str): + Optional. If set, the request will be + rejected if the latest version of the + workstation on the server does not have this + ETag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class StopWorkstationRequest(proto.Message): + r"""Request message for StopWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to stop. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + etag (str): + Optional. If set, the request will be + rejected if the latest version of the + workstation on the server does not have this + ETag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GenerateAccessTokenRequest(proto.Message): + r"""Request message for GenerateAccessToken. + + 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: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Desired expiration time of the access token. + This value must be at most 24 hours in the + future. If a value is not specified, the token's + expiration time will be set to a default value + of 1 hour in the future. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Desired lifetime duration of the access + token. This value must be at most 24 hours. If a + value is not specified, the token's lifetime + will be set to a default value of 1 hour. + + This field is a member of `oneof`_ ``expiration``. + workstation (str): + Required. Name of the workstation for which + the access token should be generated. + """ + + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + oneof='expiration', + message=duration_pb2.Duration, + ) + workstation: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateAccessTokenResponse(proto.Message): + r"""Response message for GenerateAccessToken. + + Attributes: + access_token (str): + The generated bearer access token. To use this token, + include it in an Authorization header of an HTTP request + sent to the associated workstation's hostname—for example, + ``Authorization: Bearer ``. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the generated token will + expire. + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class OperationMetadata(proto.Message): + r"""Metadata for long-running operations. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time that the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time that the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has + requested cancellation of the operation. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_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, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workstations/v1/mypy.ini b/owl-bot-staging/google-cloud-workstations/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workstations/v1/noxfile.py b/owl-bot-staging/google-cloud-workstations/v1/noxfile.py new file mode 100644 index 000000000000..b98447b026a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations' + +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/cloud/workstations_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/cloud/workstations_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-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json new file mode 100644 index 000000000000..8dabda2a933a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json @@ -0,0 +1,3307 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.workstations.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-workstations", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1.types.WorkstationCluster" + }, + { + "name": "workstation_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation_cluster" + }, + "description": "Sample for CreateWorkstationCluster", + "file": "workstations_v1_generated_workstations_create_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationCluster_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_create_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1.types.WorkstationCluster" + }, + { + "name": "workstation_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation_cluster" + }, + "description": "Sample for CreateWorkstationCluster", + "file": "workstations_v1_generated_workstations_create_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationCluster_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_create_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1.types.WorkstationConfig" + }, + { + "name": "workstation_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation_config" + }, + "description": "Sample for CreateWorkstationConfig", + "file": "workstations_v1_generated_workstations_create_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationConfig_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_create_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1.types.WorkstationConfig" + }, + { + "name": "workstation_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation_config" + }, + "description": "Sample for CreateWorkstationConfig", + "file": "workstations_v1_generated_workstations_create_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationConfig_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_create_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1.types.Workstation" + }, + { + "name": "workstation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation" + }, + "description": "Sample for CreateWorkstation", + "file": "workstations_v1_generated_workstations_create_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstation_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_create_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1.types.Workstation" + }, + { + "name": "workstation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation" + }, + "description": "Sample for CreateWorkstation", + "file": "workstations_v1_generated_workstations_create_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstation_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_create_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_workstation_cluster" + }, + "description": "Sample for DeleteWorkstationCluster", + "file": "workstations_v1_generated_workstations_delete_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationCluster_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_delete_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_workstation_cluster" + }, + "description": "Sample for DeleteWorkstationCluster", + "file": "workstations_v1_generated_workstations_delete_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_delete_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_workstation_config" + }, + "description": "Sample for DeleteWorkstationConfig", + "file": "workstations_v1_generated_workstations_delete_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationConfig_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_delete_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_workstation_config" + }, + "description": "Sample for DeleteWorkstationConfig", + "file": "workstations_v1_generated_workstations_delete_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_delete_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_workstation" + }, + "description": "Sample for DeleteWorkstation", + "file": "workstations_v1_generated_workstations_delete_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_delete_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_workstation" + }, + "description": "Sample for DeleteWorkstation", + "file": "workstations_v1_generated_workstations_delete_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_delete_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.generate_access_token", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GenerateAccessToken", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GenerateAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GenerateAccessTokenRequest" + }, + { + "name": "workstation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.GenerateAccessTokenResponse", + "shortName": "generate_access_token" + }, + "description": "Sample for GenerateAccessToken", + "file": "workstations_v1_generated_workstations_generate_access_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GenerateAccessToken_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": "workstations_v1_generated_workstations_generate_access_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.generate_access_token", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GenerateAccessToken", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GenerateAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GenerateAccessTokenRequest" + }, + { + "name": "workstation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.GenerateAccessTokenResponse", + "shortName": "generate_access_token" + }, + "description": "Sample for GenerateAccessToken", + "file": "workstations_v1_generated_workstations_generate_access_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GenerateAccessToken_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": "workstations_v1_generated_workstations_generate_access_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.WorkstationCluster", + "shortName": "get_workstation_cluster" + }, + "description": "Sample for GetWorkstationCluster", + "file": "workstations_v1_generated_workstations_get_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstationCluster_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": "workstations_v1_generated_workstations_get_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.WorkstationCluster", + "shortName": "get_workstation_cluster" + }, + "description": "Sample for GetWorkstationCluster", + "file": "workstations_v1_generated_workstations_get_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstationCluster_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": "workstations_v1_generated_workstations_get_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.WorkstationConfig", + "shortName": "get_workstation_config" + }, + "description": "Sample for GetWorkstationConfig", + "file": "workstations_v1_generated_workstations_get_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstationConfig_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": "workstations_v1_generated_workstations_get_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.WorkstationConfig", + "shortName": "get_workstation_config" + }, + "description": "Sample for GetWorkstationConfig", + "file": "workstations_v1_generated_workstations_get_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstationConfig_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": "workstations_v1_generated_workstations_get_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.Workstation", + "shortName": "get_workstation" + }, + "description": "Sample for GetWorkstation", + "file": "workstations_v1_generated_workstations_get_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstation_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": "workstations_v1_generated_workstations_get_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.Workstation", + "shortName": "get_workstation" + }, + "description": "Sample for GetWorkstation", + "file": "workstations_v1_generated_workstations_get_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstation_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": "workstations_v1_generated_workstations_get_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_usable_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager", + "shortName": "list_usable_workstation_configs" + }, + "description": "Sample for ListUsableWorkstationConfigs", + "file": "workstations_v1_generated_workstations_list_usable_workstation_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1_generated_workstations_list_usable_workstation_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_usable_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsPager", + "shortName": "list_usable_workstation_configs" + }, + "description": "Sample for ListUsableWorkstationConfigs", + "file": "workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_usable_workstations", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListUsableWorkstationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationsAsyncPager", + "shortName": "list_usable_workstations" + }, + "description": "Sample for ListUsableWorkstations", + "file": "workstations_v1_generated_workstations_list_usable_workstations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstations_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": "workstations_v1_generated_workstations_list_usable_workstations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_usable_workstations", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListUsableWorkstationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationsPager", + "shortName": "list_usable_workstations" + }, + "description": "Sample for ListUsableWorkstations", + "file": "workstations_v1_generated_workstations_list_usable_workstations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstations_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": "workstations_v1_generated_workstations_list_usable_workstations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstation_clusters", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationClusters", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationClustersAsyncPager", + "shortName": "list_workstation_clusters" + }, + "description": "Sample for ListWorkstationClusters", + "file": "workstations_v1_generated_workstations_list_workstation_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstationClusters_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": "workstations_v1_generated_workstations_list_workstation_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstation_clusters", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationClusters", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationClustersPager", + "shortName": "list_workstation_clusters" + }, + "description": "Sample for ListWorkstationClusters", + "file": "workstations_v1_generated_workstations_list_workstation_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstationClusters_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": "workstations_v1_generated_workstations_list_workstation_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationConfigsAsyncPager", + "shortName": "list_workstation_configs" + }, + "description": "Sample for ListWorkstationConfigs", + "file": "workstations_v1_generated_workstations_list_workstation_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1_generated_workstations_list_workstation_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationConfigsPager", + "shortName": "list_workstation_configs" + }, + "description": "Sample for ListWorkstationConfigs", + "file": "workstations_v1_generated_workstations_list_workstation_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1_generated_workstations_list_workstation_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstations", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationsAsyncPager", + "shortName": "list_workstations" + }, + "description": "Sample for ListWorkstations", + "file": "workstations_v1_generated_workstations_list_workstations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstations_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": "workstations_v1_generated_workstations_list_workstations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstations", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationsPager", + "shortName": "list_workstations" + }, + "description": "Sample for ListWorkstations", + "file": "workstations_v1_generated_workstations_list_workstations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstations_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": "workstations_v1_generated_workstations_list_workstations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.start_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.StartWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "StartWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.StartWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "start_workstation" + }, + "description": "Sample for StartWorkstation", + "file": "workstations_v1_generated_workstations_start_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_StartWorkstation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_start_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.start_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.StartWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "StartWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.StartWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "start_workstation" + }, + "description": "Sample for StartWorkstation", + "file": "workstations_v1_generated_workstations_start_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_StartWorkstation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_start_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.stop_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.StopWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "StopWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.StopWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "stop_workstation" + }, + "description": "Sample for StopWorkstation", + "file": "workstations_v1_generated_workstations_stop_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_StopWorkstation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_stop_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.stop_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.StopWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "StopWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.StopWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "stop_workstation" + }, + "description": "Sample for StopWorkstation", + "file": "workstations_v1_generated_workstations_stop_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_StopWorkstation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_stop_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1.types.WorkstationCluster" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_workstation_cluster" + }, + "description": "Sample for UpdateWorkstationCluster", + "file": "workstations_v1_generated_workstations_update_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationCluster_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_update_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1.types.WorkstationCluster" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_workstation_cluster" + }, + "description": "Sample for UpdateWorkstationCluster", + "file": "workstations_v1_generated_workstations_update_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_update_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1.types.WorkstationConfig" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_workstation_config" + }, + "description": "Sample for UpdateWorkstationConfig", + "file": "workstations_v1_generated_workstations_update_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationConfig_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_update_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1.types.WorkstationConfig" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_workstation_config" + }, + "description": "Sample for UpdateWorkstationConfig", + "file": "workstations_v1_generated_workstations_update_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_update_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationRequest" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1.types.Workstation" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_workstation" + }, + "description": "Sample for UpdateWorkstation", + "file": "workstations_v1_generated_workstations_update_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstation_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_update_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationRequest" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1.types.Workstation" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_workstation" + }, + "description": "Sample for UpdateWorkstation", + "file": "workstations_v1_generated_workstations_update_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstation_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1_generated_workstations_update_workstation_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py new file mode 100644 index 000000000000..da9caa9dfb44 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_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 CreateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_create_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py new file mode 100644 index 000000000000..25e77620a6d7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_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 CreateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py new file mode 100644 index 000000000000..fa95cde5c45b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_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 CreateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py new file mode 100644 index 000000000000..3388a7112edb --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_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 CreateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_create_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py new file mode 100644 index 000000000000..944fdc87ea43 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_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 CreateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_create_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py new file mode 100644 index 000000000000..514350dc4abd --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_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 CreateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_create_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py new file mode 100644 index 000000000000..82e6981832ab --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_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 DeleteWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_delete_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py new file mode 100644 index 000000000000..1071be9b0c41 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_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 DeleteWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py new file mode 100644 index 000000000000..88853e5cb549 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_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 DeleteWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py new file mode 100644 index 000000000000..c5bed5490628 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_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 DeleteWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_delete_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py new file mode 100644 index 000000000000..9b02260244de --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_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 DeleteWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_delete_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py new file mode 100644 index 000000000000..26261d76f5dc --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_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 DeleteWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_delete_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py new file mode 100644 index 000000000000..32a3d6878667 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_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 GenerateAccessToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GenerateAccessToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_generate_access_token(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = await client.generate_access_token(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GenerateAccessToken_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py new file mode 100644 index 000000000000..43530eef1bcb --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_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 GenerateAccessToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GenerateAccessToken_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_generate_access_token(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = client.generate_access_token(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GenerateAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py new file mode 100644 index 000000000000..38d2ce054fa8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_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 GetWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_get_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py new file mode 100644 index 000000000000..f82d2afc6418 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_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 GetWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py new file mode 100644 index 000000000000..941ca6de929f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_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 GetWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py new file mode 100644 index 000000000000..6b8c4cf6d4cc --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_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 GetWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_get_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_config(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py new file mode 100644 index 000000000000..6adba3ae5d6a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_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 GetWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_get_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_config(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py new file mode 100644 index 000000000000..a2585a4cabaf --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_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 GetWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_get_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py new file mode 100644 index 000000000000..13af6452678f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_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 ListUsableWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py new file mode 100644 index 000000000000..6d41579a13e7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_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 ListUsableWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py new file mode 100644 index 000000000000..b14a660ef62a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_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 ListUsableWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListUsableWorkstations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_usable_workstations(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListUsableWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py new file mode 100644 index 000000000000..4c3f026ce7ab --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_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 ListUsableWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListUsableWorkstations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_usable_workstations(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListUsableWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py new file mode 100644 index 000000000000..1807120300e5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_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 ListWorkstationClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstationClusters_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstationClusters_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py new file mode 100644 index 000000000000..6ccf5d82795d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_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 ListWorkstationClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstationClusters_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstationClusters_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py new file mode 100644 index 000000000000..771317f07927 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_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 ListWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py new file mode 100644 index 000000000000..d1c5922918ed --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_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 ListWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py new file mode 100644 index 000000000000..6f55b87c0f16 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_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 ListWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_workstations(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py new file mode 100644 index 000000000000..150093503948 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_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 ListWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_workstations(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py new file mode 100644 index 000000000000..6d6ceafebe49 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_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 StartWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_StartWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_start_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_StartWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py new file mode 100644 index 000000000000..9f206e166057 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_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 StartWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_StartWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_start_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_StartWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py new file mode 100644 index 000000000000..03a3c895665b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_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 StopWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_StopWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_stop_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_StopWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py new file mode 100644 index 000000000000..a584d0e232d8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_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 StopWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_StopWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_stop_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_StopWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py new file mode 100644 index 000000000000..04d0e9a0d277 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_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 UpdateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_update_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py new file mode 100644 index 000000000000..337918ad3af6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_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 UpdateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py new file mode 100644 index 000000000000..9442c1046878 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_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 UpdateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py new file mode 100644 index 000000000000..051ed5dadf59 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_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 UpdateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_update_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py new file mode 100644 index 000000000000..599181d6399b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_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 UpdateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_update_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py new file mode 100644 index 000000000000..906d0acb553a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_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 UpdateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_update_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py b/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py new file mode 100644 index 000000000000..d5f36b76dcbd --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py @@ -0,0 +1,195 @@ +#! /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 workstationsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_workstation': ('parent', 'workstation_id', 'workstation', 'validate_only', ), + 'create_workstation_cluster': ('parent', 'workstation_cluster_id', 'workstation_cluster', 'validate_only', ), + 'create_workstation_config': ('parent', 'workstation_config_id', 'workstation_config', 'validate_only', ), + 'delete_workstation': ('name', 'validate_only', 'etag', ), + 'delete_workstation_cluster': ('name', 'validate_only', 'etag', 'force', ), + 'delete_workstation_config': ('name', 'validate_only', 'etag', 'force', ), + 'generate_access_token': ('workstation', 'expire_time', 'ttl', ), + 'get_workstation': ('name', ), + 'get_workstation_cluster': ('name', ), + 'get_workstation_config': ('name', ), + 'list_usable_workstation_configs': ('parent', 'page_size', 'page_token', ), + 'list_usable_workstations': ('parent', 'page_size', 'page_token', ), + 'list_workstation_clusters': ('parent', 'page_size', 'page_token', ), + 'list_workstation_configs': ('parent', 'page_size', 'page_token', ), + 'list_workstations': ('parent', 'page_size', 'page_token', ), + 'start_workstation': ('name', 'validate_only', 'etag', ), + 'stop_workstation': ('name', 'validate_only', 'etag', ), + 'update_workstation': ('workstation', 'update_mask', 'validate_only', 'allow_missing', ), + 'update_workstation_cluster': ('workstation_cluster', 'update_mask', 'validate_only', 'allow_missing', ), + 'update_workstation_config': ('workstation_config', 'update_mask', 'validate_only', 'allow_missing', ), + } + + 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=workstationsCallTransformer(), +): + """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 workstations 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-cloud-workstations/v1/setup.py b/owl-bot-staging/google-cloud-workstations/v1/setup.py new file mode 100644 index 000000000000..6106efcf5486 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations' + + +description = "Google Cloud Workstations API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/workstations/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", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations" + +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-cloud-workstations/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_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-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py new file mode 100644 index 000000000000..cdc2049a589c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py @@ -0,0 +1,17992 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.location import locations_pb2 +from google.cloud.workstations_v1.services.workstations import WorkstationsAsyncClient +from google.cloud.workstations_v1.services.workstations import WorkstationsClient +from google.cloud.workstations_v1.services.workstations import pagers +from google.cloud.workstations_v1.services.workstations import transports +from google.cloud.workstations_v1.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +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 WorkstationsClient._get_default_mtls_endpoint(None) is None + assert WorkstationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert WorkstationsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WorkstationsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WorkstationsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + WorkstationsClient._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 WorkstationsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WorkstationsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WorkstationsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WorkstationsClient._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 WorkstationsClient._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 WorkstationsClient._get_client_cert_source(None, False) is None + assert WorkstationsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert WorkstationsClient._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 WorkstationsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert WorkstationsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WorkstationsClient._DEFAULT_UNIVERSE + default_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert WorkstationsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert WorkstationsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT + assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "always") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT + assert WorkstationsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT + assert WorkstationsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + WorkstationsClient._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 WorkstationsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert WorkstationsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert WorkstationsClient._get_universe_domain(None, None) == WorkstationsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + WorkstationsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WorkstationsClient, "grpc"), + (WorkstationsAsyncClient, "grpc_asyncio"), + (WorkstationsClient, "rest"), +]) +def test_workstations_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 == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workstations.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WorkstationsGrpcTransport, "grpc"), + (transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WorkstationsRestTransport, "rest"), +]) +def test_workstations_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", [ + (WorkstationsClient, "grpc"), + (WorkstationsAsyncClient, "grpc_asyncio"), + (WorkstationsClient, "rest"), +]) +def test_workstations_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 == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workstations.googleapis.com' + ) + + +def test_workstations_client_get_transport_class(): + transport = WorkstationsClient.get_transport_class() + available_transports = [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsRestTransport, + ] + assert transport in available_transports + + transport = WorkstationsClient.get_transport_class("grpc") + assert transport == transports.WorkstationsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) +def test_workstations_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(WorkstationsClient, '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(WorkstationsClient, '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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "true"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "false"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "true"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "false"), +]) +@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_workstations_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", [ + WorkstationsClient, WorkstationsAsyncClient +]) +@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) +def test_workstations_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", [ + WorkstationsClient, WorkstationsAsyncClient +]) +@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) +def test_workstations_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WorkstationsClient._DEFAULT_UNIVERSE + default_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WorkstationsClient._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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +def test_workstations_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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", None), +]) +def test_workstations_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_workstations_client_client_options_from_dict(): + with mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WorkstationsClient( + 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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_workstations_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( + "workstations.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="workstations.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationClusterRequest, + dict, +]) +def test_get_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + ) + response = client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +def test_get_workstation_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.GetWorkstationClusterRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_workstation_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationClusterRequest( + name='name_value', + ) + +def test_get_workstation_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation_cluster] = mock_rpc + request = {} + client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods + + # 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_workstation_cluster] = mock_rpc + + request = {} + await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + )) + response = await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +@pytest.mark.asyncio +async def test_get_workstation_cluster_async_from_dict(): + await test_get_workstation_cluster_async(request_type=dict) + +def test_get_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = workstations.WorkstationCluster() + client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) + await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation_cluster( + 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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation_cluster( + 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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationClustersRequest, + dict, +]) +def test_list_workstation_clusters(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_clusters_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListWorkstationClustersRequest( + 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_workstation_clusters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workstation_clusters(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationClustersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_workstation_clusters_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_clusters] = mock_rpc + request = {} + client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstation_clusters(request) + + # Establish that a new wrapper 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_workstation_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_clusters in client._client._transport._wrapped_methods + + # 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_workstation_clusters] = mock_rpc + + request = {} + await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workstation_clusters(request) + + # Establish that a new wrapper 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_workstation_clusters_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationClustersRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async_from_dict(): + await test_list_workstation_clusters_async(request_type=dict) + +def test_list_workstation_clusters_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = workstations.ListWorkstationClustersResponse() + client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_clusters_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) + await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_clusters_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstation_clusters( + 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_workstation_clusters_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstation_clusters_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstation_clusters( + 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_workstation_clusters_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + + +def test_list_workstation_clusters_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstation_clusters(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, workstations.WorkstationCluster) + for i in results) +def test_list_workstation_clusters_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstation_clusters(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_workstation_clusters_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstation_clusters(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, workstations.WorkstationCluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + 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_workstation_clusters(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", [ + workstations.CreateWorkstationClusterRequest, + dict, +]) +def test_create_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.CreateWorkstationClusterRequest( + parent='parent_value', + workstation_cluster_id='workstation_cluster_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_workstation_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationClusterRequest( + parent='parent_value', + workstation_cluster_id='workstation_cluster_id_value', + ) + +def test_create_workstation_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + request = {} + client.create_workstation_cluster(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.create_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods + + # 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_workstation_cluster] = mock_rpc + + request = {} + await client.create_workstation_cluster(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.create_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationClusterRequest() + 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_create_workstation_cluster_async_from_dict(): + await test_create_workstation_cluster_async(request_type=dict) + +def test_create_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_workstation_cluster( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_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].workstation_cluster + mock_val = workstations.WorkstationCluster(name='name_value') + assert arg == mock_val + arg = args[0].workstation_cluster_id + mock_val = 'workstation_cluster_id_value' + assert arg == mock_val + + +def test_create_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_workstation_cluster( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_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].workstation_cluster + mock_val = workstations.WorkstationCluster(name='name_value') + assert arg == mock_val + arg = args[0].workstation_cluster_id + mock_val = 'workstation_cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationClusterRequest, + dict, +]) +def test_update_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.UpdateWorkstationClusterRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_workstation_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationClusterRequest( + ) + +def test_update_workstation_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + request = {} + client.update_workstation_cluster(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.update_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods + + # 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_workstation_cluster] = mock_rpc + + request = {} + await client.update_workstation_cluster(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.update_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationClusterRequest() + 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_update_workstation_cluster_async_from_dict(): + await test_update_workstation_cluster_async(request_type=dict) + +def test_update_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationClusterRequest() + + request.workstation_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationClusterRequest() + + request.workstation_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_workstation_cluster( + workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster + mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_workstation_cluster( + workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster + mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationClusterRequest, + dict, +]) +def test_delete_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.DeleteWorkstationClusterRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_workstation_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationClusterRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_workstation_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + request = {} + client.delete_workstation_cluster(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.delete_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods + + # 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_workstation_cluster] = mock_rpc + + request = {} + await client.delete_workstation_cluster(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.delete_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationClusterRequest() + 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_delete_workstation_cluster_async_from_dict(): + await test_delete_workstation_cluster_async(request_type=dict) + +def test_delete_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_workstation_cluster( + 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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_workstation_cluster( + 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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationConfigRequest, + dict, +]) +def test_get_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + replica_zones=['replica_zones_value'], + degraded=True, + ) + response = client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.replica_zones == ['replica_zones_value'] + assert response.degraded is True + + +def test_get_workstation_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.GetWorkstationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_workstation_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationConfigRequest( + name='name_value', + ) + +def test_get_workstation_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation_config] = mock_rpc + request = {} + client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_config in client._client._transport._wrapped_methods + + # 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_workstation_config] = mock_rpc + + request = {} + await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + replica_zones=['replica_zones_value'], + degraded=True, + )) + response = await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.replica_zones == ['replica_zones_value'] + assert response.degraded is True + + +@pytest.mark.asyncio +async def test_get_workstation_config_async_from_dict(): + await test_get_workstation_config_async(request_type=dict) + +def test_get_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = workstations.WorkstationConfig() + client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) + await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation_config( + 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_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation_config( + 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_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationConfigsRequest, + dict, +]) +def test_list_workstation_configs(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListWorkstationConfigsRequest( + 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_workstation_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workstation_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_workstation_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_configs] = mock_rpc + request = {} + client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstation_configs(request) + + # Establish that a new wrapper 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_workstation_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_configs in client._client._transport._wrapped_methods + + # 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_workstation_configs] = mock_rpc + + request = {} + await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workstation_configs(request) + + # Establish that a new wrapper 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_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationConfigsRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstation_configs_async_from_dict(): + await test_list_workstation_configs_async(request_type=dict) + +def test_list_workstation_configs_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListWorkstationConfigsResponse() + client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_configs_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) + await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_configs_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstation_configs( + 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_workstation_configs_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstation_configs_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstation_configs( + 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_workstation_configs_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_workstation_configs_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstation_configs(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, workstations.WorkstationConfig) + for i in results) +def test_list_workstation_configs_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstation_configs(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_workstation_configs_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstation_configs(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, workstations.WorkstationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstation_configs_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + 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_workstation_configs(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", [ + workstations.ListUsableWorkstationConfigsRequest, + dict, +]) +def test_list_usable_workstation_configs(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListUsableWorkstationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstation_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListUsableWorkstationConfigsRequest( + 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_usable_workstation_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_usable_workstation_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_usable_workstation_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_usable_workstation_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_usable_workstation_configs] = mock_rpc + request = {} + client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_usable_workstation_configs(request) + + # Establish that a new wrapper 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_usable_workstation_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_usable_workstation_configs in client._client._transport._wrapped_methods + + # 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_usable_workstation_configs] = mock_rpc + + request = {} + await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_usable_workstation_configs(request) + + # Establish that a new wrapper 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_usable_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationConfigsRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListUsableWorkstationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async_from_dict(): + await test_list_usable_workstation_configs_async(request_type=dict) + +def test_list_usable_workstation_configs_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_usable_workstation_configs_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) + await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_usable_workstation_configs_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_usable_workstation_configs( + 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_usable_workstation_configs_flattened_error(): + client = WorkstationsClient( + credentials=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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_usable_workstation_configs( + 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_usable_workstation_configs_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstation_configs_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_usable_workstation_configs(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, workstations.WorkstationConfig) + for i in results) +def test_list_usable_workstation_configs_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_usable_workstation_configs(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_usable_workstation_configs_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_usable_workstation_configs(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, workstations.WorkstationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + 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_usable_workstation_configs(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", [ + workstations.CreateWorkstationConfigRequest, + dict, +]) +def test_create_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.CreateWorkstationConfigRequest( + parent='parent_value', + workstation_config_id='workstation_config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_workstation_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationConfigRequest( + parent='parent_value', + workstation_config_id='workstation_config_id_value', + ) + +def test_create_workstation_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + request = {} + client.create_workstation_config(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.create_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_config in client._client._transport._wrapped_methods + + # 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_workstation_config] = mock_rpc + + request = {} + await client.create_workstation_config(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.create_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationConfigRequest() + 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_create_workstation_config_async_from_dict(): + await test_create_workstation_config_async(request_type=dict) + +def test_create_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_workstation_config( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_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].workstation_config + mock_val = workstations.WorkstationConfig(name='name_value') + assert arg == mock_val + arg = args[0].workstation_config_id + mock_val = 'workstation_config_id_value' + assert arg == mock_val + + +def test_create_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_workstation_config( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_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].workstation_config + mock_val = workstations.WorkstationConfig(name='name_value') + assert arg == mock_val + arg = args[0].workstation_config_id + mock_val = 'workstation_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationConfigRequest, + dict, +]) +def test_update_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.UpdateWorkstationConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_workstation_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationConfigRequest( + ) + +def test_update_workstation_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + request = {} + client.update_workstation_config(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.update_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_config in client._client._transport._wrapped_methods + + # 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_workstation_config] = mock_rpc + + request = {} + await client.update_workstation_config(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.update_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationConfigRequest() + 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_update_workstation_config_async_from_dict(): + await test_update_workstation_config_async(request_type=dict) + +def test_update_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationConfigRequest() + + request.workstation_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationConfigRequest() + + request.workstation_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_config.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_workstation_config( + workstation_config=workstations.WorkstationConfig(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].workstation_config + mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_workstation_config( + workstation_config=workstations.WorkstationConfig(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].workstation_config + mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationConfigRequest, + dict, +]) +def test_delete_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.DeleteWorkstationConfigRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_workstation_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationConfigRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_workstation_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + request = {} + client.delete_workstation_config(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.delete_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_config in client._client._transport._wrapped_methods + + # 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_workstation_config] = mock_rpc + + request = {} + await client.delete_workstation_config(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.delete_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationConfigRequest() + 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_delete_workstation_config_async_from_dict(): + await test_delete_workstation_config_async(request_type=dict) + +def test_delete_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_workstation_config( + 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_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_workstation_config( + 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_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationRequest, + dict, +]) +def test_get_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + ) + response = client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +def test_get_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.GetWorkstationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationRequest( + name='name_value', + ) + +def test_get_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation] = mock_rpc + request = {} + client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation(request) + + # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation in client._client._transport._wrapped_methods + + # 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_workstation] = mock_rpc + + request = {} + await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_workstation(request) + + # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + )) + response = await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +@pytest.mark.asyncio +async def test_get_workstation_async_from_dict(): + await test_get_workstation_async(request_type=dict) + +def test_get_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = workstations.Workstation() + client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) + await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation( + 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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation( + 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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationsRequest, + dict, +]) +def test_list_workstations(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListWorkstationsRequest( + 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_workstations), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workstations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_workstations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstations] = mock_rpc + request = {} + client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstations(request) + + # Establish that a new wrapper 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_workstations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstations in client._client._transport._wrapped_methods + + # 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_workstations] = mock_rpc + + request = {} + await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workstations(request) + + # Establish that a new wrapper 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_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationsRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstations_async_from_dict(): + await test_list_workstations_async(request_type=dict) + +def test_list_workstations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = workstations.ListWorkstationsResponse() + client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) + await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstations_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstations( + 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_workstations_flattened_error(): + client = WorkstationsClient( + credentials=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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstations_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstations( + 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_workstations_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_workstations_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstations(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, workstations.Workstation) + for i in results) +def test_list_workstations_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstations(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_workstations_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstations(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, workstations.Workstation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstations_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + 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_workstations(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", [ + workstations.ListUsableWorkstationsRequest, + dict, +]) +def test_list_usable_workstations(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListUsableWorkstationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListUsableWorkstationsRequest( + 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_usable_workstations), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_usable_workstations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_usable_workstations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_usable_workstations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_usable_workstations] = mock_rpc + request = {} + client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_usable_workstations(request) + + # Establish that a new wrapper 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_usable_workstations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_usable_workstations in client._client._transport._wrapped_methods + + # 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_usable_workstations] = mock_rpc + + request = {} + await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_usable_workstations(request) + + # Establish that a new wrapper 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_usable_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationsRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListUsableWorkstationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_usable_workstations_async_from_dict(): + await test_list_usable_workstations_async(request_type=dict) + +def test_list_usable_workstations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationsResponse() + client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_usable_workstations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) + await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_usable_workstations_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_usable_workstations( + 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_usable_workstations_flattened_error(): + client = WorkstationsClient( + credentials=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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_usable_workstations_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_usable_workstations( + 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_usable_workstations_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstations_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_usable_workstations(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, workstations.Workstation) + for i in results) +def test_list_usable_workstations_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_usable_workstations(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_usable_workstations_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_usable_workstations(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, workstations.Workstation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_usable_workstations_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + 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_usable_workstations(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", [ + workstations.CreateWorkstationRequest, + dict, +]) +def test_create_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.CreateWorkstationRequest( + parent='parent_value', + workstation_id='workstation_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationRequest( + parent='parent_value', + workstation_id='workstation_id_value', + ) + +def test_create_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + request = {} + client.create_workstation(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.create_workstation(request) + + # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation in client._client._transport._wrapped_methods + + # 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_workstation] = mock_rpc + + request = {} + await client.create_workstation(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.create_workstation(request) + + # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationRequest() + 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_create_workstation_async_from_dict(): + await test_create_workstation_async(request_type=dict) + +def test_create_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_workstation( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_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].workstation + mock_val = workstations.Workstation(name='name_value') + assert arg == mock_val + arg = args[0].workstation_id + mock_val = 'workstation_id_value' + assert arg == mock_val + + +def test_create_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_workstation( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_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].workstation + mock_val = workstations.Workstation(name='name_value') + assert arg == mock_val + arg = args[0].workstation_id + mock_val = 'workstation_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationRequest, + dict, +]) +def test_update_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.UpdateWorkstationRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationRequest( + ) + +def test_update_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + request = {} + client.update_workstation(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.update_workstation(request) + + # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation in client._client._transport._wrapped_methods + + # 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_workstation] = mock_rpc + + request = {} + await client.update_workstation(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.update_workstation(request) + + # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationRequest() + 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_update_workstation_async_from_dict(): + await test_update_workstation_async(request_type=dict) + +def test_update_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationRequest() + + request.workstation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationRequest() + + request.workstation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_workstation( + workstation=workstations.Workstation(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].workstation + mock_val = workstations.Workstation(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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_workstation( + workstation=workstations.Workstation(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].workstation + mock_val = workstations.Workstation(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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationRequest, + dict, +]) +def test_delete_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.DeleteWorkstationRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + request = {} + client.delete_workstation(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.delete_workstation(request) + + # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation in client._client._transport._wrapped_methods + + # 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_workstation] = mock_rpc + + request = {} + await client.delete_workstation(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.delete_workstation(request) + + # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationRequest() + 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_delete_workstation_async_from_dict(): + await test_delete_workstation_async(request_type=dict) + +def test_delete_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_workstation( + 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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_workstation( + 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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StartWorkstationRequest, + dict, +]) +def test_start_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.StartWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_start_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.StartWorkstationRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.start_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StartWorkstationRequest( + name='name_value', + etag='etag_value', + ) + +def test_start_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_workstation] = mock_rpc + request = {} + client.start_workstation(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.start_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.start_workstation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.start_workstation] = mock_rpc + + request = {} + await client.start_workstation(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.start_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StartWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.StartWorkstationRequest() + 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_start_workstation_async_from_dict(): + await test_start_workstation_async(request_type=dict) + +def test_start_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StartWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StartWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_workstation( + 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_start_workstation_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_start_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_workstation( + 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_start_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StopWorkstationRequest, + dict, +]) +def test_stop_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.StopWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_stop_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.StopWorkstationRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.stop_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StopWorkstationRequest( + name='name_value', + etag='etag_value', + ) + +def test_stop_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_workstation] = mock_rpc + request = {} + client.stop_workstation(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.stop_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.stop_workstation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.stop_workstation] = mock_rpc + + request = {} + await client.stop_workstation(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.stop_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StopWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.StopWorkstationRequest() + 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_stop_workstation_async_from_dict(): + await test_stop_workstation_async(request_type=dict) + +def test_stop_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StopWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StopWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_workstation( + 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_stop_workstation_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_stop_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_workstation( + 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_stop_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GenerateAccessTokenRequest, + dict, +]) +def test_generate_access_token(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + ) + response = client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.GenerateAccessTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +def test_generate_access_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.GenerateAccessTokenRequest( + workstation='workstation_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_access_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GenerateAccessTokenRequest( + workstation='workstation_value', + ) + +def test_generate_access_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_access_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc + request = {} + client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_access_token in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.generate_access_token] = mock_rpc + + request = {} + await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=workstations.GenerateAccessTokenRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + )) + response = await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.GenerateAccessTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.asyncio +async def test_generate_access_token_async_from_dict(): + await test_generate_access_token_async(request_type=dict) + +def test_generate_access_token_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GenerateAccessTokenRequest() + + request.workstation = 'workstation_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = workstations.GenerateAccessTokenResponse() + client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation=workstation_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_access_token_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GenerateAccessTokenRequest() + + request.workstation = 'workstation_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) + await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation=workstation_value', + ) in kw['metadata'] + + +def test_generate_access_token_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_access_token( + workstation='workstation_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].workstation + mock_val = 'workstation_value' + assert arg == mock_val + + +def test_generate_access_token_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + +@pytest.mark.asyncio +async def test_generate_access_token_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_access_token( + workstation='workstation_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].workstation + mock_val = 'workstation_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_generate_access_token_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + + +def test_get_workstation_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation_cluster] = mock_rpc + + request = {} + client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation_cluster(request) + + # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.GetWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation_cluster._get_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_workstation_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.WorkstationCluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.WorkstationCluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_workstation_cluster(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_get_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + + +def test_list_workstation_clusters_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_clusters] = mock_rpc + + request = {} + client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstation_clusters(request) + + # Establish 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_workstation_clusters_rest_required_fields(request_type=workstations.ListWorkstationClustersRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_clusters._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_workstation_clusters._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListWorkstationClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_workstation_clusters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstation_clusters_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstation_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workstation_clusters_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/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 = workstations.ListWorkstationClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_workstation_clusters(**mock_args) + + # Establish that the underlying call 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/*/locations/*}/workstationClusters" % client.transport._host, args[1]) + + +def test_list_workstation_clusters_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + + +def test_list_workstation_clusters_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationClustersResponse.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/locations/sample2'} + + pager = client.list_workstation_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationCluster) + for i in results) + + pages = list(client.list_workstation_clusters(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_workstation_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + + request = {} + client.create_workstation_cluster(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.create_workstation_cluster(request) + + # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.CreateWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_cluster_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 "workstationClusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationClusterId" in jsonified_request + assert jsonified_request["workstationClusterId"] == request_init["workstation_cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationClusterId"] = 'workstation_cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only", "workstation_cluster_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 "workstationClusterId" in jsonified_request + assert jsonified_request["workstationClusterId"] == 'workstation_cluster_id_value' + + client = WorkstationsClient( + 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 + + response = client.create_workstation_cluster(request) + + expected_params = [ + ( + "workstationClusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationClusterId", )) & set(("parent", "workstationClusterId", "workstationCluster", ))) + + +def test_create_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation_cluster(**mock_args) + + # Establish that the underlying call 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/*/locations/*}/workstationClusters" % client.transport._host, args[1]) + + +def test_create_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + +def test_update_workstation_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + + request = {} + client.update_workstation_cluster(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.update_workstation_cluster(request) + + # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.UpdateWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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': "patch", + '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 + + response = client.update_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationCluster", "updateMask", ))) + + +def test_update_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation_cluster=workstations.WorkstationCluster(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_workstation_cluster(**mock_args) + + # Establish that the underlying call 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/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_update_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_workstation_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + + request = {} + client.delete_workstation_cluster(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.delete_workstation_cluster(request) + + # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.DeleteWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation_cluster._get_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_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "validate_only", )) + jsonified_request.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 = WorkstationsClient( + 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': "delete", + '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 + + response = client.delete_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) + + +def test_delete_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation_cluster(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + + +def test_get_workstation_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation_config] = mock_rpc + + request = {} + client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation_config(request) + + # Establish 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_workstation_config_rest_required_fields(request_type=workstations.GetWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation_config._get_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_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.WorkstationConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # 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 = workstations.WorkstationConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_workstation_config(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + + +def test_list_workstation_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_configs] = mock_rpc + + request = {} + client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstation_configs(request) + + # Establish 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_workstation_configs_rest_required_fields(request_type=workstations.ListWorkstationConfigsRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_configs._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_workstation_configs._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_workstation_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstation_configs_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstation_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workstation_configs_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # 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 = workstations.ListWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_workstation_configs(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) + + +def test_list_workstation_configs_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_workstation_configs_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationConfigsResponse.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/locations/sample2/workstationClusters/sample3'} + + pager = client.list_workstation_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) + + pages = list(client.list_workstation_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_usable_workstation_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_usable_workstation_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_usable_workstation_configs] = mock_rpc + + request = {} + client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_usable_workstation_configs(request) + + # Establish 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_usable_workstation_configs_rest_required_fields(request_type=workstations.ListUsableWorkstationConfigsRequest): + transport_class = transports.WorkstationsRestTransport + + 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_usable_workstation_configs._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_usable_workstation_configs._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_usable_workstation_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_usable_workstation_configs_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_usable_workstation_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_usable_workstation_configs_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # 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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_usable_workstation_configs(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable" % client.transport._host, args[1]) + + +def test_list_usable_workstation_configs_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstation_configs_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListUsableWorkstationConfigsResponse.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/locations/sample2/workstationClusters/sample3'} + + pager = client.list_usable_workstation_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) + + pages = list(client.list_usable_workstation_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_workstation_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + + request = {} + client.create_workstation_config(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.create_workstation_config(request) + + # Establish 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_workstation_config_rest_required_fields(request_type=workstations.CreateWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_config_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 "workstationConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationConfigId" in jsonified_request + assert jsonified_request["workstationConfigId"] == request_init["workstation_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationConfigId"] = 'workstation_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only", "workstation_config_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 "workstationConfigId" in jsonified_request + assert jsonified_request["workstationConfigId"] == 'workstation_config_id_value' + + client = WorkstationsClient( + 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 + + response = client.create_workstation_config(request) + + expected_params = [ + ( + "workstationConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationConfigId", )) & set(("parent", "workstationConfigId", "workstationConfig", ))) + + +def test_create_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation_config(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) + + +def test_create_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + +def test_update_workstation_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + + request = {} + client.update_workstation_config(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.update_workstation_config(request) + + # Establish 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_workstation_config_rest_required_fields(request_type=workstations.UpdateWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_config._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_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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': "patch", + '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 + + response = client.update_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationConfig", "updateMask", ))) + + +def test_update_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation_config=workstations.WorkstationConfig(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_workstation_config(**mock_args) + + # Establish that the underlying call 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/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_workstation_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + + request = {} + client.delete_workstation_config(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.delete_workstation_config(request) + + # Establish 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_workstation_config_rest_required_fields(request_type=workstations.DeleteWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation_config._get_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_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "validate_only", )) + jsonified_request.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 = WorkstationsClient( + 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': "delete", + '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 + + response = client.delete_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) + + +def test_delete_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # 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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation_config(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + + +def test_get_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation] = mock_rpc + + request = {} + client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation(request) + + # Establish 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_workstation_rest_required_fields(request_type=workstations.GetWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation._get_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_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.Workstation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # 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 = workstations.Workstation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_workstation(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_get_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + + +def test_list_workstations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstations] = mock_rpc + + request = {} + client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstations(request) + + # Establish 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_workstations_rest_required_fields(request_type=workstations.ListWorkstationsRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstations._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_workstations._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_workstations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstations_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workstations_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # 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 = workstations.ListWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_workstations(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) + + +def test_list_workstations_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_workstations_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationsResponse.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/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + pager = client.list_workstations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) + + pages = list(client.list_workstations(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_usable_workstations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_usable_workstations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_usable_workstations] = mock_rpc + + request = {} + client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_usable_workstations(request) + + # Establish 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_usable_workstations_rest_required_fields(request_type=workstations.ListUsableWorkstationsRequest): + transport_class = transports.WorkstationsRestTransport + + 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_usable_workstations._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_usable_workstations._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListUsableWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_usable_workstations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_usable_workstations_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_usable_workstations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_usable_workstations_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # 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 = workstations.ListUsableWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_usable_workstations(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable" % client.transport._host, args[1]) + + +def test_list_usable_workstations_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstations_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListUsableWorkstationsResponse.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/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + pager = client.list_usable_workstations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) + + pages = list(client.list_usable_workstations(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + + request = {} + client.create_workstation(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.create_workstation(request) + + # Establish 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_workstation_rest_required_fields(request_type=workstations.CreateWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_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 "workstationId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationId" in jsonified_request + assert jsonified_request["workstationId"] == request_init["workstation_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationId"] = 'workstation_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only", "workstation_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 "workstationId" in jsonified_request + assert jsonified_request["workstationId"] == 'workstation_id_value' + + client = WorkstationsClient( + 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 + + response = client.create_workstation(request) + + expected_params = [ + ( + "workstationId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationId", )) & set(("parent", "workstationId", "workstation", ))) + + +def test_create_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) + + +def test_create_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + +def test_update_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + + request = {} + client.update_workstation(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.update_workstation(request) + + # Establish 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_workstation_rest_required_fields(request_type=workstations.UpdateWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation._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_workstation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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': "patch", + '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 + + response = client.update_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstation", "updateMask", ))) + + +def test_update_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation=workstations.Workstation(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_workstation(**mock_args) + + # Establish that the underlying call 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/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_update_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + + request = {} + client.delete_workstation(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.delete_workstation(request) + + # Establish 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_workstation_rest_required_fields(request_type=workstations.DeleteWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation._get_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_workstation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "validate_only", )) + jsonified_request.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 = WorkstationsClient( + 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': "delete", + '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 + + response = client.delete_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) + + +def test_delete_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # 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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + + +def test_start_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_workstation] = mock_rpc + + request = {} + client.start_workstation(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.start_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_start_workstation_rest_required_fields(request_type=workstations.StartWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).start_workstation._get_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()).start_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + 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 + + response = client.start_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_start_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.start_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_start_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # 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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.start_workstation(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start" % client.transport._host, args[1]) + + +def test_start_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + + +def test_stop_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_workstation] = mock_rpc + + request = {} + client.stop_workstation(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.stop_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_stop_workstation_rest_required_fields(request_type=workstations.StopWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).stop_workstation._get_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()).stop_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + 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 + + response = client.stop_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_stop_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.stop_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_stop_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # 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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.stop_workstation(**mock_args) + + # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop" % client.transport._host, args[1]) + + +def test_stop_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + + +def test_generate_access_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_access_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc + + request = {} + client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_access_token_rest_required_fields(request_type=workstations.GenerateAccessTokenRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["workstation"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["workstation"] = 'workstation_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "workstation" in jsonified_request + assert jsonified_request["workstation"] == 'workstation_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = workstations.GenerateAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.generate_access_token(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_access_token_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_access_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("workstation", ))) + + +def test_generate_access_token_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + workstation='workstation_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = workstations.GenerateAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.generate_access_token(**mock_args) + + # Establish that the underlying call 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/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken" % client.transport._host, args[1]) + + +def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WorkstationsClient( + 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 = WorkstationsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WorkstationsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WorkstationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + transports.WorkstationsRestTransport, +]) +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 = WorkstationsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = WorkstationsClient( + 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_workstation_cluster_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = workstations.WorkstationCluster() + client.get_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_clusters_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = workstations.ListWorkstationClustersResponse() + client.list_workstation_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationClustersRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = workstations.WorkstationConfig() + client.get_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_configs_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListWorkstationConfigsResponse() + client.list_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This 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_usable_workstation_configs_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + client.list_usable_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = workstations.Workstation() + client.get_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstations_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = workstations.ListWorkstationsResponse() + client.list_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationsRequest() + + assert args[0] == request_msg + + +# This 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_usable_workstations_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationsResponse() + client.list_usable_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationsRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.start_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StartWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.stop_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StopWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_access_token_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = workstations.GenerateAccessTokenResponse() + client.generate_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GenerateAccessTokenRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = WorkstationsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = WorkstationsAsyncClient( + 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_workstation_cluster_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + )) + await client.get_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_clusters_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_workstation_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__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.create_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__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.update_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__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.delete_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + replica_zones=['replica_zones_value'], + degraded=True, + )) + await client.get_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_configs_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_usable_workstation_configs_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_usable_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__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.create_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__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.update_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__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.delete_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + )) + await client.get_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstations_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_usable_workstations_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_usable_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__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.create_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__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.update_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__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.delete_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_start_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StartWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_stop_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StopWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_access_token_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + )) + await client.generate_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GenerateAccessTokenRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = WorkstationsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_workstation_cluster_rest_bad_request(request_type=workstations.GetWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 + client.get_workstation_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationClusterRequest, + dict, +]) +def test_get_workstation_cluster_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=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 = workstations.WorkstationCluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationClusterRequest.pb(workstations.GetWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.WorkstationCluster.to_json(workstations.WorkstationCluster()) + req.return_value.content = return_value + + request = workstations.GetWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.WorkstationCluster() + + client.get_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstation_clusters_rest_bad_request(request_type=workstations.ListWorkstationClustersRequest): + client = WorkstationsClient( + 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 + client.list_workstation_clusters(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationClustersRequest, + dict, +]) +def test_list_workstation_clusters_rest_call_success(request_type): + client = WorkstationsClient( + 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 = workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListWorkstationClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_workstation_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstation_clusters_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_clusters") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationClustersRequest.pb(workstations.ListWorkstationClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListWorkstationClustersResponse.to_json(workstations.ListWorkstationClustersResponse()) + req.return_value.content = return_value + + request = workstations.ListWorkstationClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationClustersResponse() + + client.list_workstation_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_cluster_rest_bad_request(request_type=workstations.CreateWorkstationClusterRequest): + client = WorkstationsClient( + 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 + client.create_workstation_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationClusterRequest, + dict, +]) +def test_create_workstation_cluster_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = workstations.CreateWorkstationClusterRequest.meta.fields["workstation_cluster"] + + 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["workstation_cluster"].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["workstation_cluster"][field])): + del request_init["workstation_cluster"][field][i][subfield] + else: + del request_init["workstation_cluster"][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 = 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 + response = client.create_workstation_cluster(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_create_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationClusterRequest.pb(workstations.CreateWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.CreateWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_cluster_rest_bad_request(request_type=workstations.UpdateWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/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 + client.update_workstation_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationClusterRequest, + dict, +]) +def test_update_workstation_cluster_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = workstations.UpdateWorkstationClusterRequest.meta.fields["workstation_cluster"] + + 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["workstation_cluster"].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["workstation_cluster"][field])): + del request_init["workstation_cluster"][field][i][subfield] + else: + del request_init["workstation_cluster"][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 = 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 + response = client.update_workstation_cluster(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_update_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationClusterRequest.pb(workstations.UpdateWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.UpdateWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_cluster_rest_bad_request(request_type=workstations.DeleteWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 + client.delete_workstation_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationClusterRequest, + dict, +]) +def test_delete_workstation_cluster_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = 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 + response = client.delete_workstation_cluster(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_delete_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationClusterRequest.pb(workstations.DeleteWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.DeleteWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_config_rest_bad_request(request_type=workstations.GetWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_workstation_config(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationConfigRequest, + dict, +]) +def test_get_workstation_config_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + replica_zones=['replica_zones_value'], + degraded=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 = workstations.WorkstationConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_workstation_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.replica_zones == ['replica_zones_value'] + assert response.degraded is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationConfigRequest.pb(workstations.GetWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.WorkstationConfig.to_json(workstations.WorkstationConfig()) + req.return_value.content = return_value + + request = workstations.GetWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.WorkstationConfig() + + client.get_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstation_configs_rest_bad_request(request_type=workstations.ListWorkstationConfigsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 + client.list_workstation_configs(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationConfigsRequest, + dict, +]) +def test_list_workstation_configs_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_workstation_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstation_configs_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_configs") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationConfigsRequest.pb(workstations.ListWorkstationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListWorkstationConfigsResponse.to_json(workstations.ListWorkstationConfigsResponse()) + req.return_value.content = return_value + + request = workstations.ListWorkstationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationConfigsResponse() + + client.list_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_usable_workstation_configs_rest_bad_request(request_type=workstations.ListUsableWorkstationConfigsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 + client.list_usable_workstation_configs(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListUsableWorkstationConfigsRequest, + dict, +]) +def test_list_usable_workstation_configs_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_usable_workstation_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_usable_workstation_configs_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstation_configs") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstation_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListUsableWorkstationConfigsRequest.pb(workstations.ListUsableWorkstationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListUsableWorkstationConfigsResponse.to_json(workstations.ListUsableWorkstationConfigsResponse()) + req.return_value.content = return_value + + request = workstations.ListUsableWorkstationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListUsableWorkstationConfigsResponse() + + client.list_usable_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_config_rest_bad_request(request_type=workstations.CreateWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 + client.create_workstation_config(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationConfigRequest, + dict, +]) +def test_create_workstation_config_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'service_account_scopes': ['service_account_scopes_value1', 'service_account_scopes_value2'], 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'replica_zones': ['replica_zones_value1', 'replica_zones_value2'], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = workstations.CreateWorkstationConfigRequest.meta.fields["workstation_config"] + + 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["workstation_config"].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["workstation_config"][field])): + del request_init["workstation_config"][field][i][subfield] + else: + del request_init["workstation_config"][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 = 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 + response = client.create_workstation_config(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_create_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationConfigRequest.pb(workstations.CreateWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.CreateWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_config_rest_bad_request(request_type=workstations.UpdateWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_workstation_config(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationConfigRequest, + dict, +]) +def test_update_workstation_config_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'service_account_scopes': ['service_account_scopes_value1', 'service_account_scopes_value2'], 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'replica_zones': ['replica_zones_value1', 'replica_zones_value2'], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = workstations.UpdateWorkstationConfigRequest.meta.fields["workstation_config"] + + 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["workstation_config"].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["workstation_config"][field])): + del request_init["workstation_config"][field][i][subfield] + else: + del request_init["workstation_config"][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 = 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 + response = client.update_workstation_config(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_update_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationConfigRequest.pb(workstations.UpdateWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.UpdateWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_config_rest_bad_request(request_type=workstations.DeleteWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_workstation_config(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationConfigRequest, + dict, +]) +def test_delete_workstation_config_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # 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 + response = client.delete_workstation_config(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_delete_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationConfigRequest.pb(workstations.DeleteWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.DeleteWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_rest_bad_request(request_type=workstations.GetWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationRequest, + dict, +]) +def test_get_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_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 = workstations.Workstation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_workstation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationRequest.pb(workstations.GetWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.Workstation.to_json(workstations.Workstation()) + req.return_value.content = return_value + + request = workstations.GetWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.Workstation() + + client.get_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstations_rest_bad_request(request_type=workstations.ListWorkstationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_workstations(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationsRequest, + dict, +]) +def test_list_workstations_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_workstations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstations_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstations") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationsRequest.pb(workstations.ListWorkstationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListWorkstationsResponse.to_json(workstations.ListWorkstationsResponse()) + req.return_value.content = return_value + + request = workstations.ListWorkstationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationsResponse() + + client.list_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_usable_workstations_rest_bad_request(request_type=workstations.ListUsableWorkstationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_usable_workstations(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListUsableWorkstationsRequest, + dict, +]) +def test_list_usable_workstations_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListUsableWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_usable_workstations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_usable_workstations_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstations") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListUsableWorkstationsRequest.pb(workstations.ListUsableWorkstationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListUsableWorkstationsResponse.to_json(workstations.ListUsableWorkstationsResponse()) + req.return_value.content = return_value + + request = workstations.ListUsableWorkstationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListUsableWorkstationsResponse() + + client.list_usable_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_rest_bad_request(request_type=workstations.CreateWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationRequest, + dict, +]) +def test_create_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'start_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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 = workstations.CreateWorkstationRequest.meta.fields["workstation"] + + 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["workstation"].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["workstation"][field])): + del request_init["workstation"][field][i][subfield] + else: + del request_init["workstation"][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 = 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 + response = client.create_workstation(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_create_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationRequest.pb(workstations.CreateWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.CreateWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_rest_bad_request(request_type=workstations.UpdateWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationRequest, + dict, +]) +def test_update_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'start_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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 = workstations.UpdateWorkstationRequest.meta.fields["workstation"] + + 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["workstation"].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["workstation"][field])): + del request_init["workstation"][field][i][subfield] + else: + del request_init["workstation"][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 = 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 + response = client.update_workstation(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_update_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationRequest.pb(workstations.UpdateWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.UpdateWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_rest_bad_request(request_type=workstations.DeleteWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationRequest, + dict, +]) +def test_delete_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and 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 + response = client.delete_workstation(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_delete_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationRequest.pb(workstations.DeleteWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.DeleteWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_workstation_rest_bad_request(request_type=workstations.StartWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.start_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.StartWorkstationRequest, + dict, +]) +def test_start_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and 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 + response = client.start_workstation(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_start_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_start_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_start_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.StartWorkstationRequest.pb(workstations.StartWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.StartWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.start_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_workstation_rest_bad_request(request_type=workstations.StopWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.stop_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.StopWorkstationRequest, + dict, +]) +def test_stop_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and 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 + response = client.stop_workstation(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_stop_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_stop_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_stop_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.StopWorkstationRequest.pb(workstations.StopWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.StopWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.stop_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_access_token_rest_bad_request(request_type=workstations.GenerateAccessTokenRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.generate_access_token(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.GenerateAccessTokenRequest, + dict, +]) +def test_generate_access_token_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse( + access_token='access_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 = workstations.GenerateAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.generate_access_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_access_token_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_generate_access_token") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_generate_access_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GenerateAccessTokenRequest.pb(workstations.GenerateAccessTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.GenerateAccessTokenResponse.to_json(workstations.GenerateAccessTokenResponse()) + req.return_value.content = return_value + + request = workstations.GenerateAccessTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.GenerateAccessTokenResponse() + + client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + 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 = policy_pb2.Policy() + + # 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 + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + 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 = policy_pb2.Policy() + + # 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 + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + 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 = iam_policy_pb2.TestIamPermissionsResponse() + + # 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 + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = WorkstationsClient( + 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 + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = WorkstationsClient( + 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 = 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 + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = WorkstationsClient( + 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 + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = WorkstationsClient( + 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 = 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 + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = WorkstationsClient( + 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 + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = WorkstationsClient( + 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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 + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': '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(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = WorkstationsClient( + 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_workstation_cluster_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + client.get_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_clusters_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + client.list_workstation_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationClustersRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + client.create_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + client.update_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + client.delete_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + client.get_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_configs_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + client.list_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This 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_usable_workstation_configs_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + client.list_usable_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + client.create_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + client.update_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + client.delete_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + client.get_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstations_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + client.list_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationsRequest() + + assert args[0] == request_msg + + +# This 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_usable_workstations_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + client.list_usable_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationsRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + client.create_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + client.update_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + client.delete_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + client.start_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StartWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + client.stop_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StopWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_access_token_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + client.generate_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GenerateAccessTokenRequest() + + assert args[0] == request_msg + + +def test_workstations_rest_lro_client(): + client = WorkstationsClient( + 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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WorkstationsGrpcTransport, + ) + +def test_workstations_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WorkstationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_workstations_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WorkstationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_workstation_cluster', + 'list_workstation_clusters', + 'create_workstation_cluster', + 'update_workstation_cluster', + 'delete_workstation_cluster', + 'get_workstation_config', + 'list_workstation_configs', + 'list_usable_workstation_configs', + 'create_workstation_config', + 'update_workstation_config', + 'delete_workstation_config', + 'get_workstation', + 'list_workstations', + 'list_usable_workstations', + 'create_workstation', + 'update_workstation', + 'delete_workstation', + 'start_workstation', + 'stop_workstation', + 'generate_access_token', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + 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_workstations_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkstationsTransport( + 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_workstations_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkstationsTransport() + adc.assert_called_once() + + +def test_workstations_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) + WorkstationsClient() + 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.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + ], +) +def test_workstations_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.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + transports.WorkstationsRestTransport, + ], +) +def test_workstations_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.WorkstationsGrpcTransport, grpc_helpers), + (transports.WorkstationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_workstations_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( + "workstations.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="workstations.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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_workstations_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.WorkstationsRestTransport ( + 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_workstations_host_no_port(transport_name): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workstations.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_workstations_host_with_port(transport_name): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workstations.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workstations.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_workstations_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WorkstationsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WorkstationsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_workstation_cluster._session + session2 = client2.transport.get_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.list_workstation_clusters._session + session2 = client2.transport.list_workstation_clusters._session + assert session1 != session2 + session1 = client1.transport.create_workstation_cluster._session + session2 = client2.transport.create_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.update_workstation_cluster._session + session2 = client2.transport.update_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_workstation_cluster._session + session2 = client2.transport.delete_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.get_workstation_config._session + session2 = client2.transport.get_workstation_config._session + assert session1 != session2 + session1 = client1.transport.list_workstation_configs._session + session2 = client2.transport.list_workstation_configs._session + assert session1 != session2 + session1 = client1.transport.list_usable_workstation_configs._session + session2 = client2.transport.list_usable_workstation_configs._session + assert session1 != session2 + session1 = client1.transport.create_workstation_config._session + session2 = client2.transport.create_workstation_config._session + assert session1 != session2 + session1 = client1.transport.update_workstation_config._session + session2 = client2.transport.update_workstation_config._session + assert session1 != session2 + session1 = client1.transport.delete_workstation_config._session + session2 = client2.transport.delete_workstation_config._session + assert session1 != session2 + session1 = client1.transport.get_workstation._session + session2 = client2.transport.get_workstation._session + assert session1 != session2 + session1 = client1.transport.list_workstations._session + session2 = client2.transport.list_workstations._session + assert session1 != session2 + session1 = client1.transport.list_usable_workstations._session + session2 = client2.transport.list_usable_workstations._session + assert session1 != session2 + session1 = client1.transport.create_workstation._session + session2 = client2.transport.create_workstation._session + assert session1 != session2 + session1 = client1.transport.update_workstation._session + session2 = client2.transport.update_workstation._session + assert session1 != session2 + session1 = client1.transport.delete_workstation._session + session2 = client2.transport.delete_workstation._session + assert session1 != session2 + session1 = client1.transport.start_workstation._session + session2 = client2.transport.start_workstation._session + assert session1 != session2 + session1 = client1.transport.stop_workstation._session + session2 = client2.transport.stop_workstation._session + assert session1 != session2 + session1 = client1.transport.generate_access_token._session + session2 = client2.transport.generate_access_token._session + assert session1 != session2 +def test_workstations_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkstationsGrpcTransport( + 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_workstations_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkstationsGrpcAsyncIOTransport( + 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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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_workstations_grpc_lro_client(): + client = WorkstationsClient( + 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_workstations_grpc_lro_async_client(): + client = WorkstationsAsyncClient( + 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_workstation_path(): + project = "squid" + location = "clam" + workstation_cluster = "whelk" + workstation_config = "octopus" + workstation = "oyster" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) + actual = WorkstationsClient.workstation_path(project, location, workstation_cluster, workstation_config, workstation) + assert expected == actual + + +def test_parse_workstation_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "workstation_cluster": "mussel", + "workstation_config": "winkle", + "workstation": "nautilus", + } + path = WorkstationsClient.workstation_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_path(path) + assert expected == actual + +def test_workstation_cluster_path(): + project = "scallop" + location = "abalone" + workstation_cluster = "squid" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) + actual = WorkstationsClient.workstation_cluster_path(project, location, workstation_cluster) + assert expected == actual + + +def test_parse_workstation_cluster_path(): + expected = { + "project": "clam", + "location": "whelk", + "workstation_cluster": "octopus", + } + path = WorkstationsClient.workstation_cluster_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_cluster_path(path) + assert expected == actual + +def test_workstation_config_path(): + project = "oyster" + location = "nudibranch" + workstation_cluster = "cuttlefish" + workstation_config = "mussel" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) + actual = WorkstationsClient.workstation_config_path(project, location, workstation_cluster, workstation_config) + assert expected == actual + + +def test_parse_workstation_config_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "workstation_cluster": "scallop", + "workstation_config": "abalone", + } + path = WorkstationsClient.workstation_config_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WorkstationsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = WorkstationsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = WorkstationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = WorkstationsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WorkstationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = WorkstationsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = WorkstationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = WorkstationsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.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 = WorkstationsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = WorkstationsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.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.WorkstationsTransport, '_prep_wrapped_messages') as prep: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WorkstationsTransport, '_prep_wrapped_messages') as prep: + transport_class = WorkstationsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_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 response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_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 response is None + +def test_delete_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_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_delete_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_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_delete_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_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 response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_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 response is None + +def test_cancel_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_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_cancel_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_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_cancel_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = WorkstationsClient( + 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 = WorkstationsAsyncClient( + 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_list_operations(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the 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.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the 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.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_list_operations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_list_operations_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_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", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_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", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_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", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_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", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = WorkstationsClient( + 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 = WorkstationsAsyncClient( + 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 = WorkstationsClient( + 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 = WorkstationsClient( + 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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport), +]) +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-cloud-workstations/v1beta/.coveragerc b/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc new file mode 100644 index 000000000000..ee1a17c3e2ca --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/workstations/__init__.py + google/cloud/workstations/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-cloud-workstations/v1beta/.flake8 b/owl-bot-staging/google-cloud-workstations/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in new file mode 100644 index 000000000000..ebef07fddb1d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/workstations *.py +recursive-include google/cloud/workstations_v1beta *.py diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/README.rst b/owl-bot-staging/google-cloud-workstations/v1beta/README.rst new file mode 100644 index 000000000000..48a711be018f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Workstations 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 Cloud Workstations 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-cloud-workstations/v1beta/docs/_static/custom.css b/owl-bot-staging/google-cloud-workstations/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py new file mode 100644 index 000000000000..65ff2ad5ae85 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations 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-cloud-workstations" +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 Cloud 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-cloud-workstations-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-cloud-workstations.tex", + u"google-cloud-workstations 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-cloud-workstations", + u"Google Cloud Workstations 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-cloud-workstations", + u"google-cloud-workstations Documentation", + author, + "google-cloud-workstations", + "GAPIC library for Google Cloud Workstations 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-cloud-workstations/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst new file mode 100644 index 000000000000..4550acabdaad --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + workstations_v1beta/services_ + workstations_v1beta/types_ diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services_.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services_.rst new file mode 100644 index 000000000000..77aed9f52d7a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Workstations v1beta API +================================================= +.. toctree:: + :maxdepth: 2 + + workstations diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types_.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types_.rst new file mode 100644 index 000000000000..af7f36fbcb60 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Workstations v1beta API +============================================== + +.. automodule:: google.cloud.workstations_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst new file mode 100644 index 000000000000..5839880c918a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst @@ -0,0 +1,10 @@ +Workstations +------------------------------ + +.. automodule:: google.cloud.workstations_v1beta.services.workstations + :members: + :inherited-members: + +.. automodule:: google.cloud.workstations_v1beta.services.workstations.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py new file mode 100644 index 000000000000..39b1cbb59f51 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workstations import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.workstations_v1beta.services.workstations.client import WorkstationsClient +from google.cloud.workstations_v1beta.services.workstations.async_client import WorkstationsAsyncClient + +from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationClusterRequest +from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationConfigRequest +from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationClusterRequest +from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationConfigRequest +from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import GenerateAccessTokenRequest +from google.cloud.workstations_v1beta.types.workstations import GenerateAccessTokenResponse +from google.cloud.workstations_v1beta.types.workstations import GetWorkstationClusterRequest +from google.cloud.workstations_v1beta.types.workstations import GetWorkstationConfigRequest +from google.cloud.workstations_v1beta.types.workstations import GetWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationConfigsRequest +from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationConfigsResponse +from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationsRequest +from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationsResponse +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationClustersRequest +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationClustersResponse +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationConfigsRequest +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationConfigsResponse +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationsRequest +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationsResponse +from google.cloud.workstations_v1beta.types.workstations import OperationMetadata +from google.cloud.workstations_v1beta.types.workstations import StartWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import StopWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationClusterRequest +from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationConfigRequest +from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import Workstation +from google.cloud.workstations_v1beta.types.workstations import WorkstationCluster +from google.cloud.workstations_v1beta.types.workstations import WorkstationConfig + +__all__ = ('WorkstationsClient', + 'WorkstationsAsyncClient', + 'CreateWorkstationClusterRequest', + 'CreateWorkstationConfigRequest', + 'CreateWorkstationRequest', + 'DeleteWorkstationClusterRequest', + 'DeleteWorkstationConfigRequest', + 'DeleteWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GetWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'OperationMetadata', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'UpdateWorkstationClusterRequest', + 'UpdateWorkstationConfigRequest', + 'UpdateWorkstationRequest', + 'Workstation', + 'WorkstationCluster', + 'WorkstationConfig', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/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-cloud-workstations/v1beta/google/cloud/workstations/py.typed b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed new file mode 100644 index 000000000000..04170223dff9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py new file mode 100644 index 000000000000..6a7789157329 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workstations_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.workstations import WorkstationsClient +from .services.workstations import WorkstationsAsyncClient + +from .types.workstations import CreateWorkstationClusterRequest +from .types.workstations import CreateWorkstationConfigRequest +from .types.workstations import CreateWorkstationRequest +from .types.workstations import DeleteWorkstationClusterRequest +from .types.workstations import DeleteWorkstationConfigRequest +from .types.workstations import DeleteWorkstationRequest +from .types.workstations import GenerateAccessTokenRequest +from .types.workstations import GenerateAccessTokenResponse +from .types.workstations import GetWorkstationClusterRequest +from .types.workstations import GetWorkstationConfigRequest +from .types.workstations import GetWorkstationRequest +from .types.workstations import ListUsableWorkstationConfigsRequest +from .types.workstations import ListUsableWorkstationConfigsResponse +from .types.workstations import ListUsableWorkstationsRequest +from .types.workstations import ListUsableWorkstationsResponse +from .types.workstations import ListWorkstationClustersRequest +from .types.workstations import ListWorkstationClustersResponse +from .types.workstations import ListWorkstationConfigsRequest +from .types.workstations import ListWorkstationConfigsResponse +from .types.workstations import ListWorkstationsRequest +from .types.workstations import ListWorkstationsResponse +from .types.workstations import OperationMetadata +from .types.workstations import StartWorkstationRequest +from .types.workstations import StopWorkstationRequest +from .types.workstations import UpdateWorkstationClusterRequest +from .types.workstations import UpdateWorkstationConfigRequest +from .types.workstations import UpdateWorkstationRequest +from .types.workstations import Workstation +from .types.workstations import WorkstationCluster +from .types.workstations import WorkstationConfig + +__all__ = ( + 'WorkstationsAsyncClient', +'CreateWorkstationClusterRequest', +'CreateWorkstationConfigRequest', +'CreateWorkstationRequest', +'DeleteWorkstationClusterRequest', +'DeleteWorkstationConfigRequest', +'DeleteWorkstationRequest', +'GenerateAccessTokenRequest', +'GenerateAccessTokenResponse', +'GetWorkstationClusterRequest', +'GetWorkstationConfigRequest', +'GetWorkstationRequest', +'ListUsableWorkstationConfigsRequest', +'ListUsableWorkstationConfigsResponse', +'ListUsableWorkstationsRequest', +'ListUsableWorkstationsResponse', +'ListWorkstationClustersRequest', +'ListWorkstationClustersResponse', +'ListWorkstationConfigsRequest', +'ListWorkstationConfigsResponse', +'ListWorkstationsRequest', +'ListWorkstationsResponse', +'OperationMetadata', +'StartWorkstationRequest', +'StopWorkstationRequest', +'UpdateWorkstationClusterRequest', +'UpdateWorkstationConfigRequest', +'UpdateWorkstationRequest', +'Workstation', +'WorkstationCluster', +'WorkstationConfig', +'WorkstationsClient', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..cf8a80968ec1 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json @@ -0,0 +1,328 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.workstations_v1beta", + "protoPackage": "google.cloud.workstations.v1beta", + "schema": "1.0", + "services": { + "Workstations": { + "clients": { + "grpc": { + "libraryClient": "WorkstationsClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WorkstationsAsyncClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + }, + "rest": { + "libraryClient": "WorkstationsClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_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-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed new file mode 100644 index 000000000000..04170223dff9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_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-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py new file mode 100644 index 000000000000..e8958d8c0d6d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__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 WorkstationsClient +from .async_client import WorkstationsAsyncClient + +__all__ = ( + 'WorkstationsClient', + 'WorkstationsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py new file mode 100644 index 000000000000..d71d80c082ca --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py @@ -0,0 +1,3183 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.workstations_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.services.workstations import pagers +from google.cloud.workstations_v1beta.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .client import WorkstationsClient + + +class WorkstationsAsyncClient: + """Service for interacting with Cloud Workstations.""" + + _client: WorkstationsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WorkstationsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WorkstationsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WorkstationsClient._DEFAULT_UNIVERSE + + workstation_path = staticmethod(WorkstationsClient.workstation_path) + parse_workstation_path = staticmethod(WorkstationsClient.parse_workstation_path) + workstation_cluster_path = staticmethod(WorkstationsClient.workstation_cluster_path) + parse_workstation_cluster_path = staticmethod(WorkstationsClient.parse_workstation_cluster_path) + workstation_config_path = staticmethod(WorkstationsClient.workstation_config_path) + parse_workstation_config_path = staticmethod(WorkstationsClient.parse_workstation_config_path) + common_billing_account_path = staticmethod(WorkstationsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WorkstationsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WorkstationsClient.common_folder_path) + parse_common_folder_path = staticmethod(WorkstationsClient.parse_common_folder_path) + common_organization_path = staticmethod(WorkstationsClient.common_organization_path) + parse_common_organization_path = staticmethod(WorkstationsClient.parse_common_organization_path) + common_project_path = staticmethod(WorkstationsClient.common_project_path) + parse_common_project_path = staticmethod(WorkstationsClient.parse_common_project_path) + common_location_path = staticmethod(WorkstationsClient.common_location_path) + parse_common_location_path = staticmethod(WorkstationsClient.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: + WorkstationsAsyncClient: The constructed client. + """ + return WorkstationsClient.from_service_account_info.__func__(WorkstationsAsyncClient, 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: + WorkstationsAsyncClient: The constructed client. + """ + return WorkstationsClient.from_service_account_file.__func__(WorkstationsAsyncClient, 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 WorkstationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WorkstationsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkstationsTransport: 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 = WorkstationsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WorkstationsTransport, Callable[..., WorkstationsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workstations 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,WorkstationsTransport,Callable[..., WorkstationsTransport]]]): + 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 WorkstationsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WorkstationsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_workstation_cluster(self, + request: Optional[Union[workstations.GetWorkstationClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.WorkstationCluster: + r"""Returns the requested workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest, dict]]): + The request object. Request message for + GetWorkstationCluster. + name (:class:`str`): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.types.WorkstationCluster: + A workstation cluster resource in the + Cloud Workstations API. + Defines a group of workstations in a + particular region and the VPC network + they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationClusterRequest): + request = workstations.GetWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_cluster] + + # Certain fields should be provided within 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_workstation_clusters(self, + request: Optional[Union[workstations.ListWorkstationClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationClustersAsyncPager: + r"""Returns all workstation clusters in the specified + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest, dict]]): + The request object. Request message for + ListWorkstationClusters. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersAsyncPager: + Response message for + ListWorkstationClusters. + 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, workstations.ListWorkstationClustersRequest): + request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] + + # Certain fields should be provided within 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.ListWorkstationClustersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation_cluster(self, + request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_cluster: Optional[workstations.WorkstationCluster] = None, + workstation_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest, dict]]): + The request object. Message for creating a + CreateWorkstationCluster. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster (:class:`google.cloud.workstations_v1beta.types.WorkstationCluster`): + Required. Workstation cluster to + create. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster_id (:class:`str`): + Required. ID to use for the + workstation cluster. + + This corresponds to the ``workstation_cluster_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation_cluster, workstation_cluster_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, workstations.CreateWorkstationClusterRequest): + request = workstations.CreateWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + if workstation_cluster_id is not None: + request.workstation_cluster_id = workstation_cluster_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_workstation_cluster] + + # Certain fields should be provided within 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation_cluster(self, + request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, + *, + workstation_cluster: Optional[workstations.WorkstationCluster] = 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, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an existing workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest, dict]]): + The request object. Request message for + UpdateWorkstationCluster. + workstation_cluster (:class:`google.cloud.workstations_v1beta.types.WorkstationCluster`): + Required. Workstation cluster to + update. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask that specifies which + fields in the workstation cluster should + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_cluster, 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, workstations.UpdateWorkstationClusterRequest): + request = workstations.UpdateWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + 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_workstation_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_cluster.name", request.workstation_cluster.name), + )), + ) + + # 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation_cluster(self, + request: Optional[Union[workstations.DeleteWorkstationClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest, dict]]): + The request object. Message for deleting a workstation + cluster. + name (:class:`str`): + Required. Name of the workstation + cluster to delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationClusterRequest): + request = workstations.DeleteWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_cluster] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_workstation_config(self, + request: Optional[Union[workstations.GetWorkstationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.WorkstationConfig: + r"""Returns the requested workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_get_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest, dict]]): + The request object. Request message for + GetWorkstationConfig. + name (:class:`str`): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.types.WorkstationConfig: + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationConfigRequest): + request = workstations.GetWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_config] + + # Certain fields should be provided within 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_workstation_configs(self, + request: Optional[Union[workstations.ListWorkstationConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationConfigsAsyncPager: + r"""Returns all workstation configurations in the + specified cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest, dict]]): + The request object. Request message for + ListWorkstationConfigs. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsAsyncPager: + Response message for + ListWorkstationConfigs. + 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, workstations.ListWorkstationConfigsRequest): + request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] + + # Certain fields should be provided within 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.ListWorkstationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_usable_workstation_configs(self, + request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUsableWorkstationConfigsAsyncPager: + r"""Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest, dict]]): + The request object. Request message for + ListUsableWorkstationConfigs. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager: + Response message for + ListUsableWorkstationConfigs. + 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, workstations.ListUsableWorkstationConfigsRequest): + request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] + + # Certain fields should be provided within 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.ListUsableWorkstationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation_config(self, + request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_config: Optional[workstations.WorkstationConfig] = None, + workstation_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_create_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest, dict]]): + The request object. Message for creating a + CreateWorkstationConfig. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config (:class:`google.cloud.workstations_v1beta.types.WorkstationConfig`): + Required. Config to create. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config_id (:class:`str`): + Required. ID to use for the + workstation configuration. + + This corresponds to the ``workstation_config_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation_config, workstation_config_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, workstations.CreateWorkstationConfigRequest): + request = workstations.CreateWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_config is not None: + request.workstation_config = workstation_config + if workstation_config_id is not None: + request.workstation_config_id = workstation_config_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_workstation_config] + + # Certain fields should be provided within 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation_config(self, + request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, + *, + workstation_config: Optional[workstations.WorkstationConfig] = 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, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an existing workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_update_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest, dict]]): + The request object. Request message for + UpdateWorkstationConfig. + workstation_config (:class:`google.cloud.workstations_v1beta.types.WorkstationConfig`): + Required. Config to update. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask specifying which + fields in the workstation configuration + should 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_config, 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, workstations.UpdateWorkstationConfigRequest): + request = workstations.UpdateWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_config is not None: + request.workstation_config = workstation_config + 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_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_config.name", request.workstation_config.name), + )), + ) + + # 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation_config(self, + request: Optional[Union[workstations.DeleteWorkstationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_delete_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest, dict]]): + The request object. Message for deleting a workstation + configuration. + name (:class:`str`): + Required. Name of the workstation + configuration to delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationConfigRequest): + request = workstations.DeleteWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_config] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_workstation(self, + request: Optional[Union[workstations.GetWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.Workstation: + r"""Returns the requested workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_get_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationRequest, dict]]): + The request object. Request message for GetWorkstation. + name (:class:`str`): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.types.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationRequest): + request = workstations.GetWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation] + + # Certain fields should be provided within 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_workstations(self, + request: Optional[Union[workstations.ListWorkstationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationsAsyncPager: + r"""Returns all Workstations using the specified + workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationsRequest, dict]]): + The request object. Request message for ListWorkstations. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationsAsyncPager: + Response message for + ListWorkstations. + 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, workstations.ListWorkstationsRequest): + request = workstations.ListWorkstationsRequest(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_workstations] + + # Certain fields should be provided within 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.ListWorkstationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_usable_workstations(self, + request: Optional[Union[workstations.ListUsableWorkstationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUsableWorkstationsAsyncPager: + r"""Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_usable_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest, dict]]): + The request object. Request message for + ListUsableWorkstations. + parent (:class:`str`): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsAsyncPager: + Response message for + ListUsableWorkstations. + 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, workstations.ListUsableWorkstationsRequest): + request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] + + # Certain fields should be provided within 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.ListUsableWorkstationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation(self, + request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation: Optional[workstations.Workstation] = None, + workstation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_create_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationRequest, dict]]): + The request object. Message for creating a + CreateWorkstation. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation (:class:`google.cloud.workstations_v1beta.types.Workstation`): + Required. Workstation to create. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_id (:class:`str`): + Required. ID to use for the + workstation. + + This corresponds to the ``workstation_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation, workstation_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, workstations.CreateWorkstationRequest): + request = workstations.CreateWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation is not None: + request.workstation = workstation + if workstation_id is not None: + request.workstation_id = workstation_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_workstation] + + # Certain fields should be provided within 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation(self, + request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, + *, + workstation: Optional[workstations.Workstation] = 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, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an existing workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_update_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationRequest, dict]]): + The request object. Request message for + UpdateWorkstation. + workstation (:class:`google.cloud.workstations_v1beta.types.Workstation`): + Required. Workstation to update. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask specifying which + fields in the workstation configuration + should 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation, 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, workstations.UpdateWorkstationRequest): + request = workstations.UpdateWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + 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_workstation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation.name", request.workstation.name), + )), + ) + + # 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation(self, + request: Optional[Union[workstations.DeleteWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_delete_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationRequest, dict]]): + The request object. Request message for + DeleteWorkstation. + name (:class:`str`): + Required. Name of the workstation to + delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationRequest): + request = workstations.DeleteWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def start_workstation(self, + request: Optional[Union[workstations.StartWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts running a workstation so that users can + connect to it. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_start_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.StartWorkstationRequest, dict]]): + The request object. Request message for StartWorkstation. + name (:class:`str`): + Required. Name of the workstation to + start. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.StartWorkstationRequest): + request = workstations.StartWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.start_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def stop_workstation(self, + request: Optional[Union[workstations.StopWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Stops running a workstation, reducing costs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_stop_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.StopWorkstationRequest, dict]]): + The request object. Request message for StopWorkstation. + name (:class:`str`): + Required. Name of the workstation to + stop. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.StopWorkstationRequest): + request = workstations.StopWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.stop_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_access_token(self, + request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, + *, + workstation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.GenerateAccessTokenResponse: + r"""Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_generate_access_token(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = await client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest, dict]]): + The request object. Request message for + GenerateAccessToken. + workstation (:class:`str`): + Required. Name of the workstation for + which the access token should be + generated. + + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_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. + + Returns: + google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, workstations.GenerateAccessTokenRequest): + request = workstations.GenerateAccessTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation", request.workstation), + )), + ) + + # Validate the universe domain. + self._client._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_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # 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.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within 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_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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # 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.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # 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.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._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_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._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) -> "WorkstationsAsyncClient": + 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__ = ( + "WorkstationsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py new file mode 100644 index 000000000000..ab254329c5e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py @@ -0,0 +1,3536 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.workstations_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 + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.services.workstations import pagers +from google.cloud.workstations_v1beta.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WorkstationsGrpcTransport +from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .transports.rest import WorkstationsRestTransport + + +class WorkstationsClientMeta(type): + """Metaclass for the Workstations 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[WorkstationsTransport]] + _transport_registry["grpc"] = WorkstationsGrpcTransport + _transport_registry["grpc_asyncio"] = WorkstationsGrpcAsyncIOTransport + _transport_registry["rest"] = WorkstationsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WorkstationsTransport]: + """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 WorkstationsClient(metaclass=WorkstationsClientMeta): + """Service for interacting with Cloud Workstations.""" + + @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 = "workstations.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "workstations.{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: + WorkstationsClient: 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: + WorkstationsClient: 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) -> WorkstationsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkstationsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def workstation_path(project: str,location: str,workstation_cluster: str,workstation_config: str,workstation: str,) -> str: + """Returns a fully-qualified workstation string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) + + @staticmethod + def parse_workstation_path(path: str) -> Dict[str,str]: + """Parses a workstation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?P.+?)/workstations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workstation_cluster_path(project: str,location: str,workstation_cluster: str,) -> str: + """Returns a fully-qualified workstation_cluster string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) + + @staticmethod + def parse_workstation_cluster_path(path: str) -> Dict[str,str]: + """Parses a workstation_cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workstation_config_path(project: str,location: str,workstation_cluster: str,workstation_config: str,) -> str: + """Returns a fully-qualified workstation_config string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) + + @staticmethod + def parse_workstation_config_path(path: str) -> Dict[str,str]: + """Parses a workstation_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?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 = WorkstationsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = WorkstationsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WorkstationsClient._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 = WorkstationsClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = WorkstationsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + WorkstationsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, WorkstationsTransport, Callable[..., WorkstationsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workstations client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,WorkstationsTransport,Callable[..., WorkstationsTransport]]]): + 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 WorkstationsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = WorkstationsClient._read_environment_variables() + self._client_cert_source = WorkstationsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = WorkstationsClient._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 + + 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, WorkstationsTransport) + if transport_provided: + # transport is a WorkstationsTransport 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(WorkstationsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + WorkstationsClient._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[WorkstationsTransport], Callable[..., WorkstationsTransport]] = ( + WorkstationsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WorkstationsTransport], 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, + ) + + def get_workstation_cluster(self, + request: Optional[Union[workstations.GetWorkstationClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.WorkstationCluster: + r"""Returns the requested workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest, dict]): + The request object. Request message for + GetWorkstationCluster. + name (str): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.types.WorkstationCluster: + A workstation cluster resource in the + Cloud Workstations API. + Defines a group of workstations in a + particular region and the VPC network + they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationClusterRequest): + request = workstations.GetWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_cluster] + + # Certain fields should be provided within 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_workstation_clusters(self, + request: Optional[Union[workstations.ListWorkstationClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationClustersPager: + r"""Returns all workstation clusters in the specified + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest, dict]): + The request object. Request message for + ListWorkstationClusters. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersPager: + Response message for + ListWorkstationClusters. + 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, workstations.ListWorkstationClustersRequest): + request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] + + # Certain fields should be provided within 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.ListWorkstationClustersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation_cluster(self, + request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_cluster: Optional[workstations.WorkstationCluster] = None, + workstation_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest, dict]): + The request object. Message for creating a + CreateWorkstationCluster. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): + Required. Workstation cluster to + create. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster_id (str): + Required. ID to use for the + workstation cluster. + + This corresponds to the ``workstation_cluster_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation_cluster, workstation_cluster_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, workstations.CreateWorkstationClusterRequest): + request = workstations.CreateWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + if workstation_cluster_id is not None: + request.workstation_cluster_id = workstation_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation_cluster] + + # Certain fields should be provided within 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation_cluster(self, + request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, + *, + workstation_cluster: Optional[workstations.WorkstationCluster] = 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, str]] = (), + ) -> operation.Operation: + r"""Updates an existing workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest, dict]): + The request object. Request message for + UpdateWorkstationCluster. + workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): + Required. Workstation cluster to + update. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask that specifies which + fields in the workstation cluster should + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_cluster, 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, workstations.UpdateWorkstationClusterRequest): + request = workstations.UpdateWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + 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_workstation_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_cluster.name", request.workstation_cluster.name), + )), + ) + + # 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation_cluster(self, + request: Optional[Union[workstations.DeleteWorkstationClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest, dict]): + The request object. Message for deleting a workstation + cluster. + name (str): + Required. Name of the workstation + cluster to delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` + A workstation cluster resource in the Cloud Workstations + API. + + Defines a group of workstations in a particular + region and the VPC network they're attached to. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationClusterRequest): + request = workstations.DeleteWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_cluster] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_workstation_config(self, + request: Optional[Union[workstations.GetWorkstationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.WorkstationConfig: + r"""Returns the requested workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_get_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest, dict]): + The request object. Request message for + GetWorkstationConfig. + name (str): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.types.WorkstationConfig: + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationConfigRequest): + request = workstations.GetWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_config] + + # Certain fields should be provided within 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_workstation_configs(self, + request: Optional[Union[workstations.ListWorkstationConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationConfigsPager: + r"""Returns all workstation configurations in the + specified cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest, dict]): + The request object. Request message for + ListWorkstationConfigs. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsPager: + Response message for + ListWorkstationConfigs. + 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, workstations.ListWorkstationConfigsRequest): + request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] + + # Certain fields should be provided within 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.ListWorkstationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_usable_workstation_configs(self, + request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUsableWorkstationConfigsPager: + r"""Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest, dict]): + The request object. Request message for + ListUsableWorkstationConfigs. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsPager: + Response message for + ListUsableWorkstationConfigs. + 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, workstations.ListUsableWorkstationConfigsRequest): + request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] + + # Certain fields should be provided within 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.ListUsableWorkstationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation_config(self, + request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_config: Optional[workstations.WorkstationConfig] = None, + workstation_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_create_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest, dict]): + The request object. Message for creating a + CreateWorkstationConfig. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): + Required. Config to create. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config_id (str): + Required. ID to use for the + workstation configuration. + + This corresponds to the ``workstation_config_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation_config, workstation_config_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, workstations.CreateWorkstationConfigRequest): + request = workstations.CreateWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_config is not None: + request.workstation_config = workstation_config + if workstation_config_id is not None: + request.workstation_config_id = workstation_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation_config] + + # Certain fields should be provided within 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation_config(self, + request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, + *, + workstation_config: Optional[workstations.WorkstationConfig] = 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, str]] = (), + ) -> operation.Operation: + r"""Updates an existing workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_update_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest, dict]): + The request object. Request message for + UpdateWorkstationConfig. + workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): + Required. Config to update. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which + fields in the workstation configuration + should 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_config, 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, workstations.UpdateWorkstationConfigRequest): + request = workstations.UpdateWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_config is not None: + request.workstation_config = workstation_config + 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_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_config.name", request.workstation_config.name), + )), + ) + + # 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation_config(self, + request: Optional[Union[workstations.DeleteWorkstationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_delete_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest, dict]): + The request object. Message for deleting a workstation + configuration. + name (str): + Required. Name of the workstation + configuration to delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to + use, and more. Administrators and platform teams can + also use [Identity and Access Management + (IAM)](https://cloud.google.com/iam/docs/overview) + rules to grant access to teams or to individual + developers. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationConfigRequest): + request = workstations.DeleteWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation_config] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_workstation(self, + request: Optional[Union[workstations.GetWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.Workstation: + r"""Returns the requested workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_get_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.GetWorkstationRequest, dict]): + The request object. Request message for GetWorkstation. + name (str): + Required. Name of the requested + resource. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.types.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.GetWorkstationRequest): + request = workstations.GetWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation] + + # Certain fields should be provided within 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_workstations(self, + request: Optional[Union[workstations.ListWorkstationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWorkstationsPager: + r"""Returns all Workstations using the specified + workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListWorkstationsRequest, dict]): + The request object. Request message for ListWorkstations. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationsPager: + Response message for + ListWorkstations. + 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, workstations.ListWorkstationsRequest): + request = workstations.ListWorkstationsRequest(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_workstations] + + # Certain fields should be provided within 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.ListWorkstationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_usable_workstations(self, + request: Optional[Union[workstations.ListUsableWorkstationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUsableWorkstationsPager: + r"""Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_usable_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest, dict]): + The request object. Request message for + ListUsableWorkstations. + parent (str): + Required. Parent resource name. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsPager: + Response message for + ListUsableWorkstations. + 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, workstations.ListUsableWorkstationsRequest): + request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] + + # Certain fields should be provided within 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.ListUsableWorkstationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation(self, + request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation: Optional[workstations.Workstation] = None, + workstation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_create_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationRequest, dict]): + The request object. Message for creating a + CreateWorkstation. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation (google.cloud.workstations_v1beta.types.Workstation): + Required. Workstation to create. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_id (str): + Required. ID to use for the + workstation. + + This corresponds to the ``workstation_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstation, workstation_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, workstations.CreateWorkstationRequest): + request = workstations.CreateWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation is not None: + request.workstation = workstation + if workstation_id is not None: + request.workstation_id = workstation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation] + + # Certain fields should be provided within 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation(self, + request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, + *, + workstation: Optional[workstations.Workstation] = 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, str]] = (), + ) -> operation.Operation: + r"""Updates an existing workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_update_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationRequest, dict]): + The request object. Request message for + UpdateWorkstation. + workstation (google.cloud.workstations_v1beta.types.Workstation): + Required. Workstation to update. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which + fields in the workstation configuration + should 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation, 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, workstations.UpdateWorkstationRequest): + request = workstations.UpdateWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + 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_workstation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation.name", request.workstation.name), + )), + ) + + # 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation(self, + request: Optional[Union[workstations.DeleteWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_delete_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationRequest, dict]): + The request object. Request message for + DeleteWorkstation. + name (str): + Required. Name of the workstation to + delete. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.DeleteWorkstationRequest): + request = workstations.DeleteWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def start_workstation(self, + request: Optional[Union[workstations.StartWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts running a workstation so that users can + connect to it. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_start_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.StartWorkstationRequest, dict]): + The request object. Request message for StartWorkstation. + name (str): + Required. Name of the workstation to + start. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.StartWorkstationRequest): + request = workstations.StartWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.start_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def stop_workstation(self, + request: Optional[Union[workstations.StopWorkstationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Stops running a workstation, reducing costs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_stop_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.StopWorkstationRequest, dict]): + The request object. Request message for StopWorkstation. + name (str): + Required. Name of the workstation to + stop. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, workstations.StopWorkstationRequest): + request = workstations.StopWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.stop_workstation] + + # Certain fields should be provided within 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_access_token(self, + request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, + *, + workstation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.GenerateAccessTokenResponse: + r"""Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_generate_access_token(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest, dict]): + The request object. Request message for + GenerateAccessToken. + workstation (str): + Required. Name of the workstation for + which the access token should be + generated. + + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.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. + + Returns: + google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, workstations.GenerateAccessTokenRequest): + request = workstations.GenerateAccessTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation", request.workstation), + )), + ) + + # Validate the universe 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) -> "WorkstationsClient": + 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 list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.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. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # 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.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within 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_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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.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. + Returns: + None + """ + # 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.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.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. + Returns: + None + """ + # 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.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.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. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe 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_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.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. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.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. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the 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__ = ( + "WorkstationsClient", +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py new file mode 100644 index 000000000000..35c0d313cec9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py @@ -0,0 +1,702 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.workstations_v1beta.types import workstations + + +class ListWorkstationClustersPager: + """A pager for iterating through ``list_workstation_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstationClusters`` requests and continue to iterate + through the ``workstation_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListWorkstationClustersResponse], + request: workstations.ListWorkstationClustersRequest, + response: workstations.ListWorkstationClustersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationClustersRequest(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[workstations.ListWorkstationClustersResponse]: + 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[workstations.WorkstationCluster]: + for page in self.pages: + yield from page.workstation_clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationClustersAsyncPager: + """A pager for iterating through ``list_workstation_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstationClusters`` requests and continue to iterate + through the ``workstation_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` + attributes are available on the 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[workstations.ListWorkstationClustersResponse]], + request: workstations.ListWorkstationClustersRequest, + response: workstations.ListWorkstationClustersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationClustersRequest(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[workstations.ListWorkstationClustersResponse]: + 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[workstations.WorkstationCluster]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationConfigsPager: + """A pager for iterating through ``list_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListWorkstationConfigsResponse], + request: workstations.ListWorkstationConfigsRequest, + response: workstations.ListWorkstationConfigsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationConfigsRequest(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[workstations.ListWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + for page in self.pages: + yield from page.workstation_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationConfigsAsyncPager: + """A pager for iterating through ``list_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` + attributes are available on the 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[workstations.ListWorkstationConfigsResponse]], + request: workstations.ListWorkstationConfigsRequest, + response: workstations.ListWorkstationConfigsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationConfigsRequest(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[workstations.ListWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationConfigsPager: + """A pager for iterating through ``list_usable_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsableWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListUsableWorkstationConfigsResponse], + request: workstations.ListUsableWorkstationConfigsRequest, + response: workstations.ListUsableWorkstationConfigsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListUsableWorkstationConfigsRequest(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[workstations.ListUsableWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + for page in self.pages: + yield from page.workstation_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationConfigsAsyncPager: + """A pager for iterating through ``list_usable_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsableWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` + attributes are available on the 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[workstations.ListUsableWorkstationConfigsResponse]], + request: workstations.ListUsableWorkstationConfigsRequest, + response: workstations.ListUsableWorkstationConfigsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListUsableWorkstationConfigsRequest(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[workstations.ListUsableWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationsPager: + """A pager for iterating through ``list_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListWorkstationsResponse], + request: workstations.ListWorkstationsRequest, + response: workstations.ListWorkstationsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationsRequest(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[workstations.ListWorkstationsResponse]: + 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[workstations.Workstation]: + for page in self.pages: + yield from page.workstations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationsAsyncPager: + """A pager for iterating through ``list_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` + attributes are available on the 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[workstations.ListWorkstationsResponse]], + request: workstations.ListWorkstationsRequest, + response: workstations.ListWorkstationsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListWorkstationsRequest(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[workstations.ListWorkstationsResponse]: + 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[workstations.Workstation]: + async def async_generator(): + async for page in self.pages: + for response in page.workstations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationsPager: + """A pager for iterating through ``list_usable_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsableWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., workstations.ListUsableWorkstationsResponse], + request: workstations.ListUsableWorkstationsRequest, + response: workstations.ListUsableWorkstationsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListUsableWorkstationsRequest(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[workstations.ListUsableWorkstationsResponse]: + 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[workstations.Workstation]: + for page in self.pages: + yield from page.workstations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationsAsyncPager: + """A pager for iterating through ``list_usable_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsableWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` + attributes are available on the 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[workstations.ListUsableWorkstationsResponse]], + request: workstations.ListUsableWorkstationsRequest, + response: workstations.ListUsableWorkstationsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = workstations.ListUsableWorkstationsRequest(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[workstations.ListUsableWorkstationsResponse]: + 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[workstations.Workstation]: + async def async_generator(): + async for page in self.pages: + for response in page.workstations: + 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-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/README.rst b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/README.rst new file mode 100644 index 000000000000..e25a7cc4b1cf --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`WorkstationsTransport` is the ABC for all transports. +- public child `WorkstationsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `WorkstationsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseWorkstationsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `WorkstationsRestTransport` 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-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py new file mode 100644 index 000000000000..3ae547e57985 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/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 WorkstationsTransport +from .grpc import WorkstationsGrpcTransport +from .grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .rest import WorkstationsRestTransport +from .rest import WorkstationsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WorkstationsTransport]] +_transport_registry['grpc'] = WorkstationsGrpcTransport +_transport_registry['grpc_asyncio'] = WorkstationsGrpcAsyncIOTransport +_transport_registry['rest'] = WorkstationsRestTransport + +__all__ = ( + 'WorkstationsTransport', + 'WorkstationsGrpcTransport', + 'WorkstationsGrpcAsyncIOTransport', + 'WorkstationsRestTransport', + 'WorkstationsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py new file mode 100644 index 000000000000..7b2c872c486e --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.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 abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.workstations_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.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.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WorkstationsTransport(abc.ABC): + """Abstract transport class for Workstations.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'workstations.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: 'workstations.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_workstation_cluster: gapic_v1.method.wrap_method( + self.get_workstation_cluster, + 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_workstation_clusters: gapic_v1.method.wrap_method( + self.list_workstation_clusters, + 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.create_workstation_cluster: gapic_v1.method.wrap_method( + self.create_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_cluster: gapic_v1.method.wrap_method( + self.update_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_cluster: gapic_v1.method.wrap_method( + self.delete_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation_config: gapic_v1.method.wrap_method( + self.get_workstation_config, + 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_workstation_configs: gapic_v1.method.wrap_method( + self.list_workstation_configs, + 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_usable_workstation_configs: gapic_v1.method.wrap_method( + self.list_usable_workstation_configs, + 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.create_workstation_config: gapic_v1.method.wrap_method( + self.create_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_config: gapic_v1.method.wrap_method( + self.update_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_config: gapic_v1.method.wrap_method( + self.delete_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation: gapic_v1.method.wrap_method( + self.get_workstation, + 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_workstations: gapic_v1.method.wrap_method( + self.list_workstations, + 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_usable_workstations: gapic_v1.method.wrap_method( + self.list_usable_workstations, + 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.create_workstation: gapic_v1.method.wrap_method( + self.create_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation: gapic_v1.method.wrap_method( + self.update_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation: gapic_v1.method.wrap_method( + self.delete_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.start_workstation: gapic_v1.method.wrap_method( + self.start_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.stop_workstation: gapic_v1.method.wrap_method( + self.stop_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_access_token: gapic_v1.method.wrap_method( + self.generate_access_token, + 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_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + 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, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + 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 get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + Union[ + workstations.WorkstationCluster, + Awaitable[workstations.WorkstationCluster] + ]]: + raise NotImplementedError() + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + Union[ + workstations.ListWorkstationClustersResponse, + Awaitable[workstations.ListWorkstationClustersResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + Union[ + workstations.WorkstationConfig, + Awaitable[workstations.WorkstationConfig] + ]]: + raise NotImplementedError() + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + Union[ + workstations.ListWorkstationConfigsResponse, + Awaitable[workstations.ListWorkstationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + Union[ + workstations.ListUsableWorkstationConfigsResponse, + Awaitable[workstations.ListUsableWorkstationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + Union[ + workstations.Workstation, + Awaitable[workstations.Workstation] + ]]: + raise NotImplementedError() + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + Union[ + workstations.ListWorkstationsResponse, + Awaitable[workstations.ListWorkstationsResponse] + ]]: + raise NotImplementedError() + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + Union[ + workstations.ListUsableWorkstationsResponse, + Awaitable[workstations.ListUsableWorkstationsResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + Union[ + workstations.GenerateAccessTokenResponse, + Awaitable[workstations.GenerateAccessTokenResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WorkstationsTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py new file mode 100644 index 000000000000..7432aac344da --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py @@ -0,0 +1,948 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO + + +class WorkstationsGrpcTransport(WorkstationsTransport): + """gRPC backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workstations.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: 'workstations.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'workstations.googleapis.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.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + workstations.WorkstationCluster]: + r"""Return a callable for the get workstation cluster method over gRPC. + + Returns the requested workstation cluster. + + Returns: + Callable[[~.GetWorkstationClusterRequest], + ~.WorkstationCluster]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstationCluster', + request_serializer=workstations.GetWorkstationClusterRequest.serialize, + response_deserializer=workstations.WorkstationCluster.deserialize, + ) + return self._stubs['get_workstation_cluster'] + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + workstations.ListWorkstationClustersResponse]: + r"""Return a callable for the list workstation clusters method over gRPC. + + Returns all workstation clusters in the specified + location. + + Returns: + Callable[[~.ListWorkstationClustersRequest], + ~.ListWorkstationClustersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: + self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstationClusters', + request_serializer=workstations.ListWorkstationClustersRequest.serialize, + response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, + ) + return self._stubs['list_workstation_clusters'] + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation cluster method over gRPC. + + Creates a new workstation cluster. + + Returns: + Callable[[~.CreateWorkstationClusterRequest], + ~.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 'create_workstation_cluster' not in self._stubs: + self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationCluster', + request_serializer=workstations.CreateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_cluster'] + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation cluster method over gRPC. + + Updates an existing workstation cluster. + + Returns: + Callable[[~.UpdateWorkstationClusterRequest], + ~.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 'update_workstation_cluster' not in self._stubs: + self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationCluster', + request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_cluster'] + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation cluster method over gRPC. + + Deletes the specified workstation cluster. + + Returns: + Callable[[~.DeleteWorkstationClusterRequest], + ~.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 'delete_workstation_cluster' not in self._stubs: + self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationCluster', + request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_cluster'] + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + workstations.WorkstationConfig]: + r"""Return a callable for the get workstation config method over gRPC. + + Returns the requested workstation configuration. + + Returns: + Callable[[~.GetWorkstationConfigRequest], + ~.WorkstationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstationConfig', + request_serializer=workstations.GetWorkstationConfigRequest.serialize, + response_deserializer=workstations.WorkstationConfig.deserialize, + ) + return self._stubs['get_workstation_config'] + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + workstations.ListWorkstationConfigsResponse]: + r"""Return a callable for the list workstation configs method over gRPC. + + Returns all workstation configurations in the + specified cluster. + + Returns: + Callable[[~.ListWorkstationConfigsRequest], + ~.ListWorkstationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: + self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstationConfigs', + request_serializer=workstations.ListWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_workstation_configs'] + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + workstations.ListUsableWorkstationConfigsResponse]: + r"""Return a callable for the list usable workstation + configs method over gRPC. + + Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + Returns: + Callable[[~.ListUsableWorkstationConfigsRequest], + ~.ListUsableWorkstationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: + self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstationConfigs', + request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_usable_workstation_configs'] + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation config method over gRPC. + + Creates a new workstation configuration. + + Returns: + Callable[[~.CreateWorkstationConfigRequest], + ~.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 'create_workstation_config' not in self._stubs: + self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationConfig', + request_serializer=workstations.CreateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_config'] + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation config method over gRPC. + + Updates an existing workstation configuration. + + Returns: + Callable[[~.UpdateWorkstationConfigRequest], + ~.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 'update_workstation_config' not in self._stubs: + self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationConfig', + request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_config'] + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation config method over gRPC. + + Deletes the specified workstation configuration. + + Returns: + Callable[[~.DeleteWorkstationConfigRequest], + ~.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 'delete_workstation_config' not in self._stubs: + self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationConfig', + request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_config'] + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + workstations.Workstation]: + r"""Return a callable for the get workstation method over gRPC. + + Returns the requested workstation. + + Returns: + Callable[[~.GetWorkstationRequest], + ~.Workstation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['get_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstation', + request_serializer=workstations.GetWorkstationRequest.serialize, + response_deserializer=workstations.Workstation.deserialize, + ) + return self._stubs['get_workstation'] + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + workstations.ListWorkstationsResponse]: + r"""Return a callable for the list workstations method over gRPC. + + Returns all Workstations using the specified + workstation configuration. + + Returns: + Callable[[~.ListWorkstationsRequest], + ~.ListWorkstationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstations' not in self._stubs: + self._stubs['list_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstations', + request_serializer=workstations.ListWorkstationsRequest.serialize, + response_deserializer=workstations.ListWorkstationsResponse.deserialize, + ) + return self._stubs['list_workstations'] + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + workstations.ListUsableWorkstationsResponse]: + r"""Return a callable for the list usable workstations method over gRPC. + + Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + Returns: + Callable[[~.ListUsableWorkstationsRequest], + ~.ListUsableWorkstationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: + self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstations', + request_serializer=workstations.ListUsableWorkstationsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, + ) + return self._stubs['list_usable_workstations'] + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation method over gRPC. + + Creates a new workstation. + + Returns: + Callable[[~.CreateWorkstationRequest], + ~.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 'create_workstation' not in self._stubs: + self._stubs['create_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstation', + request_serializer=workstations.CreateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation'] + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation method over gRPC. + + Updates an existing workstation. + + Returns: + Callable[[~.UpdateWorkstationRequest], + ~.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 'update_workstation' not in self._stubs: + self._stubs['update_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstation', + request_serializer=workstations.UpdateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation'] + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation method over gRPC. + + Deletes the specified workstation. + + Returns: + Callable[[~.DeleteWorkstationRequest], + ~.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 'delete_workstation' not in self._stubs: + self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstation', + request_serializer=workstations.DeleteWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation'] + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the start workstation method over gRPC. + + Starts running a workstation so that users can + connect to it. + + Returns: + Callable[[~.StartWorkstationRequest], + ~.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 'start_workstation' not in self._stubs: + self._stubs['start_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/StartWorkstation', + request_serializer=workstations.StartWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['start_workstation'] + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the stop workstation method over gRPC. + + Stops running a workstation, reducing costs. + + Returns: + Callable[[~.StopWorkstationRequest], + ~.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 'stop_workstation' not in self._stubs: + self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/StopWorkstation', + request_serializer=workstations.StopWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['stop_workstation'] + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + workstations.GenerateAccessTokenResponse]: + r"""Return a callable for the generate access token method over gRPC. + + Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + ~.GenerateAccessTokenResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GenerateAccessToken', + request_serializer=workstations.GenerateAccessTokenRequest.serialize, + response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs['generate_access_token'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @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.grpc_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 list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WorkstationsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py new file mode 100644 index 000000000000..168cd94b888d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py @@ -0,0 +1,1180 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .grpc import WorkstationsGrpcTransport + + +class WorkstationsGrpcAsyncIOTransport(WorkstationsTransport): + """gRPC AsyncIO backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'workstations.googleapis.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 = 'workstations.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: 'workstations.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + Awaitable[workstations.WorkstationCluster]]: + r"""Return a callable for the get workstation cluster method over gRPC. + + Returns the requested workstation cluster. + + Returns: + Callable[[~.GetWorkstationClusterRequest], + Awaitable[~.WorkstationCluster]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstationCluster', + request_serializer=workstations.GetWorkstationClusterRequest.serialize, + response_deserializer=workstations.WorkstationCluster.deserialize, + ) + return self._stubs['get_workstation_cluster'] + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + Awaitable[workstations.ListWorkstationClustersResponse]]: + r"""Return a callable for the list workstation clusters method over gRPC. + + Returns all workstation clusters in the specified + location. + + Returns: + Callable[[~.ListWorkstationClustersRequest], + Awaitable[~.ListWorkstationClustersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: + self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstationClusters', + request_serializer=workstations.ListWorkstationClustersRequest.serialize, + response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, + ) + return self._stubs['list_workstation_clusters'] + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation cluster method over gRPC. + + Creates a new workstation cluster. + + Returns: + Callable[[~.CreateWorkstationClusterRequest], + 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 'create_workstation_cluster' not in self._stubs: + self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationCluster', + request_serializer=workstations.CreateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_cluster'] + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation cluster method over gRPC. + + Updates an existing workstation cluster. + + Returns: + Callable[[~.UpdateWorkstationClusterRequest], + 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 'update_workstation_cluster' not in self._stubs: + self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationCluster', + request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_cluster'] + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation cluster method over gRPC. + + Deletes the specified workstation cluster. + + Returns: + Callable[[~.DeleteWorkstationClusterRequest], + 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 'delete_workstation_cluster' not in self._stubs: + self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationCluster', + request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_cluster'] + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + Awaitable[workstations.WorkstationConfig]]: + r"""Return a callable for the get workstation config method over gRPC. + + Returns the requested workstation configuration. + + Returns: + Callable[[~.GetWorkstationConfigRequest], + Awaitable[~.WorkstationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstationConfig', + request_serializer=workstations.GetWorkstationConfigRequest.serialize, + response_deserializer=workstations.WorkstationConfig.deserialize, + ) + return self._stubs['get_workstation_config'] + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + Awaitable[workstations.ListWorkstationConfigsResponse]]: + r"""Return a callable for the list workstation configs method over gRPC. + + Returns all workstation configurations in the + specified cluster. + + Returns: + Callable[[~.ListWorkstationConfigsRequest], + Awaitable[~.ListWorkstationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: + self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstationConfigs', + request_serializer=workstations.ListWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_workstation_configs'] + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + Awaitable[workstations.ListUsableWorkstationConfigsResponse]]: + r"""Return a callable for the list usable workstation + configs method over gRPC. + + Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + Returns: + Callable[[~.ListUsableWorkstationConfigsRequest], + Awaitable[~.ListUsableWorkstationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: + self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstationConfigs', + request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_usable_workstation_configs'] + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation config method over gRPC. + + Creates a new workstation configuration. + + Returns: + Callable[[~.CreateWorkstationConfigRequest], + 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 'create_workstation_config' not in self._stubs: + self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationConfig', + request_serializer=workstations.CreateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_config'] + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation config method over gRPC. + + Updates an existing workstation configuration. + + Returns: + Callable[[~.UpdateWorkstationConfigRequest], + 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 'update_workstation_config' not in self._stubs: + self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationConfig', + request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_config'] + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation config method over gRPC. + + Deletes the specified workstation configuration. + + Returns: + Callable[[~.DeleteWorkstationConfigRequest], + 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 'delete_workstation_config' not in self._stubs: + self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationConfig', + request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_config'] + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + Awaitable[workstations.Workstation]]: + r"""Return a callable for the get workstation method over gRPC. + + Returns the requested workstation. + + Returns: + Callable[[~.GetWorkstationRequest], + Awaitable[~.Workstation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['get_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstation', + request_serializer=workstations.GetWorkstationRequest.serialize, + response_deserializer=workstations.Workstation.deserialize, + ) + return self._stubs['get_workstation'] + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + Awaitable[workstations.ListWorkstationsResponse]]: + r"""Return a callable for the list workstations method over gRPC. + + Returns all Workstations using the specified + workstation configuration. + + Returns: + Callable[[~.ListWorkstationsRequest], + Awaitable[~.ListWorkstationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstations' not in self._stubs: + self._stubs['list_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstations', + request_serializer=workstations.ListWorkstationsRequest.serialize, + response_deserializer=workstations.ListWorkstationsResponse.deserialize, + ) + return self._stubs['list_workstations'] + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + Awaitable[workstations.ListUsableWorkstationsResponse]]: + r"""Return a callable for the list usable workstations method over gRPC. + + Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + Returns: + Callable[[~.ListUsableWorkstationsRequest], + Awaitable[~.ListUsableWorkstationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: + self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstations', + request_serializer=workstations.ListUsableWorkstationsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, + ) + return self._stubs['list_usable_workstations'] + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation method over gRPC. + + Creates a new workstation. + + Returns: + Callable[[~.CreateWorkstationRequest], + 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 'create_workstation' not in self._stubs: + self._stubs['create_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstation', + request_serializer=workstations.CreateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation'] + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation method over gRPC. + + Updates an existing workstation. + + Returns: + Callable[[~.UpdateWorkstationRequest], + 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 'update_workstation' not in self._stubs: + self._stubs['update_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstation', + request_serializer=workstations.UpdateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation'] + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation method over gRPC. + + Deletes the specified workstation. + + Returns: + Callable[[~.DeleteWorkstationRequest], + 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 'delete_workstation' not in self._stubs: + self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstation', + request_serializer=workstations.DeleteWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation'] + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the start workstation method over gRPC. + + Starts running a workstation so that users can + connect to it. + + Returns: + Callable[[~.StartWorkstationRequest], + 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 'start_workstation' not in self._stubs: + self._stubs['start_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/StartWorkstation', + request_serializer=workstations.StartWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['start_workstation'] + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the stop workstation method over gRPC. + + Stops running a workstation, reducing costs. + + Returns: + Callable[[~.StopWorkstationRequest], + 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 'stop_workstation' not in self._stubs: + self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/StopWorkstation', + request_serializer=workstations.StopWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['stop_workstation'] + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + Awaitable[workstations.GenerateAccessTokenResponse]]: + r"""Return a callable for the generate access token method over gRPC. + + Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + Awaitable[~.GenerateAccessTokenResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GenerateAccessToken', + request_serializer=workstations.GenerateAccessTokenRequest.serialize, + response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs['generate_access_token'] + + 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_workstation_cluster: self._wrap_method( + self.get_workstation_cluster, + 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_workstation_clusters: self._wrap_method( + self.list_workstation_clusters, + 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.create_workstation_cluster: self._wrap_method( + self.create_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_cluster: self._wrap_method( + self.update_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_cluster: self._wrap_method( + self.delete_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation_config: self._wrap_method( + self.get_workstation_config, + 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_workstation_configs: self._wrap_method( + self.list_workstation_configs, + 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_usable_workstation_configs: self._wrap_method( + self.list_usable_workstation_configs, + 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.create_workstation_config: self._wrap_method( + self.create_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_config: self._wrap_method( + self.update_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_config: self._wrap_method( + self.delete_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation: self._wrap_method( + self.get_workstation, + 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_workstations: self._wrap_method( + self.list_workstations, + 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_usable_workstations: self._wrap_method( + self.list_usable_workstations, + 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.create_workstation: self._wrap_method( + self.create_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation: self._wrap_method( + self.update_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation: self._wrap_method( + self.delete_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.start_workstation: self._wrap_method( + self.start_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.stop_workstation: self._wrap_method( + self.stop_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_access_token: self._wrap_method( + self.generate_access_token, + 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_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @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.grpc_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 list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'WorkstationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py new file mode 100644 index 000000000000..66d847554284 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py @@ -0,0 +1,3048 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.workstations_v1beta.types import workstations +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseWorkstationsRestTransport +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 + + +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 WorkstationsRestInterceptor: + """Interceptor for Workstations. + + 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 WorkstationsRestTransport. + + .. code-block:: python + class MyCustomWorkstationsInterceptor(WorkstationsRestInterceptor): + def pre_create_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_access_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_access_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_usable_workstation_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_usable_workstation_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_usable_workstations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_usable_workstations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstation_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstation_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstation_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstation_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WorkstationsRestTransport(interceptor=MyCustomWorkstationsInterceptor()) + client = WorkstationsClient(transport=transport) + + + """ + def pre_create_workstation(self, request: workstations.CreateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_create_workstation_cluster(self, request: workstations.CreateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_create_workstation_config(self, request: workstations.CreateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_delete_workstation(self, request: workstations.DeleteWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_delete_workstation_cluster(self, request: workstations.DeleteWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_delete_workstation_config(self, request: workstations.DeleteWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_generate_access_token(self, request: workstations.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_generate_access_token(self, response: workstations.GenerateAccessTokenResponse) -> workstations.GenerateAccessTokenResponse: + """Post-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_workstation(self, request: workstations.GetWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation(self, response: workstations.Workstation) -> workstations.Workstation: + """Post-rpc interceptor for get_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_workstation_cluster(self, request: workstations.GetWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation_cluster(self, response: workstations.WorkstationCluster) -> workstations.WorkstationCluster: + """Post-rpc interceptor for get_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_workstation_config(self, request: workstations.GetWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation_config(self, response: workstations.WorkstationConfig) -> workstations.WorkstationConfig: + """Post-rpc interceptor for get_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_usable_workstation_configs(self, request: workstations.ListUsableWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_usable_workstation_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_usable_workstation_configs(self, response: workstations.ListUsableWorkstationConfigsResponse) -> workstations.ListUsableWorkstationConfigsResponse: + """Post-rpc interceptor for list_usable_workstation_configs + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_usable_workstations(self, request: workstations.ListUsableWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_usable_workstations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_usable_workstations(self, response: workstations.ListUsableWorkstationsResponse) -> workstations.ListUsableWorkstationsResponse: + """Post-rpc interceptor for list_usable_workstations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_workstation_clusters(self, request: workstations.ListWorkstationClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationClustersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstation_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstation_clusters(self, response: workstations.ListWorkstationClustersResponse) -> workstations.ListWorkstationClustersResponse: + """Post-rpc interceptor for list_workstation_clusters + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_workstation_configs(self, request: workstations.ListWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstation_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstation_configs(self, response: workstations.ListWorkstationConfigsResponse) -> workstations.ListWorkstationConfigsResponse: + """Post-rpc interceptor for list_workstation_configs + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_workstations(self, request: workstations.ListWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstations(self, response: workstations.ListWorkstationsResponse) -> workstations.ListWorkstationsResponse: + """Post-rpc interceptor for list_workstations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_start_workstation(self, request: workstations.StartWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StartWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_start_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for start_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_stop_workstation(self, request: workstations.StopWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StopWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_stop_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for stop_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_update_workstation(self, request: workstations.UpdateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_update_workstation_cluster(self, request: workstations.UpdateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_update_workstation_config(self, request: workstations.UpdateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations 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 Workstations server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WorkstationsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WorkstationsRestInterceptor + + +class WorkstationsRestTransport(_BaseWorkstationsRestTransport): + """REST backend synchronous transport for Workstations. + + Service for interacting with Cloud Workstations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'workstations.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[WorkstationsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'workstations.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 WorkstationsRestInterceptor() + 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.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta/{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="v1beta") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateWorkstation(_BaseWorkstationsRestTransport._BaseCreateWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.CreateWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.CreateWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation method over HTTP. + + Args: + request (~.workstations.CreateWorkstationRequest): + The request object. Message for creating a + CreateWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_http_options() + request, metadata = self._interceptor.pre_create_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._CreateWorkstation._get_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_create_workstation(resp) + return resp + + class _CreateWorkstationCluster(_BaseWorkstationsRestTransport._BaseCreateWorkstationCluster, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.CreateWorkstationCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.CreateWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation + cluster method over HTTP. + + Args: + request (~.workstations.CreateWorkstationClusterRequest): + The request object. Message for creating a + CreateWorkstationCluster. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_http_options() + request, metadata = self._interceptor.pre_create_workstation_cluster(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._CreateWorkstationCluster._get_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_create_workstation_cluster(resp) + return resp + + class _CreateWorkstationConfig(_BaseWorkstationsRestTransport._BaseCreateWorkstationConfig, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.CreateWorkstationConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.CreateWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation config method over HTTP. + + Args: + request (~.workstations.CreateWorkstationConfigRequest): + The request object. Message for creating a + CreateWorkstationConfig. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_http_options() + request, metadata = self._interceptor.pre_create_workstation_config(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._CreateWorkstationConfig._get_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_create_workstation_config(resp) + return resp + + class _DeleteWorkstation(_BaseWorkstationsRestTransport._BaseDeleteWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.DeleteWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.DeleteWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationRequest): + The request object. Request message for + DeleteWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_http_options() + request, metadata = self._interceptor.pre_delete_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._DeleteWorkstation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, 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_delete_workstation(resp) + return resp + + class _DeleteWorkstationCluster(_BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.DeleteWorkstationCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.DeleteWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation + cluster method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationClusterRequest): + The request object. Message for deleting a workstation + cluster. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_http_options() + request, metadata = self._interceptor.pre_delete_workstation_cluster(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._DeleteWorkstationCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, 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_delete_workstation_cluster(resp) + return resp + + class _DeleteWorkstationConfig(_BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.DeleteWorkstationConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.DeleteWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation config method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationConfigRequest): + The request object. Message for deleting a workstation + configuration. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_http_options() + request, metadata = self._interceptor.pre_delete_workstation_config(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._DeleteWorkstationConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, 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_delete_workstation_config(resp) + return resp + + class _GenerateAccessToken(_BaseWorkstationsRestTransport._BaseGenerateAccessToken, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GenerateAccessToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.GenerateAccessTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.GenerateAccessTokenResponse: + r"""Call the generate access token method over HTTP. + + Args: + request (~.workstations.GenerateAccessTokenRequest): + The request object. Request message for + GenerateAccessToken. + retry (google.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. + + Returns: + ~.workstations.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_http_options() + request, metadata = self._interceptor.pre_generate_access_token(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GenerateAccessToken._get_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 = workstations.GenerateAccessTokenResponse() + pb_resp = workstations.GenerateAccessTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_access_token(resp) + return resp + + class _GetWorkstation(_BaseWorkstationsRestTransport._BaseGetWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GetWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.GetWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.Workstation: + r"""Call the get workstation method over HTTP. + + Args: + request (~.workstations.GetWorkstationRequest): + The request object. Request message for GetWorkstation. + retry (google.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. + + Returns: + ~.workstations.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_http_options() + request, metadata = self._interceptor.pre_get_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GetWorkstation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.Workstation() + pb_resp = workstations.Workstation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation(resp) + return resp + + class _GetWorkstationCluster(_BaseWorkstationsRestTransport._BaseGetWorkstationCluster, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GetWorkstationCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.GetWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.WorkstationCluster: + r"""Call the get workstation cluster method over HTTP. + + Args: + request (~.workstations.GetWorkstationClusterRequest): + The request object. Request message for + GetWorkstationCluster. + retry (google.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. + + Returns: + ~.workstations.WorkstationCluster: + A workstation cluster resource in the + Cloud Workstations API. + Defines a group of workstations in a + particular region and the VPC network + they're attached to. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_http_options() + request, metadata = self._interceptor.pre_get_workstation_cluster(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GetWorkstationCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.WorkstationCluster() + pb_resp = workstations.WorkstationCluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation_cluster(resp) + return resp + + class _GetWorkstationConfig(_BaseWorkstationsRestTransport._BaseGetWorkstationConfig, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GetWorkstationConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.GetWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.WorkstationConfig: + r"""Call the get workstation config method over HTTP. + + Args: + request (~.workstations.GetWorkstationConfigRequest): + The request object. Request message for + GetWorkstationConfig. + retry (google.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. + + Returns: + ~.workstations.WorkstationConfig: + A workstation configuration resource in the Cloud + Workstations API. + + Workstation configurations act as templates for + workstations. The workstation configuration defines + details such as the workstation virtual machine (VM) + instance type, persistent storage, container image + defining environment, which IDE or Code Editor to use, + and more. Administrators and platform teams can also use + `Identity and Access Management + (IAM) `__ + rules to grant access to teams or to individual + developers. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_http_options() + request, metadata = self._interceptor.pre_get_workstation_config(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GetWorkstationConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.WorkstationConfig() + pb_resp = workstations.WorkstationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation_config(resp) + return resp + + class _ListUsableWorkstationConfigs(_BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListUsableWorkstationConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListUsableWorkstationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListUsableWorkstationConfigsResponse: + r"""Call the list usable workstation + configs method over HTTP. + + Args: + request (~.workstations.ListUsableWorkstationConfigsRequest): + The request object. Request message for + ListUsableWorkstationConfigs. + retry (google.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. + + Returns: + ~.workstations.ListUsableWorkstationConfigsResponse: + Response message for + ListUsableWorkstationConfigs. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_http_options() + request, metadata = self._interceptor.pre_list_usable_workstation_configs(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListUsableWorkstationConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListUsableWorkstationConfigsResponse() + pb_resp = workstations.ListUsableWorkstationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_usable_workstation_configs(resp) + return resp + + class _ListUsableWorkstations(_BaseWorkstationsRestTransport._BaseListUsableWorkstations, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListUsableWorkstations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListUsableWorkstationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListUsableWorkstationsResponse: + r"""Call the list usable workstations method over HTTP. + + Args: + request (~.workstations.ListUsableWorkstationsRequest): + The request object. Request message for + ListUsableWorkstations. + retry (google.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. + + Returns: + ~.workstations.ListUsableWorkstationsResponse: + Response message for + ListUsableWorkstations. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_http_options() + request, metadata = self._interceptor.pre_list_usable_workstations(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListUsableWorkstations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListUsableWorkstationsResponse() + pb_resp = workstations.ListUsableWorkstationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_usable_workstations(resp) + return resp + + class _ListWorkstationClusters(_BaseWorkstationsRestTransport._BaseListWorkstationClusters, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListWorkstationClusters") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListWorkstationClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationClustersResponse: + r"""Call the list workstation clusters method over HTTP. + + Args: + request (~.workstations.ListWorkstationClustersRequest): + The request object. Request message for + ListWorkstationClusters. + retry (google.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. + + Returns: + ~.workstations.ListWorkstationClustersResponse: + Response message for + ListWorkstationClusters. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_http_options() + request, metadata = self._interceptor.pre_list_workstation_clusters(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListWorkstationClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListWorkstationClustersResponse() + pb_resp = workstations.ListWorkstationClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstation_clusters(resp) + return resp + + class _ListWorkstationConfigs(_BaseWorkstationsRestTransport._BaseListWorkstationConfigs, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListWorkstationConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListWorkstationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationConfigsResponse: + r"""Call the list workstation configs method over HTTP. + + Args: + request (~.workstations.ListWorkstationConfigsRequest): + The request object. Request message for + ListWorkstationConfigs. + retry (google.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. + + Returns: + ~.workstations.ListWorkstationConfigsResponse: + Response message for + ListWorkstationConfigs. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_http_options() + request, metadata = self._interceptor.pre_list_workstation_configs(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListWorkstationConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListWorkstationConfigsResponse() + pb_resp = workstations.ListWorkstationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstation_configs(resp) + return resp + + class _ListWorkstations(_BaseWorkstationsRestTransport._BaseListWorkstations, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListWorkstations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: workstations.ListWorkstationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationsResponse: + r"""Call the list workstations method over HTTP. + + Args: + request (~.workstations.ListWorkstationsRequest): + The request object. Request message for ListWorkstations. + retry (google.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. + + Returns: + ~.workstations.ListWorkstationsResponse: + Response message for + ListWorkstations. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseListWorkstations._get_http_options() + request, metadata = self._interceptor.pre_list_workstations(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListWorkstations._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListWorkstations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = workstations.ListWorkstationsResponse() + pb_resp = workstations.ListWorkstationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstations(resp) + return resp + + class _StartWorkstation(_BaseWorkstationsRestTransport._BaseStartWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.StartWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.StartWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the start workstation method over HTTP. + + Args: + request (~.workstations.StartWorkstationRequest): + The request object. Request message for StartWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_http_options() + request, metadata = self._interceptor.pre_start_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._StartWorkstation._get_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_start_workstation(resp) + return resp + + class _StopWorkstation(_BaseWorkstationsRestTransport._BaseStopWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.StopWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.StopWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the stop workstation method over HTTP. + + Args: + request (~.workstations.StopWorkstationRequest): + The request object. Request message for StopWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_http_options() + request, metadata = self._interceptor.pre_stop_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._StopWorkstation._get_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_stop_workstation(resp) + return resp + + class _UpdateWorkstation(_BaseWorkstationsRestTransport._BaseUpdateWorkstation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.UpdateWorkstation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.UpdateWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationRequest): + The request object. Request message for + UpdateWorkstation. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_http_options() + request, metadata = self._interceptor.pre_update_workstation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._UpdateWorkstation._get_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_update_workstation(resp) + return resp + + class _UpdateWorkstationCluster(_BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.UpdateWorkstationCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.UpdateWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation + cluster method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationClusterRequest): + The request object. Request message for + UpdateWorkstationCluster. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_http_options() + request, metadata = self._interceptor.pre_update_workstation_cluster(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._UpdateWorkstationCluster._get_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_update_workstation_cluster(resp) + return resp + + class _UpdateWorkstationConfig(_BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.UpdateWorkstationConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: workstations.UpdateWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation config method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationConfigRequest): + The request object. Request message for + UpdateWorkstationConfig. + retry (google.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. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_http_options() + request, metadata = self._interceptor.pre_update_workstation_config(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._UpdateWorkstationConfig._get_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_update_workstation_config(resp) + return resp + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + 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._CreateWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + 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._CreateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + 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._CreateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + 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._DeleteWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + 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._DeleteWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + 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._DeleteWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + workstations.GenerateAccessTokenResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + workstations.Workstation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + workstations.WorkstationCluster]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + workstations.WorkstationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + workstations.ListUsableWorkstationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsableWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + workstations.ListUsableWorkstationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsableWorkstations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + workstations.ListWorkstationClustersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstationClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + workstations.ListWorkstationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + workstations.ListWorkstationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstations(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + 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._StartWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + 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._StopWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + 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._UpdateWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + 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._UpdateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + 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._UpdateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseWorkstationsRestTransport._BaseGetIamPolicy, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.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. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseWorkstationsRestTransport._BaseSetIamPolicy, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.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. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._SetIamPolicy._get_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) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseWorkstationsRestTransport._BaseTestIamPermissions, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.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. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._TestIamPermissions._get_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) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseWorkstationsRestTransport._BaseCancelOperation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.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. + """ + + http_options = _BaseWorkstationsRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseWorkstationsRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._CancelOperation._get_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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseWorkstationsRestTransport._BaseDeleteOperation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(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.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.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. + """ + + http_options = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseWorkstationsRestTransport._BaseGetOperation, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._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) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseWorkstationsRestTransport._BaseListOperations, WorkstationsRestStub): + def __hash__(self): + return hash("WorkstationsRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(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.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.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. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseWorkstationsRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseWorkstationsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseWorkstationsRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + # Send the request + response = WorkstationsRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WorkstationsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest_base.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest_base.py new file mode 100644 index 000000000000..80e432e7895d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest_base.py @@ -0,0 +1,1129 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.workstations_v1beta.types import workstations +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseWorkstationsRestTransport(WorkstationsTransport): + """Base REST backend transport for Workstations. + + 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 = 'workstations.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: 'workstations.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 _BaseCreateWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', + 'body': 'workstation', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.CreateWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateWorkstationCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationClusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{parent=projects/*/locations/*}/workstationClusters', + 'body': 'workstation_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.CreateWorkstationClusterRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateWorkstationConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationConfigId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', + 'body': 'workstation_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.CreateWorkstationConfigRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.DeleteWorkstationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteWorkstationCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.DeleteWorkstationClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteWorkstationConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.DeleteWorkstationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGenerateAccessToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.GenerateAccessTokenRequest.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(_BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.GetWorkstationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetWorkstationCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.GetWorkstationClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetWorkstationConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.GetWorkstationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUsableWorkstationConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListUsableWorkstationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUsableWorkstations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListUsableWorkstationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkstationClusters: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*}/workstationClusters', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListWorkstationClustersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkstationConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListWorkstationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkstations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.ListWorkstationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstations._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStartWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.StartWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseStartWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStopWorkstation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.StopWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseStopWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateWorkstation: + 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': '/v1beta/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + 'body': 'workstation', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.UpdateWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateWorkstationCluster: + 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': '/v1beta/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}', + 'body': 'workstation_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.UpdateWorkstationClusterRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateWorkstationConfig: + 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': '/v1beta/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + 'body': 'workstation_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = workstations.UpdateWorkstationConfigRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + 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': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:getIamPolicy', + }, + ] + 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 + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:setIamPolicy', + 'body': '*', + }, + ] + 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_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:testIamPermissions', + 'body': '*', + }, + ] + 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_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + 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_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta/{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 + + 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': '/v1beta/{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 + + class _BaseListOperations: + 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': '/v1beta/{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__=( + '_BaseWorkstationsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py new file mode 100644 index 000000000000..74244c2b3708 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .workstations import ( + CreateWorkstationClusterRequest, + CreateWorkstationConfigRequest, + CreateWorkstationRequest, + DeleteWorkstationClusterRequest, + DeleteWorkstationConfigRequest, + DeleteWorkstationRequest, + GenerateAccessTokenRequest, + GenerateAccessTokenResponse, + GetWorkstationClusterRequest, + GetWorkstationConfigRequest, + GetWorkstationRequest, + ListUsableWorkstationConfigsRequest, + ListUsableWorkstationConfigsResponse, + ListUsableWorkstationsRequest, + ListUsableWorkstationsResponse, + ListWorkstationClustersRequest, + ListWorkstationClustersResponse, + ListWorkstationConfigsRequest, + ListWorkstationConfigsResponse, + ListWorkstationsRequest, + ListWorkstationsResponse, + OperationMetadata, + StartWorkstationRequest, + StopWorkstationRequest, + UpdateWorkstationClusterRequest, + UpdateWorkstationConfigRequest, + UpdateWorkstationRequest, + Workstation, + WorkstationCluster, + WorkstationConfig, +) + +__all__ = ( + 'CreateWorkstationClusterRequest', + 'CreateWorkstationConfigRequest', + 'CreateWorkstationRequest', + 'DeleteWorkstationClusterRequest', + 'DeleteWorkstationConfigRequest', + 'DeleteWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GetWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'OperationMetadata', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'UpdateWorkstationClusterRequest', + 'UpdateWorkstationConfigRequest', + 'UpdateWorkstationRequest', + 'Workstation', + 'WorkstationCluster', + 'WorkstationConfig', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py new file mode 100644 index 000000000000..3e1612aafe34 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py @@ -0,0 +1,2087 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.workstations.v1beta', + manifest={ + 'WorkstationCluster', + 'WorkstationConfig', + 'Workstation', + 'GetWorkstationClusterRequest', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'CreateWorkstationClusterRequest', + 'UpdateWorkstationClusterRequest', + 'DeleteWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'CreateWorkstationConfigRequest', + 'UpdateWorkstationConfigRequest', + 'DeleteWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'CreateWorkstationRequest', + 'UpdateWorkstationRequest', + 'DeleteWorkstationRequest', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'OperationMetadata', + }, +) + + +class WorkstationCluster(proto.Message): + r"""A workstation cluster resource in the Cloud Workstations API. + + Defines a group of workstations in a particular region and the + VPC network they're attached to. + + Attributes: + name (str): + Full name of this workstation cluster. + display_name (str): + Optional. Human-readable name for this + workstation cluster. + uid (str): + Output only. A system-assigned unique + identifier for this workstation cluster. + reconciling (bool): + Output only. Indicates whether this + workstation cluster is currently being updated + to match its intended state. + annotations (MutableMapping[str, str]): + Optional. Client-specified annotations. + labels (MutableMapping[str, str]): + Optional. + `Labels `__ + that are applied to the workstation cluster and that are + also propagated to the underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + cluster was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + cluster was most recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + cluster was soft-deleted. + etag (str): + Optional. Checksum computed by the server. + May be sent on update and delete requests to + make sure that the client has an up-to-date + value before proceeding. + network (str): + Immutable. Name of the Compute Engine network + in which instances associated with this + workstation cluster will be created. + subnetwork (str): + Immutable. Name of the Compute Engine + subnetwork in which instances associated with + this workstation cluster will be created. Must + be part of the subnetwork specified for this + workstation cluster. + control_plane_ip (str): + Output only. The private IP address of the + control plane for this workstation cluster. + Workstation VMs need access to this IP address + to work with the service, so make sure that your + firewall rules allow egress from the workstation + VMs to this address. + private_cluster_config (google.cloud.workstations_v1beta.types.WorkstationCluster.PrivateClusterConfig): + Optional. Configuration for private + workstation cluster. + degraded (bool): + Output only. Whether this workstation cluster is in degraded + mode, in which case it may require user action to restore + full functionality. Details can be found in + [conditions][google.cloud.workstations.v1beta.WorkstationCluster.conditions]. + conditions (MutableSequence[google.rpc.status_pb2.Status]): + Output only. Status conditions describing the + workstation cluster's current state. + """ + + class PrivateClusterConfig(proto.Message): + r"""Configuration options for private workstation clusters. + + Attributes: + enable_private_endpoint (bool): + Immutable. Whether Workstations endpoint is + private. + cluster_hostname (str): + Output only. Hostname for the workstation + cluster. This field will be populated only when + private endpoint is enabled. To access + workstations in the workstation cluster, create + a new DNS zone mapping this domain name to an + internal IP address and a forwarding rule + mapping that address to the service attachment. + service_attachment_uri (str): + Output only. Service attachment URI for the workstation + cluster. The service attachemnt is created when private + endpoint is enabled. To access workstations in the + workstation cluster, configure access to the managed service + using `Private Service + Connect `__. + allowed_projects (MutableSequence[str]): + Optional. Additional projects that are + allowed to attach to the workstation cluster's + service attachment. By default, the workstation + cluster's project and the VPC host project (if + different) are allowed. + """ + + enable_private_endpoint: bool = proto.Field( + proto.BOOL, + number=1, + ) + cluster_hostname: str = proto.Field( + proto.STRING, + number=2, + ) + service_attachment_uri: str = proto.Field( + proto.STRING, + number=3, + ) + allowed_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + 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, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + ) + network: str = proto.Field( + proto.STRING, + number=10, + ) + subnetwork: str = proto.Field( + proto.STRING, + number=11, + ) + control_plane_ip: str = proto.Field( + proto.STRING, + number=16, + ) + private_cluster_config: PrivateClusterConfig = proto.Field( + proto.MESSAGE, + number=12, + message=PrivateClusterConfig, + ) + degraded: bool = proto.Field( + proto.BOOL, + number=13, + ) + conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=status_pb2.Status, + ) + + +class WorkstationConfig(proto.Message): + r"""A workstation configuration resource in the Cloud Workstations API. + + Workstation configurations act as templates for workstations. The + workstation configuration defines details such as the workstation + virtual machine (VM) instance type, persistent storage, container + image defining environment, which IDE or Code Editor to use, and + more. Administrators and platform teams can also use `Identity and + Access Management + (IAM) `__ rules to grant + access to teams or to individual developers. + + Attributes: + name (str): + Full name of this workstation configuration. + display_name (str): + Optional. Human-readable name for this + workstation configuration. + uid (str): + Output only. A system-assigned unique + identifier for this workstation configuration. + reconciling (bool): + Output only. Indicates whether this + workstation configuration is currently being + updated to match its intended state. + annotations (MutableMapping[str, str]): + Optional. Client-specified annotations. + labels (MutableMapping[str, str]): + Optional. + `Labels `__ + that are applied to the workstation configuration and that + are also propagated to the underlying Compute Engine + resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + configuration was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + configuration was most recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation + configuration was soft-deleted. + etag (str): + Optional. Checksum computed by the server. + May be sent on update and delete requests to + make sure that the client has an up-to-date + value before proceeding. + idle_timeout (google.protobuf.duration_pb2.Duration): + Optional. Number of seconds to wait before automatically + stopping a workstation after it last received user traffic. + + A value of ``"0s"`` indicates that Cloud Workstations VMs + created with this configuration should never time out due to + idleness. Provide + `duration `__ + terminated by ``s`` for seconds—for example, ``"7200s"`` (2 + hours). The default is ``"1200s"`` (20 minutes). + running_timeout (google.protobuf.duration_pb2.Duration): + Optional. Number of seconds that a workstation can run until + it is automatically shut down. We recommend that + workstations be shut down daily to reduce costs and so that + security updates can be applied upon restart. The + [idle_timeout][google.cloud.workstations.v1beta.WorkstationConfig.idle_timeout] + and + [running_timeout][google.cloud.workstations.v1beta.WorkstationConfig.running_timeout] + fields are independent of each other. Note that the + [running_timeout][google.cloud.workstations.v1beta.WorkstationConfig.running_timeout] + field shuts down VMs after the specified time, regardless of + whether or not the VMs are idle. + + Provide duration terminated by ``s`` for seconds—for + example, ``"54000s"`` (15 hours). Defaults to ``"43200s"`` + (12 hours). A value of ``"0s"`` indicates that workstations + using this configuration should never time out. If + [encryption_key][google.cloud.workstations.v1beta.WorkstationConfig.encryption_key] + is set, it must be greater than ``"0s"`` and less than + ``"86400s"`` (24 hours). + + Warning: A value of ``"0s"`` indicates that Cloud + Workstations VMs created with this configuration have no + maximum running time. This is strongly discouraged because + you incur costs and will not pick up security updates. + host (google.cloud.workstations_v1beta.types.WorkstationConfig.Host): + Optional. Runtime host for the workstation. + persistent_directories (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory]): + Optional. Directories to persist across + workstation sessions. + ephemeral_directories (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.EphemeralDirectory]): + Optional. Ephemeral directories which won't + persist across workstation sessions. + container (google.cloud.workstations_v1beta.types.WorkstationConfig.Container): + Optional. Container that runs upon startup + for each workstation using this workstation + configuration. + encryption_key (google.cloud.workstations_v1beta.types.WorkstationConfig.CustomerEncryptionKey): + Immutable. Encrypts resources of this + workstation configuration using a + customer-managed encryption key (CMEK). + + If specified, the boot disk of the Compute + Engine instance and the persistent disk are + encrypted using this encryption key. If this + field is not set, the disks are encrypted using + a generated key. Customer-managed encryption + keys do not protect disk metadata. + + If the customer-managed encryption key is + rotated, when the workstation instance is + stopped, the system attempts to recreate the + persistent disk with the new version of the key. + Be sure to keep older versions of the key until + the persistent disk is recreated. Otherwise, + data on the persistent disk might be lost. + + If the encryption key is revoked, the + workstation session automatically stops within 7 + hours. + + Immutable after the workstation configuration is + created. + readiness_checks (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.ReadinessCheck]): + Optional. Readiness checks to perform when + starting a workstation using this workstation + configuration. Mark a workstation as running + only after all specified readiness checks return + 200 status codes. + replica_zones (MutableSequence[str]): + Optional. Immutable. Specifies the zones used to replicate + the VM and disk resources within the region. If set, exactly + two zones within the workstation cluster's region must be + specified—for example, + ``['us-central1-a', 'us-central1-f']``. If this field is + empty, two default zones within the region are used. + + Immutable after the workstation configuration is created. + degraded (bool): + Output only. Whether this resource is degraded, in which + case it may require user action to restore full + functionality. See also the + [conditions][google.cloud.workstations.v1beta.WorkstationConfig.conditions] + field. + conditions (MutableSequence[google.rpc.status_pb2.Status]): + Output only. Status conditions describing the + current resource state. + enable_audit_agent (bool): + Optional. Whether to enable Linux ``auditd`` logging on the + workstation. When enabled, a service account must also be + specified that has ``logging.buckets.write`` permission on + the project. Operating system audit logging is distinct from + `Cloud Audit + Logs `__. + """ + + class Host(proto.Message): + r"""Runtime host for a workstation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gce_instance (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance): + Specifies a Compute Engine instance as the + host. + + This field is a member of `oneof`_ ``config``. + """ + + class GceInstance(proto.Message): + r"""A runtime using a Compute Engine instance. + + Attributes: + machine_type (str): + Optional. The type of machine to use for VM instances—for + example, ``"e2-standard-4"``. For more information about + machine types that Cloud Workstations supports, see the list + of `available machine + types `__. + service_account (str): + Optional. The email address of the service account for Cloud + Workstations VMs created with this configuration. When + specified, be sure that the service account has + ``logginglogEntries.create`` permission on the project so it + can write logs out to Cloud Logging. If using a custom + container image, the service account must have permissions + to pull the specified image. + + If you as the administrator want to be able to ``ssh`` into + the underlying VM, you need to set this value to a service + account for which you have the ``iam.serviceAccounts.actAs`` + permission. Conversely, if you don't want anyone to be able + to ``ssh`` into the underlying VM, use a service account + where no one has that permission. + + If not set, VMs run with a service account provided by the + Cloud Workstations service, and the image must be publicly + accessible. + service_account_scopes (MutableSequence[str]): + Optional. Scopes to grant to the + [service_account][google.cloud.workstations.v1beta.WorkstationConfig.Host.GceInstance.service_account]. + Various scopes are automatically added based on feature + usage. When specified, users of workstations under this + configuration must have ``iam.serviceAccounts.actAs`` on the + service account. + tags (MutableSequence[str]): + Optional. Network tags to add to the Compute Engine VMs + backing the workstations. This option applies `network + tags `__ + to VMs created with this configuration. These network tags + enable the creation of `firewall + rules `__. + pool_size (int): + Optional. The number of VMs that the system should keep idle + so that new workstations can be started quickly for new + users. Defaults to ``0`` in the API. + pooled_instances (int): + Output only. Number of instances currently + available in the pool for faster workstation + startup. + disable_public_ip_addresses (bool): + Optional. When set to true, disables public IP addresses for + VMs. If you disable public IP addresses, you must set up + Private Google Access or Cloud NAT on your network. If you + use Private Google Access and you use + ``private.googleapis.com`` or ``restricted.googleapis.com`` + for Container Registry and Artifact Registry, make sure that + you set up DNS records for domains ``*.gcr.io`` and + ``*.pkg.dev``. Defaults to false (VMs have public IP + addresses). + enable_nested_virtualization (bool): + Optional. Whether to enable nested virtualization on Cloud + Workstations VMs created under this workstation + configuration. + + Nested virtualization lets you run virtual machine (VM) + instances inside your workstation. Before enabling nested + virtualization, consider the following important + considerations. Cloud Workstations instances are subject to + the `same restrictions as Compute Engine + instances `__: + + - **Organization policy**: projects, folders, or + organizations may be restricted from creating nested VMs + if the **Disable VM nested virtualization** constraint is + enforced in the organization policy. For more + information, see the Compute Engine section, `Checking + whether nested virtualization is + allowed `__. + - **Performance**: nested VMs might experience a 10% or + greater decrease in performance for workloads that are + CPU-bound and possibly greater than a 10% decrease for + workloads that are input/output bound. + - **Machine Type**: nested virtualization can only be + enabled on workstation configurations that specify a + [machine_type][google.cloud.workstations.v1beta.WorkstationConfig.Host.GceInstance.machine_type] + in the N1 or N2 machine series. + - **GPUs**: nested virtualization may not be enabled on + workstation configurations with accelerators. + - **Operating System**: Because `Container-Optimized + OS `__ + does not support nested virtualization, when nested + virtualization is enabled, the underlying Compute Engine + VM instances boot from an `Ubuntu + LTS `__ + image. + shielded_instance_config (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig): + Optional. A set of Compute Engine Shielded + instance options. + confidential_instance_config (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig): + Optional. A set of Compute Engine + Confidential VM instance options. + boot_disk_size_gb (int): + Optional. The size of the boot disk for the VM in gigabytes + (GB). The minimum boot disk size is ``30`` GB. Defaults to + ``50`` GB. + accelerators (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.Accelerator]): + Optional. A list of the type and count of + accelerator cards attached to the instance. + """ + + class GceShieldedInstanceConfig(proto.Message): + r"""A set of Compute Engine Shielded instance options. + + Attributes: + enable_secure_boot (bool): + Optional. Whether the instance has Secure + Boot enabled. + enable_vtpm (bool): + Optional. Whether the instance has the vTPM + enabled. + enable_integrity_monitoring (bool): + Optional. Whether the instance has integrity + monitoring enabled. + """ + + enable_secure_boot: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_vtpm: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_integrity_monitoring: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class GceConfidentialInstanceConfig(proto.Message): + r"""A set of Compute Engine Confidential VM instance options. + + Attributes: + enable_confidential_compute (bool): + Optional. Whether the instance has + confidential compute enabled. + """ + + enable_confidential_compute: bool = proto.Field( + proto.BOOL, + number=1, + ) + + class Accelerator(proto.Message): + r"""An accelerator card attached to the instance. + + Attributes: + type_ (str): + Optional. Type of accelerator resource to attach to the + instance, for example, ``"nvidia-tesla-p100"``. + count (int): + Optional. Number of accelerator cards exposed + to the instance. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + count: int = proto.Field( + proto.INT32, + number=2, + ) + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + service_account: str = proto.Field( + proto.STRING, + number=2, + ) + service_account_scopes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + pool_size: int = proto.Field( + proto.INT32, + number=5, + ) + pooled_instances: int = proto.Field( + proto.INT32, + number=12, + ) + disable_public_ip_addresses: bool = proto.Field( + proto.BOOL, + number=6, + ) + enable_nested_virtualization: bool = proto.Field( + proto.BOOL, + number=7, + ) + shielded_instance_config: 'WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig' = proto.Field( + proto.MESSAGE, + number=8, + message='WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig', + ) + confidential_instance_config: 'WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig' = proto.Field( + proto.MESSAGE, + number=10, + message='WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig', + ) + boot_disk_size_gb: int = proto.Field( + proto.INT32, + number=9, + ) + accelerators: MutableSequence['WorkstationConfig.Host.GceInstance.Accelerator'] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='WorkstationConfig.Host.GceInstance.Accelerator', + ) + + gce_instance: 'WorkstationConfig.Host.GceInstance' = proto.Field( + proto.MESSAGE, + number=1, + oneof='config', + message='WorkstationConfig.Host.GceInstance', + ) + + class PersistentDirectory(proto.Message): + r"""A directory to persist across workstation sessions. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gce_pd (google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk): + A PersistentDirectory backed by a Compute + Engine persistent disk. + + This field is a member of `oneof`_ ``directory_type``. + mount_path (str): + Optional. Location of this directory in the + running workstation. + """ + + class GceRegionalPersistentDisk(proto.Message): + r"""A PersistentDirectory backed by a Compute Engine regional persistent + disk. The + [persistent_directories][google.cloud.workstations.v1beta.WorkstationConfig.persistent_directories] + field is repeated, but it may contain only one entry. It creates a + `persistent + disk `__ + that mounts to the workstation VM at ``/home`` when the session + starts and detaches when the session ends. If this field is empty, + workstations created with this configuration do not have a + persistent home directory. + + Attributes: + size_gb (int): + Optional. The GB capacity of a persistent home directory for + each workstation created with this configuration. Must be + empty if + [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.source_snapshot] + is set. + + Valid values are ``10``, ``50``, ``100``, ``200``, ``500``, + or ``1000``. Defaults to ``200``. If less than ``200`` GB, + the + [disk_type][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.disk_type] + must be ``"pd-balanced"`` or ``"pd-ssd"``. + fs_type (str): + Optional. Type of file system that the disk should be + formatted with. The workstation image must support this file + system type. Must be empty if + [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.source_snapshot] + is set. Defaults to ``"ext4"``. + disk_type (str): + Optional. The `type of the persistent + disk `__ + for the home directory. Defaults to ``"pd-standard"``. + source_snapshot (str): + Optional. Name of the snapshot to use as the source for the + disk. If set, + [size_gb][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.size_gb] + and + [fs_type][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.fs_type] + must be empty. + reclaim_policy (google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy): + Optional. Whether the persistent disk should be deleted when + the workstation is deleted. Valid values are ``DELETE`` and + ``RETAIN``. Defaults to ``DELETE``. + """ + class ReclaimPolicy(proto.Enum): + r"""Value representing what should happen to the disk after the + workstation is deleted. + + Values: + RECLAIM_POLICY_UNSPECIFIED (0): + Do not use. + DELETE (1): + Delete the persistent disk when deleting the + workstation. + RETAIN (2): + Keep the persistent disk when deleting the + workstation. An administrator must manually + delete the disk. + """ + RECLAIM_POLICY_UNSPECIFIED = 0 + DELETE = 1 + RETAIN = 2 + + size_gb: int = proto.Field( + proto.INT32, + number=1, + ) + fs_type: str = proto.Field( + proto.STRING, + number=2, + ) + disk_type: str = proto.Field( + proto.STRING, + number=3, + ) + source_snapshot: str = proto.Field( + proto.STRING, + number=5, + ) + reclaim_policy: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy' = proto.Field( + proto.ENUM, + number=4, + enum='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy', + ) + + gce_pd: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk' = proto.Field( + proto.MESSAGE, + number=2, + oneof='directory_type', + message='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk', + ) + mount_path: str = proto.Field( + proto.STRING, + number=1, + ) + + class EphemeralDirectory(proto.Message): + r"""An ephemeral directory which won't persist across workstation + sessions. It is freshly created on every workstation start + operation. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gce_pd (google.cloud.workstations_v1beta.types.WorkstationConfig.EphemeralDirectory.GcePersistentDisk): + An EphemeralDirectory backed by a Compute + Engine persistent disk. + + This field is a member of `oneof`_ ``directory_type``. + mount_path (str): + Required. Location of this directory in the + running workstation. + """ + + class GcePersistentDisk(proto.Message): + r"""An EphemeralDirectory is backed by a Compute Engine + persistent disk. + + Attributes: + disk_type (str): + Optional. Type of the disk to use. Defaults to + ``"pd-standard"``. + source_snapshot (str): + Optional. Name of the snapshot to use as the source for the + disk. Must be empty if + [source_image][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_image] + is set. Updating + [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_snapshot] + will update content in the ephemeral directory after the + workstation is restarted. This field is mutable. + source_image (str): + Optional. Name of the disk image to use as the source for + the disk. Must be empty if + [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_snapshot] + is set. Updating + [source_image][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_image] + will update content in the ephemeral directory after the + workstation is restarted. This field is mutable. + read_only (bool): + Optional. Whether the disk is read only. If true, the disk + may be shared by multiple VMs and + [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_snapshot] + must be set. + """ + + disk_type: str = proto.Field( + proto.STRING, + number=1, + ) + source_snapshot: str = proto.Field( + proto.STRING, + number=2, + ) + source_image: str = proto.Field( + proto.STRING, + number=3, + ) + read_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + gce_pd: 'WorkstationConfig.EphemeralDirectory.GcePersistentDisk' = proto.Field( + proto.MESSAGE, + number=3, + oneof='directory_type', + message='WorkstationConfig.EphemeralDirectory.GcePersistentDisk', + ) + mount_path: str = proto.Field( + proto.STRING, + number=1, + ) + + class Container(proto.Message): + r"""A Docker container. + + Attributes: + image (str): + Optional. A Docker container image that defines a custom + environment. + + Cloud Workstations provides a number of `preconfigured + images `__, + but you can create your own `custom container + images `__. + If using a private image, the + ``host.gceInstance.serviceAccount`` field must be specified + in the workstation configuration and must have permission to + pull the specified image. Otherwise, the image must be + publicly accessible. + command (MutableSequence[str]): + Optional. If set, overrides the default + ENTRYPOINT specified by the image. + args (MutableSequence[str]): + Optional. Arguments passed to the entrypoint. + env (MutableMapping[str, str]): + Optional. Environment variables passed to the + container's entrypoint. + working_dir (str): + Optional. If set, overrides the default DIR + specified by the image. + run_as_user (int): + Optional. If set, overrides the USER + specified in the image with the given uid. + """ + + image: str = proto.Field( + proto.STRING, + number=1, + ) + command: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + env: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + working_dir: str = proto.Field( + proto.STRING, + number=5, + ) + run_as_user: int = proto.Field( + proto.INT32, + number=6, + ) + + class CustomerEncryptionKey(proto.Message): + r"""A customer-managed encryption key (CMEK) for the Compute Engine + resources of the associated workstation configuration. Specify the + name of your Cloud KMS encryption key and the default service + account. We recommend that you use a separate service account and + follow `Cloud KMS best + practices `__. + + Attributes: + kms_key (str): + Immutable. The name of the Google Cloud KMS encryption key. + For example, + ``"projects/PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY_NAME"``. + The key must be in the same region as the workstation + configuration. + kms_key_service_account (str): + Immutable. The service account to use with the specified KMS + key. We recommend that you use a separate service account + and follow KMS best practices. For more information, see + `Separation of + duties `__ + and ``gcloud kms keys add-iam-policy-binding`` + ```--member`` `__. + """ + + kms_key: str = proto.Field( + proto.STRING, + number=1, + ) + kms_key_service_account: str = proto.Field( + proto.STRING, + number=2, + ) + + class ReadinessCheck(proto.Message): + r"""A readiness check to be performed on a workstation. + + Attributes: + path (str): + Optional. Path to which the request should be + sent. + port (int): + Optional. Port to which the request should be + sent. + """ + + path: str = proto.Field( + proto.STRING, + number=1, + ) + port: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=18, + ) + 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, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + ) + idle_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + message=duration_pb2.Duration, + ) + running_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=11, + message=duration_pb2.Duration, + ) + host: Host = proto.Field( + proto.MESSAGE, + number=12, + message=Host, + ) + persistent_directories: MutableSequence[PersistentDirectory] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=PersistentDirectory, + ) + ephemeral_directories: MutableSequence[EphemeralDirectory] = proto.RepeatedField( + proto.MESSAGE, + number=22, + message=EphemeralDirectory, + ) + container: Container = proto.Field( + proto.MESSAGE, + number=14, + message=Container, + ) + encryption_key: CustomerEncryptionKey = proto.Field( + proto.MESSAGE, + number=17, + message=CustomerEncryptionKey, + ) + readiness_checks: MutableSequence[ReadinessCheck] = proto.RepeatedField( + proto.MESSAGE, + number=19, + message=ReadinessCheck, + ) + replica_zones: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=23, + ) + degraded: bool = proto.Field( + proto.BOOL, + number=15, + ) + conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message=status_pb2.Status, + ) + enable_audit_agent: bool = proto.Field( + proto.BOOL, + number=20, + ) + + +class Workstation(proto.Message): + r"""A single instance of a developer workstation with its own + persistent storage. + + Attributes: + name (str): + Full name of this workstation. + display_name (str): + Optional. Human-readable name for this + workstation. + uid (str): + Output only. A system-assigned unique + identifier for this workstation. + reconciling (bool): + Output only. Indicates whether this + workstation is currently being updated to match + its intended state. + annotations (MutableMapping[str, str]): + Optional. Client-specified annotations. + labels (MutableMapping[str, str]): + Optional. + `Labels `__ + that are applied to the workstation and that are also + propagated to the underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation was + most recently updated. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation was + most recently successfully started, regardless + of the workstation's initial state. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this workstation was + soft-deleted. + etag (str): + Optional. Checksum computed by the server. + May be sent on update and delete requests to + make sure that the client has an up-to-date + value before proceeding. + state (google.cloud.workstations_v1beta.types.Workstation.State): + Output only. Current state of the + workstation. + host (str): + Output only. Host to which clients can send HTTPS traffic + that will be received by the workstation. Authorized traffic + will be received to the workstation as HTTP on port 80. To + send traffic to a different port, clients may prefix the + host with the destination port in the format + ``{port}-{host}``. + env (MutableMapping[str, str]): + Optional. Environment variables passed to the + workstation container's entrypoint. + """ + class State(proto.Enum): + r"""Whether a workstation is running and ready to receive user + requests. + + Values: + STATE_UNSPECIFIED (0): + Do not use. + STATE_STARTING (1): + The workstation is not yet ready to accept + requests from users but will be soon. + STATE_RUNNING (2): + The workstation is ready to accept requests + from users. + STATE_STOPPING (3): + The workstation is being stopped. + STATE_STOPPED (4): + The workstation is stopped and will not be + able to receive requests until it is started. + """ + STATE_UNSPECIFIED = 0 + STATE_STARTING = 1 + STATE_RUNNING = 2 + STATE_STOPPING = 3 + STATE_STOPPED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + 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, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=14, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + host: str = proto.Field( + proto.STRING, + number=11, + ) + env: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + + +class GetWorkstationClusterRequest(proto.Message): + r"""Request message for GetWorkstationCluster. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationClustersRequest(proto.Message): + r"""Request message for ListWorkstationClusters. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListWorkstationClustersResponse(proto.Message): + r"""Response message for ListWorkstationClusters. + + Attributes: + workstation_clusters (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationCluster]): + The requested workstation clusters. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_clusters: MutableSequence['WorkstationCluster'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationCluster', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationClusterRequest(proto.Message): + r"""Message for creating a CreateWorkstationCluster. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_cluster_id (str): + Required. ID to use for the workstation + cluster. + workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): + Required. Workstation cluster to create. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation_cluster: 'WorkstationCluster' = proto.Field( + proto.MESSAGE, + number=3, + message='WorkstationCluster', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationClusterRequest(proto.Message): + r"""Request message for UpdateWorkstationCluster. + + Attributes: + workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): + Required. Workstation cluster to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask that specifies which fields in + the workstation cluster should be updated. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + allow_missing (bool): + Optional. If set, and the workstation cluster is not found, + a new workstation cluster will be created. In this + situation, update_mask is ignored. + """ + + workstation_cluster: 'WorkstationCluster' = proto.Field( + proto.MESSAGE, + number=1, + message='WorkstationCluster', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationClusterRequest(proto.Message): + r"""Message for deleting a workstation cluster. + + Attributes: + name (str): + Required. Name of the workstation cluster to + delete. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not apply it. + etag (str): + Optional. If set, the request will be + rejected if the latest version of the + workstation cluster on the server does not have + this ETag. + force (bool): + Optional. If set, any workstation + configurations and workstations in the + workstation cluster are also deleted. Otherwise, + the request only works if the workstation + cluster has no configurations or workstations. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetWorkstationConfigRequest(proto.Message): + r"""Request message for GetWorkstationConfig. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationConfigsRequest(proto.Message): + r"""Request message for ListWorkstationConfigs. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListWorkstationConfigsResponse(proto.Message): + r"""Response message for ListWorkstationConfigs. + + Attributes: + workstation_configs (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig]): + The requested configs. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationConfigsRequest(proto.Message): + r"""Request message for ListUsableWorkstationConfigs. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListUsableWorkstationConfigsResponse(proto.Message): + r"""Response message for ListUsableWorkstationConfigs. + + Attributes: + workstation_configs (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig]): + The requested configs. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationConfigRequest(proto.Message): + r"""Message for creating a CreateWorkstationConfig. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_config_id (str): + Required. ID to use for the workstation + configuration. + workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): + Required. Config to create. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_config_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation_config: 'WorkstationConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='WorkstationConfig', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationConfigRequest(proto.Message): + r"""Request message for UpdateWorkstationConfig. + + Attributes: + workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): + Required. Config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which fields in the + workstation configuration should be updated. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + allow_missing (bool): + Optional. If set and the workstation configuration is not + found, a new workstation configuration will be created. In + this situation, update_mask is ignored. + """ + + workstation_config: 'WorkstationConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationConfigRequest(proto.Message): + r"""Message for deleting a workstation configuration. + + Attributes: + name (str): + Required. Name of the workstation + configuration to delete. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + etag (str): + Optional. If set, the request is rejected if + the latest version of the workstation + configuration on the server does not have this + ETag. + force (bool): + Optional. If set, any workstations in the + workstation configuration are also deleted. + Otherwise, the request works only if the + workstation configuration has no workstations. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetWorkstationRequest(proto.Message): + r"""Request message for GetWorkstation. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationsRequest(proto.Message): + r"""Request message for ListWorkstations. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListWorkstationsResponse(proto.Message): + r"""Response message for ListWorkstations. + + Attributes: + workstations (MutableSequence[google.cloud.workstations_v1beta.types.Workstation]): + The requested workstations. + next_page_token (str): + Optional. Token to retrieve the next page of + results, or empty if there are no more results + in the list. + unreachable (MutableSequence[str]): + Optional. Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstations: MutableSequence['Workstation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workstation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationsRequest(proto.Message): + r"""Request message for ListUsableWorkstations. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Optional. Maximum number of items to return. + page_token (str): + Optional. next_page_token value returned from a previous + List request, if any. + """ + + 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 ListUsableWorkstationsResponse(proto.Message): + r"""Response message for ListUsableWorkstations. + + Attributes: + workstations (MutableSequence[google.cloud.workstations_v1beta.types.Workstation]): + The requested workstations. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstations: MutableSequence['Workstation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workstation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationRequest(proto.Message): + r"""Message for creating a CreateWorkstation. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_id (str): + Required. ID to use for the workstation. + workstation (google.cloud.workstations_v1beta.types.Workstation): + Required. Workstation to create. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation: 'Workstation' = proto.Field( + proto.MESSAGE, + number=3, + message='Workstation', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationRequest(proto.Message): + r"""Request message for UpdateWorkstation. + + Attributes: + workstation (google.cloud.workstations_v1beta.types.Workstation): + Required. Workstation to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which fields in the + workstation configuration should be updated. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + allow_missing (bool): + Optional. If set and the workstation configuration is not + found, a new workstation configuration is created. In this + situation, update_mask is ignored. + """ + + workstation: 'Workstation' = proto.Field( + proto.MESSAGE, + number=1, + message='Workstation', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationRequest(proto.Message): + r"""Request message for DeleteWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to delete. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + etag (str): + Optional. If set, the request will be + rejected if the latest version of the + workstation on the server does not have this + ETag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class StartWorkstationRequest(proto.Message): + r"""Request message for StartWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to start. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + etag (str): + Optional. If set, the request will be + rejected if the latest version of the + workstation on the server does not have this + ETag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class StopWorkstationRequest(proto.Message): + r"""Request message for StopWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to stop. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not actually apply + it. + etag (str): + Optional. If set, the request will be + rejected if the latest version of the + workstation on the server does not have this + ETag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GenerateAccessTokenRequest(proto.Message): + r"""Request message for GenerateAccessToken. + + 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: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Desired expiration time of the access token. + This value must be at most 24 hours in the + future. If a value is not specified, the token's + expiration time will be set to a default value + of 1 hour in the future. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Desired lifetime duration of the access + token. This value must be at most 24 hours. If a + value is not specified, the token's lifetime + will be set to a default value of 1 hour. + + This field is a member of `oneof`_ ``expiration``. + workstation (str): + Required. Name of the workstation for which + the access token should be generated. + """ + + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + oneof='expiration', + message=duration_pb2.Duration, + ) + workstation: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateAccessTokenResponse(proto.Message): + r"""Response message for GenerateAccessToken. + + Attributes: + access_token (str): + The generated bearer access token. To use this token, + include it in an Authorization header of an HTTP request + sent to the associated workstation's hostname—for example, + ``Authorization: Bearer ``. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the generated token will + expire. + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class OperationMetadata(proto.Message): + r"""Metadata for long-running operations. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time that the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time that the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has + requested cancellation of the operation. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_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, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini b/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py b/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py new file mode 100644 index 000000000000..387cadc75af2 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations' + +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/cloud/workstations_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/cloud/workstations_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-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json new file mode 100644 index 000000000000..8afcd1793b5c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json @@ -0,0 +1,3307 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.workstations.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-workstations", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" + }, + { + "name": "workstation_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation_cluster" + }, + "description": "Sample for CreateWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_create_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_create_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" + }, + { + "name": "workstation_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation_cluster" + }, + "description": "Sample for CreateWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" + }, + { + "name": "workstation_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation_config" + }, + "description": "Sample for CreateWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_create_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_create_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" + }, + { + "name": "workstation_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation_config" + }, + "description": "Sample for CreateWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_create_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_create_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1beta.types.Workstation" + }, + { + "name": "workstation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation" + }, + "description": "Sample for CreateWorkstation", + "file": "workstations_v1beta_generated_workstations_create_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstation_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_create_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1beta.types.Workstation" + }, + { + "name": "workstation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation" + }, + "description": "Sample for CreateWorkstation", + "file": "workstations_v1beta_generated_workstations_create_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstation_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_create_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_workstation_cluster" + }, + "description": "Sample for DeleteWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_workstation_cluster" + }, + "description": "Sample for DeleteWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_workstation_config" + }, + "description": "Sample for DeleteWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_delete_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_delete_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_workstation_config" + }, + "description": "Sample for DeleteWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_delete_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_delete_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_workstation" + }, + "description": "Sample for DeleteWorkstation", + "file": "workstations_v1beta_generated_workstations_delete_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_delete_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_workstation" + }, + "description": "Sample for DeleteWorkstation", + "file": "workstations_v1beta_generated_workstations_delete_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_delete_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.generate_access_token", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GenerateAccessToken", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GenerateAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest" + }, + { + "name": "workstation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse", + "shortName": "generate_access_token" + }, + "description": "Sample for GenerateAccessToken", + "file": "workstations_v1beta_generated_workstations_generate_access_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GenerateAccessToken_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": "workstations_v1beta_generated_workstations_generate_access_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.generate_access_token", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GenerateAccessToken", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GenerateAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest" + }, + { + "name": "workstation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse", + "shortName": "generate_access_token" + }, + "description": "Sample for GenerateAccessToken", + "file": "workstations_v1beta_generated_workstations_generate_access_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GenerateAccessToken_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": "workstations_v1beta_generated_workstations_generate_access_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.WorkstationCluster", + "shortName": "get_workstation_cluster" + }, + "description": "Sample for GetWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_get_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationCluster_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": "workstations_v1beta_generated_workstations_get_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.WorkstationCluster", + "shortName": "get_workstation_cluster" + }, + "description": "Sample for GetWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationCluster_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": "workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.WorkstationConfig", + "shortName": "get_workstation_config" + }, + "description": "Sample for GetWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_get_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationConfig_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": "workstations_v1beta_generated_workstations_get_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.WorkstationConfig", + "shortName": "get_workstation_config" + }, + "description": "Sample for GetWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_get_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationConfig_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": "workstations_v1beta_generated_workstations_get_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.Workstation", + "shortName": "get_workstation" + }, + "description": "Sample for GetWorkstation", + "file": "workstations_v1beta_generated_workstations_get_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstation_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": "workstations_v1beta_generated_workstations_get_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.Workstation", + "shortName": "get_workstation" + }, + "description": "Sample for GetWorkstation", + "file": "workstations_v1beta_generated_workstations_get_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstation_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": "workstations_v1beta_generated_workstations_get_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_usable_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager", + "shortName": "list_usable_workstation_configs" + }, + "description": "Sample for ListUsableWorkstationConfigs", + "file": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_usable_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsPager", + "shortName": "list_usable_workstation_configs" + }, + "description": "Sample for ListUsableWorkstationConfigs", + "file": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_usable_workstations", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsAsyncPager", + "shortName": "list_usable_workstations" + }, + "description": "Sample for ListUsableWorkstations", + "file": "workstations_v1beta_generated_workstations_list_usable_workstations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstations_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": "workstations_v1beta_generated_workstations_list_usable_workstations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_usable_workstations", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsPager", + "shortName": "list_usable_workstations" + }, + "description": "Sample for ListUsableWorkstations", + "file": "workstations_v1beta_generated_workstations_list_usable_workstations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstations_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": "workstations_v1beta_generated_workstations_list_usable_workstations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstation_clusters", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationClusters", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersAsyncPager", + "shortName": "list_workstation_clusters" + }, + "description": "Sample for ListWorkstationClusters", + "file": "workstations_v1beta_generated_workstations_list_workstation_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationClusters_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": "workstations_v1beta_generated_workstations_list_workstation_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstation_clusters", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationClusters", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersPager", + "shortName": "list_workstation_clusters" + }, + "description": "Sample for ListWorkstationClusters", + "file": "workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationClusters_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": "workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsAsyncPager", + "shortName": "list_workstation_configs" + }, + "description": "Sample for ListWorkstationConfigs", + "file": "workstations_v1beta_generated_workstations_list_workstation_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_workstation_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsPager", + "shortName": "list_workstation_configs" + }, + "description": "Sample for ListWorkstationConfigs", + "file": "workstations_v1beta_generated_workstations_list_workstation_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_workstation_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstations", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationsAsyncPager", + "shortName": "list_workstations" + }, + "description": "Sample for ListWorkstations", + "file": "workstations_v1beta_generated_workstations_list_workstations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstations_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": "workstations_v1beta_generated_workstations_list_workstations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstations", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationsPager", + "shortName": "list_workstations" + }, + "description": "Sample for ListWorkstations", + "file": "workstations_v1beta_generated_workstations_list_workstations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstations_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": "workstations_v1beta_generated_workstations_list_workstations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.start_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.StartWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "StartWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.StartWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "start_workstation" + }, + "description": "Sample for StartWorkstation", + "file": "workstations_v1beta_generated_workstations_start_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_StartWorkstation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_start_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.start_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.StartWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "StartWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.StartWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "start_workstation" + }, + "description": "Sample for StartWorkstation", + "file": "workstations_v1beta_generated_workstations_start_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_StartWorkstation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_start_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.stop_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.StopWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "StopWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.StopWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "stop_workstation" + }, + "description": "Sample for StopWorkstation", + "file": "workstations_v1beta_generated_workstations_stop_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_StopWorkstation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_stop_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.stop_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.StopWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "StopWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.StopWorkstationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "stop_workstation" + }, + "description": "Sample for StopWorkstation", + "file": "workstations_v1beta_generated_workstations_stop_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_StopWorkstation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_stop_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_workstation_cluster" + }, + "description": "Sample for UpdateWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_update_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_update_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_workstation_cluster" + }, + "description": "Sample for UpdateWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_workstation_config" + }, + "description": "Sample for UpdateWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_update_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_update_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_workstation_config" + }, + "description": "Sample for UpdateWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_update_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_update_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationRequest" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1beta.types.Workstation" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_workstation" + }, + "description": "Sample for UpdateWorkstation", + "file": "workstations_v1beta_generated_workstations_update_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstation_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_update_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationRequest" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1beta.types.Workstation" + }, + { + "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, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_workstation" + }, + "description": "Sample for UpdateWorkstation", + "file": "workstations_v1beta_generated_workstations_update_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstation_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "workstations_v1beta_generated_workstations_update_workstation_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py new file mode 100644 index 000000000000..25d6d1cc1386 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_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 CreateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_create_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py new file mode 100644 index 000000000000..4277893c4542 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_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 CreateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py new file mode 100644 index 000000000000..8e08528d07eb --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_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 CreateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py new file mode 100644 index 000000000000..adb0fe31f47a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_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 CreateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_create_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py new file mode 100644 index 000000000000..d9241dd3b035 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_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 CreateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_create_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py new file mode 100644 index 000000000000..51686d435e86 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_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 CreateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_create_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py new file mode 100644 index 000000000000..bbff0682f847 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_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 DeleteWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_delete_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py new file mode 100644 index 000000000000..16ab313463d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_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 DeleteWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py new file mode 100644 index 000000000000..390eb9fc620e --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_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 DeleteWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py new file mode 100644 index 000000000000..292a8d5e3206 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_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 DeleteWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_delete_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py new file mode 100644 index 000000000000..12e436dded63 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_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 DeleteWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_delete_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py new file mode 100644 index 000000000000..10d26495a739 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_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 DeleteWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_delete_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py new file mode 100644 index 000000000000..73f954930a43 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_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 GenerateAccessToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GenerateAccessToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_generate_access_token(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = await client.generate_access_token(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GenerateAccessToken_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py new file mode 100644 index 000000000000..32d570bf51b4 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_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 GenerateAccessToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GenerateAccessToken_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_generate_access_token(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = client.generate_access_token(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GenerateAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py new file mode 100644 index 000000000000..6ba46df98486 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_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 GetWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_get_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py new file mode 100644 index 000000000000..8c9ce3be54d6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_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 GetWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py new file mode 100644 index 000000000000..cd3baaea4660 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_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 GetWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py new file mode 100644 index 000000000000..671253c19d41 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_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 GetWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_get_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_config(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py new file mode 100644 index 000000000000..1c83ac5b50b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_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 GetWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_get_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_config(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py new file mode 100644 index 000000000000..3e6624180a0b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_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 GetWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_get_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py new file mode 100644 index 000000000000..e177763630e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_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 ListUsableWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py new file mode 100644 index 000000000000..366e2c534144 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_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 ListUsableWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py new file mode 100644 index 000000000000..f3ec6f0e4786 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_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 ListUsableWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListUsableWorkstations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_usable_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListUsableWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py new file mode 100644 index 000000000000..afcb460801be --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_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 ListUsableWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListUsableWorkstations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_usable_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListUsableWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py new file mode 100644 index 000000000000..335db75c2249 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_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 ListWorkstationClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstationClusters_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstationClusters_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py new file mode 100644 index 000000000000..2b80a5c40ef7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_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 ListWorkstationClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstationClusters_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstationClusters_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py new file mode 100644 index 000000000000..0616e10bc7c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_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 ListWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py new file mode 100644 index 000000000000..2c6f221ef80c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_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 ListWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py new file mode 100644 index 000000000000..d62698ab6d95 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_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 ListWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py new file mode 100644 index 000000000000..c16a71301682 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_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 ListWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py new file mode 100644 index 000000000000..07ed7765cb84 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_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 StartWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_StartWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_start_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_StartWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py new file mode 100644 index 000000000000..682464e81f61 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_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 StartWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_StartWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_start_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_StartWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py new file mode 100644 index 000000000000..963d2cfbdc72 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_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 StopWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_StopWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_stop_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_StopWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py new file mode 100644 index 000000000000..0f3a6326f15a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_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 StopWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_StopWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_stop_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_StopWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py new file mode 100644 index 000000000000..3d2ecb5c9e15 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_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 UpdateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_update_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py new file mode 100644 index 000000000000..5f707487e718 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_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 UpdateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py new file mode 100644 index 000000000000..3cea9c289e5b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_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 UpdateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py new file mode 100644 index 000000000000..0f94cb324602 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_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 UpdateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_update_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py new file mode 100644 index 000000000000..95eb95f64b2c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_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 UpdateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_update_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py new file mode 100644 index 000000000000..74719a00dbc8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_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 UpdateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_update_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py b/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py new file mode 100644 index 000000000000..d5f36b76dcbd --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py @@ -0,0 +1,195 @@ +#! /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 workstationsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_workstation': ('parent', 'workstation_id', 'workstation', 'validate_only', ), + 'create_workstation_cluster': ('parent', 'workstation_cluster_id', 'workstation_cluster', 'validate_only', ), + 'create_workstation_config': ('parent', 'workstation_config_id', 'workstation_config', 'validate_only', ), + 'delete_workstation': ('name', 'validate_only', 'etag', ), + 'delete_workstation_cluster': ('name', 'validate_only', 'etag', 'force', ), + 'delete_workstation_config': ('name', 'validate_only', 'etag', 'force', ), + 'generate_access_token': ('workstation', 'expire_time', 'ttl', ), + 'get_workstation': ('name', ), + 'get_workstation_cluster': ('name', ), + 'get_workstation_config': ('name', ), + 'list_usable_workstation_configs': ('parent', 'page_size', 'page_token', ), + 'list_usable_workstations': ('parent', 'page_size', 'page_token', ), + 'list_workstation_clusters': ('parent', 'page_size', 'page_token', ), + 'list_workstation_configs': ('parent', 'page_size', 'page_token', ), + 'list_workstations': ('parent', 'page_size', 'page_token', ), + 'start_workstation': ('name', 'validate_only', 'etag', ), + 'stop_workstation': ('name', 'validate_only', 'etag', ), + 'update_workstation': ('workstation', 'update_mask', 'validate_only', 'allow_missing', ), + 'update_workstation_cluster': ('workstation_cluster', 'update_mask', 'validate_only', 'allow_missing', ), + 'update_workstation_config': ('workstation_config', 'update_mask', 'validate_only', 'allow_missing', ), + } + + 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=workstationsCallTransformer(), +): + """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 workstations 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-cloud-workstations/v1beta/setup.py b/owl-bot-staging/google-cloud-workstations/v1beta/setup.py new file mode 100644 index 000000000000..6106efcf5486 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations' + + +description = "Google Cloud Workstations API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/workstations/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", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations" + +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-cloud-workstations/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_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-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py new file mode 100644 index 000000000000..3f801a885d70 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py @@ -0,0 +1,17999 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.location import locations_pb2 +from google.cloud.workstations_v1beta.services.workstations import WorkstationsAsyncClient +from google.cloud.workstations_v1beta.services.workstations import WorkstationsClient +from google.cloud.workstations_v1beta.services.workstations import pagers +from google.cloud.workstations_v1beta.services.workstations import transports +from google.cloud.workstations_v1beta.types import workstations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +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 WorkstationsClient._get_default_mtls_endpoint(None) is None + assert WorkstationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert WorkstationsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WorkstationsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WorkstationsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + WorkstationsClient._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 WorkstationsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WorkstationsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WorkstationsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WorkstationsClient._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 WorkstationsClient._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 WorkstationsClient._get_client_cert_source(None, False) is None + assert WorkstationsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert WorkstationsClient._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 WorkstationsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert WorkstationsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WorkstationsClient._DEFAULT_UNIVERSE + default_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert WorkstationsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert WorkstationsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT + assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "always") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT + assert WorkstationsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT + assert WorkstationsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + WorkstationsClient._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 WorkstationsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert WorkstationsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert WorkstationsClient._get_universe_domain(None, None) == WorkstationsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + WorkstationsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WorkstationsClient, "grpc"), + (WorkstationsAsyncClient, "grpc_asyncio"), + (WorkstationsClient, "rest"), +]) +def test_workstations_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 == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workstations.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WorkstationsGrpcTransport, "grpc"), + (transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WorkstationsRestTransport, "rest"), +]) +def test_workstations_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", [ + (WorkstationsClient, "grpc"), + (WorkstationsAsyncClient, "grpc_asyncio"), + (WorkstationsClient, "rest"), +]) +def test_workstations_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 == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workstations.googleapis.com' + ) + + +def test_workstations_client_get_transport_class(): + transport = WorkstationsClient.get_transport_class() + available_transports = [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsRestTransport, + ] + assert transport in available_transports + + transport = WorkstationsClient.get_transport_class("grpc") + assert transport == transports.WorkstationsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) +def test_workstations_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(WorkstationsClient, '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(WorkstationsClient, '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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "true"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "false"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "true"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "false"), +]) +@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_workstations_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", [ + WorkstationsClient, WorkstationsAsyncClient +]) +@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) +def test_workstations_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", [ + WorkstationsClient, WorkstationsAsyncClient +]) +@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) +def test_workstations_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WorkstationsClient._DEFAULT_UNIVERSE + default_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WorkstationsClient._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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +def test_workstations_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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", None), +]) +def test_workstations_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_workstations_client_client_options_from_dict(): + with mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WorkstationsClient( + 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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_workstations_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( + "workstations.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="workstations.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationClusterRequest, + dict, +]) +def test_get_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + ) + response = client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +def test_get_workstation_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.GetWorkstationClusterRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_workstation_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationClusterRequest( + name='name_value', + ) + +def test_get_workstation_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation_cluster] = mock_rpc + request = {} + client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods + + # 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_workstation_cluster] = mock_rpc + + request = {} + await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + )) + response = await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +@pytest.mark.asyncio +async def test_get_workstation_cluster_async_from_dict(): + await test_get_workstation_cluster_async(request_type=dict) + +def test_get_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = workstations.WorkstationCluster() + client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) + await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation_cluster( + 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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation_cluster( + 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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationClustersRequest, + dict, +]) +def test_list_workstation_clusters(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_clusters_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListWorkstationClustersRequest( + 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_workstation_clusters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workstation_clusters(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationClustersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_workstation_clusters_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_clusters] = mock_rpc + request = {} + client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstation_clusters(request) + + # Establish that a new wrapper 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_workstation_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_clusters in client._client._transport._wrapped_methods + + # 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_workstation_clusters] = mock_rpc + + request = {} + await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workstation_clusters(request) + + # Establish that a new wrapper 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_workstation_clusters_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationClustersRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async_from_dict(): + await test_list_workstation_clusters_async(request_type=dict) + +def test_list_workstation_clusters_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = workstations.ListWorkstationClustersResponse() + client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_clusters_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) + await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_clusters_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstation_clusters( + 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_workstation_clusters_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstation_clusters_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstation_clusters( + 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_workstation_clusters_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + + +def test_list_workstation_clusters_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstation_clusters(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, workstations.WorkstationCluster) + for i in results) +def test_list_workstation_clusters_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstation_clusters(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_workstation_clusters_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstation_clusters(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, workstations.WorkstationCluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + 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_workstation_clusters(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", [ + workstations.CreateWorkstationClusterRequest, + dict, +]) +def test_create_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.CreateWorkstationClusterRequest( + parent='parent_value', + workstation_cluster_id='workstation_cluster_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_workstation_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationClusterRequest( + parent='parent_value', + workstation_cluster_id='workstation_cluster_id_value', + ) + +def test_create_workstation_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + request = {} + client.create_workstation_cluster(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.create_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods + + # 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_workstation_cluster] = mock_rpc + + request = {} + await client.create_workstation_cluster(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.create_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationClusterRequest() + 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_create_workstation_cluster_async_from_dict(): + await test_create_workstation_cluster_async(request_type=dict) + +def test_create_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_workstation_cluster( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_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].workstation_cluster + mock_val = workstations.WorkstationCluster(name='name_value') + assert arg == mock_val + arg = args[0].workstation_cluster_id + mock_val = 'workstation_cluster_id_value' + assert arg == mock_val + + +def test_create_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_workstation_cluster( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_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].workstation_cluster + mock_val = workstations.WorkstationCluster(name='name_value') + assert arg == mock_val + arg = args[0].workstation_cluster_id + mock_val = 'workstation_cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationClusterRequest, + dict, +]) +def test_update_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.UpdateWorkstationClusterRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_workstation_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationClusterRequest( + ) + +def test_update_workstation_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + request = {} + client.update_workstation_cluster(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.update_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods + + # 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_workstation_cluster] = mock_rpc + + request = {} + await client.update_workstation_cluster(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.update_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationClusterRequest() + 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_update_workstation_cluster_async_from_dict(): + await test_update_workstation_cluster_async(request_type=dict) + +def test_update_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationClusterRequest() + + request.workstation_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationClusterRequest() + + request.workstation_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_workstation_cluster( + workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster + mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_workstation_cluster( + workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster + mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationClusterRequest, + dict, +]) +def test_delete_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.DeleteWorkstationClusterRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_workstation_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationClusterRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_workstation_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + request = {} + client.delete_workstation_cluster(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.delete_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods + + # 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_workstation_cluster] = mock_rpc + + request = {} + await client.delete_workstation_cluster(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.delete_workstation_cluster(request) + + # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationClusterRequest() + 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_delete_workstation_cluster_async_from_dict(): + await test_delete_workstation_cluster_async(request_type=dict) + +def test_delete_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_workstation_cluster( + 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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_workstation_cluster( + 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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationConfigRequest, + dict, +]) +def test_get_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + replica_zones=['replica_zones_value'], + degraded=True, + enable_audit_agent=True, + ) + response = client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.replica_zones == ['replica_zones_value'] + assert response.degraded is True + assert response.enable_audit_agent is True + + +def test_get_workstation_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.GetWorkstationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_workstation_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationConfigRequest( + name='name_value', + ) + +def test_get_workstation_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation_config] = mock_rpc + request = {} + client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_config in client._client._transport._wrapped_methods + + # 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_workstation_config] = mock_rpc + + request = {} + await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + replica_zones=['replica_zones_value'], + degraded=True, + enable_audit_agent=True, + )) + response = await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.replica_zones == ['replica_zones_value'] + assert response.degraded is True + assert response.enable_audit_agent is True + + +@pytest.mark.asyncio +async def test_get_workstation_config_async_from_dict(): + await test_get_workstation_config_async(request_type=dict) + +def test_get_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = workstations.WorkstationConfig() + client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) + await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation_config( + 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_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation_config( + 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_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationConfigsRequest, + dict, +]) +def test_list_workstation_configs(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListWorkstationConfigsRequest( + 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_workstation_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workstation_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_workstation_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_configs] = mock_rpc + request = {} + client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstation_configs(request) + + # Establish that a new wrapper 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_workstation_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_configs in client._client._transport._wrapped_methods + + # 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_workstation_configs] = mock_rpc + + request = {} + await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workstation_configs(request) + + # Establish that a new wrapper 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_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationConfigsRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstation_configs_async_from_dict(): + await test_list_workstation_configs_async(request_type=dict) + +def test_list_workstation_configs_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListWorkstationConfigsResponse() + client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_configs_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) + await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_configs_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstation_configs( + 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_workstation_configs_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstation_configs_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstation_configs( + 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_workstation_configs_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_workstation_configs_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstation_configs(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, workstations.WorkstationConfig) + for i in results) +def test_list_workstation_configs_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstation_configs(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_workstation_configs_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstation_configs(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, workstations.WorkstationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstation_configs_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + 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_workstation_configs(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", [ + workstations.ListUsableWorkstationConfigsRequest, + dict, +]) +def test_list_usable_workstation_configs(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListUsableWorkstationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstation_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListUsableWorkstationConfigsRequest( + 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_usable_workstation_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_usable_workstation_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_usable_workstation_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_usable_workstation_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_usable_workstation_configs] = mock_rpc + request = {} + client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_usable_workstation_configs(request) + + # Establish that a new wrapper 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_usable_workstation_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_usable_workstation_configs in client._client._transport._wrapped_methods + + # 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_usable_workstation_configs] = mock_rpc + + request = {} + await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_usable_workstation_configs(request) + + # Establish that a new wrapper 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_usable_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationConfigsRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListUsableWorkstationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async_from_dict(): + await test_list_usable_workstation_configs_async(request_type=dict) + +def test_list_usable_workstation_configs_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_usable_workstation_configs_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) + await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_usable_workstation_configs_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_usable_workstation_configs( + 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_usable_workstation_configs_flattened_error(): + client = WorkstationsClient( + credentials=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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_usable_workstation_configs( + 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_usable_workstation_configs_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstation_configs_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_usable_workstation_configs(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, workstations.WorkstationConfig) + for i in results) +def test_list_usable_workstation_configs_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_usable_workstation_configs(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_usable_workstation_configs_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_usable_workstation_configs(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, workstations.WorkstationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + 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_usable_workstation_configs(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", [ + workstations.CreateWorkstationConfigRequest, + dict, +]) +def test_create_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.CreateWorkstationConfigRequest( + parent='parent_value', + workstation_config_id='workstation_config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_workstation_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationConfigRequest( + parent='parent_value', + workstation_config_id='workstation_config_id_value', + ) + +def test_create_workstation_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + request = {} + client.create_workstation_config(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.create_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_config in client._client._transport._wrapped_methods + + # 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_workstation_config] = mock_rpc + + request = {} + await client.create_workstation_config(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.create_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationConfigRequest() + 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_create_workstation_config_async_from_dict(): + await test_create_workstation_config_async(request_type=dict) + +def test_create_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_workstation_config( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_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].workstation_config + mock_val = workstations.WorkstationConfig(name='name_value') + assert arg == mock_val + arg = args[0].workstation_config_id + mock_val = 'workstation_config_id_value' + assert arg == mock_val + + +def test_create_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_workstation_config( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_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].workstation_config + mock_val = workstations.WorkstationConfig(name='name_value') + assert arg == mock_val + arg = args[0].workstation_config_id + mock_val = 'workstation_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationConfigRequest, + dict, +]) +def test_update_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.UpdateWorkstationConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_workstation_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationConfigRequest( + ) + +def test_update_workstation_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + request = {} + client.update_workstation_config(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.update_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_config in client._client._transport._wrapped_methods + + # 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_workstation_config] = mock_rpc + + request = {} + await client.update_workstation_config(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.update_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationConfigRequest() + 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_update_workstation_config_async_from_dict(): + await test_update_workstation_config_async(request_type=dict) + +def test_update_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationConfigRequest() + + request.workstation_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationConfigRequest() + + request.workstation_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_config.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_workstation_config( + workstation_config=workstations.WorkstationConfig(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].workstation_config + mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_workstation_config( + workstation_config=workstations.WorkstationConfig(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].workstation_config + mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationConfigRequest, + dict, +]) +def test_delete_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.DeleteWorkstationConfigRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_workstation_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationConfigRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_workstation_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + request = {} + client.delete_workstation_config(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.delete_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation_config in client._client._transport._wrapped_methods + + # 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_workstation_config] = mock_rpc + + request = {} + await client.delete_workstation_config(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.delete_workstation_config(request) + + # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationConfigRequest() + 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_delete_workstation_config_async_from_dict(): + await test_delete_workstation_config_async(request_type=dict) + +def test_delete_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_workstation_config( + 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_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_workstation_config( + 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_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationRequest, + dict, +]) +def test_get_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + ) + response = client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +def test_get_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.GetWorkstationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationRequest( + name='name_value', + ) + +def test_get_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation] = mock_rpc + request = {} + client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation(request) + + # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation in client._client._transport._wrapped_methods + + # 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_workstation] = mock_rpc + + request = {} + await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_workstation(request) + + # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + )) + response = await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.GetWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +@pytest.mark.asyncio +async def test_get_workstation_async_from_dict(): + await test_get_workstation_async(request_type=dict) + +def test_get_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = workstations.Workstation() + client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) + await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation( + 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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation( + 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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationsRequest, + dict, +]) +def test_list_workstations(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListWorkstationsRequest( + 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_workstations), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workstations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_workstations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstations] = mock_rpc + request = {} + client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstations(request) + + # Establish that a new wrapper 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_workstations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstations in client._client._transport._wrapped_methods + + # 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_workstations] = mock_rpc + + request = {} + await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workstations(request) + + # Establish that a new wrapper 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_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationsRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListWorkstationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstations_async_from_dict(): + await test_list_workstations_async(request_type=dict) + +def test_list_workstations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = workstations.ListWorkstationsResponse() + client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) + await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstations_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstations( + 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_workstations_flattened_error(): + client = WorkstationsClient( + credentials=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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstations_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstations( + 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_workstations_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_workstations_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstations(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, workstations.Workstation) + for i in results) +def test_list_workstations_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstations(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_workstations_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstations(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, workstations.Workstation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstations_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + 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_workstations(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", [ + workstations.ListUsableWorkstationsRequest, + dict, +]) +def test_list_usable_workstations(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.ListUsableWorkstationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.ListUsableWorkstationsRequest( + 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_usable_workstations), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_usable_workstations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_usable_workstations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_usable_workstations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_usable_workstations] = mock_rpc + request = {} + client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_usable_workstations(request) + + # Establish that a new wrapper 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_usable_workstations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_usable_workstations in client._client._transport._wrapped_methods + + # 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_usable_workstations] = mock_rpc + + request = {} + await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_usable_workstations(request) + + # Establish that a new wrapper 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_usable_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationsRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.ListUsableWorkstationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_usable_workstations_async_from_dict(): + await test_list_usable_workstations_async(request_type=dict) + +def test_list_usable_workstations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationsResponse() + client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_usable_workstations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) + await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_usable_workstations_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_usable_workstations( + 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_usable_workstations_flattened_error(): + client = WorkstationsClient( + credentials=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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_usable_workstations_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_usable_workstations( + 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_usable_workstations_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstations_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_usable_workstations(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, workstations.Workstation) + for i in results) +def test_list_usable_workstations_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_usable_workstations(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_usable_workstations_async_pager(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_usable_workstations(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, workstations.Workstation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_usable_workstations_async_pages(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + 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_usable_workstations(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", [ + workstations.CreateWorkstationRequest, + dict, +]) +def test_create_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.CreateWorkstationRequest( + parent='parent_value', + workstation_id='workstation_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationRequest( + parent='parent_value', + workstation_id='workstation_id_value', + ) + +def test_create_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + request = {} + client.create_workstation(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.create_workstation(request) + + # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation in client._client._transport._wrapped_methods + + # 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_workstation] = mock_rpc + + request = {} + await client.create_workstation(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.create_workstation(request) + + # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.CreateWorkstationRequest() + 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_create_workstation_async_from_dict(): + await test_create_workstation_async(request_type=dict) + +def test_create_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_workstation( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_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].workstation + mock_val = workstations.Workstation(name='name_value') + assert arg == mock_val + arg = args[0].workstation_id + mock_val = 'workstation_id_value' + assert arg == mock_val + + +def test_create_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_workstation( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_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].workstation + mock_val = workstations.Workstation(name='name_value') + assert arg == mock_val + arg = args[0].workstation_id + mock_val = 'workstation_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationRequest, + dict, +]) +def test_update_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.UpdateWorkstationRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationRequest( + ) + +def test_update_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + request = {} + client.update_workstation(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.update_workstation(request) + + # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation in client._client._transport._wrapped_methods + + # 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_workstation] = mock_rpc + + request = {} + await client.update_workstation(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.update_workstation(request) + + # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.UpdateWorkstationRequest() + 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_update_workstation_async_from_dict(): + await test_update_workstation_async(request_type=dict) + +def test_update_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationRequest() + + request.workstation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationRequest() + + request.workstation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_workstation( + workstation=workstations.Workstation(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].workstation + mock_val = workstations.Workstation(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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_workstation( + workstation=workstations.Workstation(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].workstation + mock_val = workstations.Workstation(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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationRequest, + dict, +]) +def test_delete_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.DeleteWorkstationRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + request = {} + client.delete_workstation(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.delete_workstation(request) + + # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_workstation in client._client._transport._wrapped_methods + + # 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_workstation] = mock_rpc + + request = {} + await client.delete_workstation(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.delete_workstation(request) + + # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.DeleteWorkstationRequest() + 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_delete_workstation_async_from_dict(): + await test_delete_workstation_async(request_type=dict) + +def test_delete_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_workstation( + 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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_workstation( + 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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StartWorkstationRequest, + dict, +]) +def test_start_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.StartWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_start_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.StartWorkstationRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.start_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StartWorkstationRequest( + name='name_value', + etag='etag_value', + ) + +def test_start_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_workstation] = mock_rpc + request = {} + client.start_workstation(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.start_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.start_workstation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.start_workstation] = mock_rpc + + request = {} + await client.start_workstation(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.start_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_start_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StartWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.StartWorkstationRequest() + 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_start_workstation_async_from_dict(): + await test_start_workstation_async(request_type=dict) + +def test_start_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StartWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StartWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_workstation( + 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_start_workstation_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_start_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_workstation( + 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_start_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StopWorkstationRequest, + dict, +]) +def test_stop_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.StopWorkstationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_stop_workstation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.StopWorkstationRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.stop_workstation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StopWorkstationRequest( + name='name_value', + etag='etag_value', + ) + +def test_stop_workstation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_workstation] = mock_rpc + request = {} + client.stop_workstation(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.stop_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.stop_workstation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.stop_workstation] = mock_rpc + + request = {} + await client.stop_workstation(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.stop_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StopWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.StopWorkstationRequest() + 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_stop_workstation_async_from_dict(): + await test_stop_workstation_async(request_type=dict) + +def test_stop_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StopWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StopWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_workstation( + 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_stop_workstation_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_stop_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_workstation( + 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_stop_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GenerateAccessTokenRequest, + dict, +]) +def test_generate_access_token(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + ) + response = client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = workstations.GenerateAccessTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +def test_generate_access_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = workstations.GenerateAccessTokenRequest( + workstation='workstation_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_access_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GenerateAccessTokenRequest( + workstation='workstation_value', + ) + +def test_generate_access_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_access_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc + request = {} + client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_access_token in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.generate_access_token] = mock_rpc + + request = {} + await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=workstations.GenerateAccessTokenRequest): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + )) + response = await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = workstations.GenerateAccessTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.asyncio +async def test_generate_access_token_async_from_dict(): + await test_generate_access_token_async(request_type=dict) + +def test_generate_access_token_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GenerateAccessTokenRequest() + + request.workstation = 'workstation_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = workstations.GenerateAccessTokenResponse() + client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation=workstation_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_access_token_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GenerateAccessTokenRequest() + + request.workstation = 'workstation_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) + await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation=workstation_value', + ) in kw['metadata'] + + +def test_generate_access_token_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_access_token( + workstation='workstation_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].workstation + mock_val = 'workstation_value' + assert arg == mock_val + + +def test_generate_access_token_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + +@pytest.mark.asyncio +async def test_generate_access_token_flattened_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_access_token( + workstation='workstation_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].workstation + mock_val = 'workstation_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_generate_access_token_flattened_error_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + + +def test_get_workstation_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation_cluster] = mock_rpc + + request = {} + client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation_cluster(request) + + # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.GetWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation_cluster._get_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_workstation_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.WorkstationCluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.WorkstationCluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_get_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + + +def test_list_workstation_clusters_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_clusters] = mock_rpc + + request = {} + client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstation_clusters(request) + + # Establish 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_workstation_clusters_rest_required_fields(request_type=workstations.ListWorkstationClustersRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_clusters._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_workstation_clusters._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListWorkstationClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_workstation_clusters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstation_clusters_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstation_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workstation_clusters_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/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 = workstations.ListWorkstationClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_workstation_clusters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) + + +def test_list_workstation_clusters_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + + +def test_list_workstation_clusters_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationClustersResponse.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/locations/sample2'} + + pager = client.list_workstation_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationCluster) + for i in results) + + pages = list(client.list_workstation_clusters(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_workstation_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + + request = {} + client.create_workstation_cluster(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.create_workstation_cluster(request) + + # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.CreateWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_cluster_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 "workstationClusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationClusterId" in jsonified_request + assert jsonified_request["workstationClusterId"] == request_init["workstation_cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationClusterId"] = 'workstation_cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only", "workstation_cluster_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 "workstationClusterId" in jsonified_request + assert jsonified_request["workstationClusterId"] == 'workstation_cluster_id_value' + + client = WorkstationsClient( + 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 + + response = client.create_workstation_cluster(request) + + expected_params = [ + ( + "workstationClusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationClusterId", )) & set(("parent", "workstationClusterId", "workstationCluster", ))) + + +def test_create_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) + + +def test_create_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + +def test_update_workstation_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + + request = {} + client.update_workstation_cluster(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.update_workstation_cluster(request) + + # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.UpdateWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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': "patch", + '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 + + response = client.update_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationCluster", "updateMask", ))) + + +def test_update_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation_cluster=workstations.WorkstationCluster(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_update_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_workstation_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_cluster] = mock_rpc + + request = {} + client.delete_workstation_cluster(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.delete_workstation_cluster(request) + + # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.DeleteWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation_cluster._get_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_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "validate_only", )) + jsonified_request.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 = WorkstationsClient( + 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': "delete", + '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 + + response = client.delete_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) + + +def test_delete_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + + +def test_get_workstation_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation_config] = mock_rpc + + request = {} + client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation_config(request) + + # Establish 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_workstation_config_rest_required_fields(request_type=workstations.GetWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation_config._get_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_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.WorkstationConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # 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 = workstations.WorkstationConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + + +def test_list_workstation_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_configs] = mock_rpc + + request = {} + client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstation_configs(request) + + # Establish 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_workstation_configs_rest_required_fields(request_type=workstations.ListWorkstationConfigsRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_configs._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_workstation_configs._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_workstation_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstation_configs_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstation_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workstation_configs_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # 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 = workstations.ListWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_workstation_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) + + +def test_list_workstation_configs_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_workstation_configs_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationConfigsResponse.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/locations/sample2/workstationClusters/sample3'} + + pager = client.list_workstation_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) + + pages = list(client.list_workstation_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_usable_workstation_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_usable_workstation_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_usable_workstation_configs] = mock_rpc + + request = {} + client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_usable_workstation_configs(request) + + # Establish 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_usable_workstation_configs_rest_required_fields(request_type=workstations.ListUsableWorkstationConfigsRequest): + transport_class = transports.WorkstationsRestTransport + + 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_usable_workstation_configs._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_usable_workstation_configs._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_usable_workstation_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_usable_workstation_configs_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_usable_workstation_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_usable_workstation_configs_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # 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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_usable_workstation_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable" % client.transport._host, args[1]) + + +def test_list_usable_workstation_configs_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstation_configs_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListUsableWorkstationConfigsResponse.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/locations/sample2/workstationClusters/sample3'} + + pager = client.list_usable_workstation_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) + + pages = list(client.list_usable_workstation_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_workstation_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + + request = {} + client.create_workstation_config(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.create_workstation_config(request) + + # Establish 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_workstation_config_rest_required_fields(request_type=workstations.CreateWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_config_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 "workstationConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationConfigId" in jsonified_request + assert jsonified_request["workstationConfigId"] == request_init["workstation_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationConfigId"] = 'workstation_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only", "workstation_config_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 "workstationConfigId" in jsonified_request + assert jsonified_request["workstationConfigId"] == 'workstation_config_id_value' + + client = WorkstationsClient( + 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 + + response = client.create_workstation_config(request) + + expected_params = [ + ( + "workstationConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationConfigId", )) & set(("parent", "workstationConfigId", "workstationConfig", ))) + + +def test_create_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) + + +def test_create_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + +def test_update_workstation_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + + request = {} + client.update_workstation_config(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.update_workstation_config(request) + + # Establish 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_workstation_config_rest_required_fields(request_type=workstations.UpdateWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_config._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_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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': "patch", + '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 + + response = client.update_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationConfig", "updateMask", ))) + + +def test_update_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation_config=workstations.WorkstationConfig(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_workstation_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation_config] = mock_rpc + + request = {} + client.delete_workstation_config(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.delete_workstation_config(request) + + # Establish 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_workstation_config_rest_required_fields(request_type=workstations.DeleteWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation_config._get_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_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "validate_only", )) + jsonified_request.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 = WorkstationsClient( + 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': "delete", + '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 + + response = client.delete_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) + + +def test_delete_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # 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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + + +def test_get_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_workstation] = mock_rpc + + request = {} + client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_workstation(request) + + # Establish 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_workstation_rest_required_fields(request_type=workstations.GetWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation._get_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_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.Workstation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # 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 = workstations.Workstation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_get_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + + +def test_list_workstations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstations] = mock_rpc + + request = {} + client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workstations(request) + + # Establish 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_workstations_rest_required_fields(request_type=workstations.ListWorkstationsRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstations._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_workstations._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_workstations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstations_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workstations_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # 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 = workstations.ListWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_workstations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) + + +def test_list_workstations_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_workstations_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationsResponse.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/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + pager = client.list_workstations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) + + pages = list(client.list_workstations(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_usable_workstations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_usable_workstations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_usable_workstations] = mock_rpc + + request = {} + client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_usable_workstations(request) + + # Establish 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_usable_workstations_rest_required_fields(request_type=workstations.ListUsableWorkstationsRequest): + transport_class = transports.WorkstationsRestTransport + + 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_usable_workstations._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_usable_workstations._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = workstations.ListUsableWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_usable_workstations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_usable_workstations_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_usable_workstations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_usable_workstations_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # 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 = workstations.ListUsableWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_usable_workstations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable" % client.transport._host, args[1]) + + +def test_list_usable_workstations_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstations_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListUsableWorkstationsResponse.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/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + pager = client.list_usable_workstations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) + + pages = list(client.list_usable_workstations(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + + request = {} + client.create_workstation(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.create_workstation(request) + + # Establish 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_workstation_rest_required_fields(request_type=workstations.CreateWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_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 "workstationId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationId" in jsonified_request + assert jsonified_request["workstationId"] == request_init["workstation_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationId"] = 'workstation_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only", "workstation_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 "workstationId" in jsonified_request + assert jsonified_request["workstationId"] == 'workstation_id_value' + + client = WorkstationsClient( + 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 + + response = client.create_workstation(request) + + expected_params = [ + ( + "workstationId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationId", )) & set(("parent", "workstationId", "workstation", ))) + + +def test_create_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) + + +def test_create_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + +def test_update_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + + request = {} + client.update_workstation(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.update_workstation(request) + + # Establish 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_workstation_rest_required_fields(request_type=workstations.UpdateWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation._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_workstation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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': "patch", + '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 + + response = client.update_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstation", "updateMask", ))) + + +def test_update_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation=workstations.Workstation(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_update_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_workstation] = mock_rpc + + request = {} + client.delete_workstation(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.delete_workstation(request) + + # Establish 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_workstation_rest_required_fields(request_type=workstations.DeleteWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_workstation._get_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_workstation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "validate_only", )) + jsonified_request.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 = WorkstationsClient( + 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': "delete", + '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 + + response = client.delete_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) + + +def test_delete_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # 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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + + +def test_start_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.start_workstation] = mock_rpc + + request = {} + client.start_workstation(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.start_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_start_workstation_rest_required_fields(request_type=workstations.StartWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).start_workstation._get_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()).start_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + 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 + + response = client.start_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_start_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.start_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_start_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # 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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.start_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start" % client.transport._host, args[1]) + + +def test_start_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + + +def test_stop_workstation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_workstation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.stop_workstation] = mock_rpc + + request = {} + client.stop_workstation(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.stop_workstation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_stop_workstation_rest_required_fields(request_type=workstations.StopWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).stop_workstation._get_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()).stop_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.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 = WorkstationsClient( + 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 + + response = client.stop_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_stop_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.stop_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_stop_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # 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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.stop_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop" % client.transport._host, args[1]) + + +def test_stop_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + + +def test_generate_access_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_access_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc + + request = {} + client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_access_token_rest_required_fields(request_type=workstations.GenerateAccessTokenRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["workstation"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["workstation"] = 'workstation_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "workstation" in jsonified_request + assert jsonified_request["workstation"] == 'workstation_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = workstations.GenerateAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.generate_access_token(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_access_token_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_access_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("workstation", ))) + + +def test_generate_access_token_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + workstation='workstation_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = workstations.GenerateAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.generate_access_token(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken" % client.transport._host, args[1]) + + +def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WorkstationsClient( + 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 = WorkstationsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WorkstationsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WorkstationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + transports.WorkstationsRestTransport, +]) +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 = WorkstationsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = WorkstationsClient( + 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_workstation_cluster_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = workstations.WorkstationCluster() + client.get_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_clusters_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = workstations.ListWorkstationClustersResponse() + client.list_workstation_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationClustersRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = workstations.WorkstationConfig() + client.get_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_configs_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListWorkstationConfigsResponse() + client.list_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This 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_usable_workstation_configs_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + client.list_usable_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = workstations.Workstation() + client.get_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstations_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = workstations.ListWorkstationsResponse() + client.list_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationsRequest() + + assert args[0] == request_msg + + +# This 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_usable_workstations_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationsResponse() + client.list_usable_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationsRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.start_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StartWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_workstation_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.stop_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StopWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_access_token_empty_call_grpc(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = workstations.GenerateAccessTokenResponse() + client.generate_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GenerateAccessTokenRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = WorkstationsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = WorkstationsAsyncClient( + 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_workstation_cluster_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + )) + await client.get_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_clusters_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_workstation_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__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.create_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__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.update_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__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.delete_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + replica_zones=['replica_zones_value'], + degraded=True, + enable_audit_agent=True, + )) + await client.get_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_configs_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_usable_workstation_configs_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_usable_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__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.create_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__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.update_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__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.delete_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + )) + await client.get_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstations_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_usable_workstations_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_usable_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__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.create_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__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.update_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__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.delete_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_start_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StartWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_stop_workstation_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StopWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_access_token_empty_call_grpc_asyncio(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + )) + await client.generate_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GenerateAccessTokenRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = WorkstationsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_workstation_cluster_rest_bad_request(request_type=workstations.GetWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 + client.get_workstation_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationClusterRequest, + dict, +]) +def test_get_workstation_cluster_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=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 = workstations.WorkstationCluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationClusterRequest.pb(workstations.GetWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.WorkstationCluster.to_json(workstations.WorkstationCluster()) + req.return_value.content = return_value + + request = workstations.GetWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.WorkstationCluster() + + client.get_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstation_clusters_rest_bad_request(request_type=workstations.ListWorkstationClustersRequest): + client = WorkstationsClient( + 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 + client.list_workstation_clusters(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationClustersRequest, + dict, +]) +def test_list_workstation_clusters_rest_call_success(request_type): + client = WorkstationsClient( + 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 = workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListWorkstationClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_workstation_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstation_clusters_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_clusters") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationClustersRequest.pb(workstations.ListWorkstationClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListWorkstationClustersResponse.to_json(workstations.ListWorkstationClustersResponse()) + req.return_value.content = return_value + + request = workstations.ListWorkstationClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationClustersResponse() + + client.list_workstation_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_cluster_rest_bad_request(request_type=workstations.CreateWorkstationClusterRequest): + client = WorkstationsClient( + 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 + client.create_workstation_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationClusterRequest, + dict, +]) +def test_create_workstation_cluster_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = workstations.CreateWorkstationClusterRequest.meta.fields["workstation_cluster"] + + 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["workstation_cluster"].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["workstation_cluster"][field])): + del request_init["workstation_cluster"][field][i][subfield] + else: + del request_init["workstation_cluster"][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 = 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 + response = client.create_workstation_cluster(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_create_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationClusterRequest.pb(workstations.CreateWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.CreateWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_cluster_rest_bad_request(request_type=workstations.UpdateWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/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 + client.update_workstation_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationClusterRequest, + dict, +]) +def test_update_workstation_cluster_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = workstations.UpdateWorkstationClusterRequest.meta.fields["workstation_cluster"] + + 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["workstation_cluster"].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["workstation_cluster"][field])): + del request_init["workstation_cluster"][field][i][subfield] + else: + del request_init["workstation_cluster"][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 = 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 + response = client.update_workstation_cluster(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_update_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationClusterRequest.pb(workstations.UpdateWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.UpdateWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_cluster_rest_bad_request(request_type=workstations.DeleteWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 + client.delete_workstation_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationClusterRequest, + dict, +]) +def test_delete_workstation_cluster_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = 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 + response = client.delete_workstation_cluster(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_delete_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationClusterRequest.pb(workstations.DeleteWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.DeleteWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_config_rest_bad_request(request_type=workstations.GetWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_workstation_config(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationConfigRequest, + dict, +]) +def test_get_workstation_config_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + replica_zones=['replica_zones_value'], + degraded=True, + enable_audit_agent=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 = workstations.WorkstationConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_workstation_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.replica_zones == ['replica_zones_value'] + assert response.degraded is True + assert response.enable_audit_agent is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationConfigRequest.pb(workstations.GetWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.WorkstationConfig.to_json(workstations.WorkstationConfig()) + req.return_value.content = return_value + + request = workstations.GetWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.WorkstationConfig() + + client.get_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstation_configs_rest_bad_request(request_type=workstations.ListWorkstationConfigsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 + client.list_workstation_configs(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationConfigsRequest, + dict, +]) +def test_list_workstation_configs_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_workstation_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstation_configs_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_configs") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationConfigsRequest.pb(workstations.ListWorkstationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListWorkstationConfigsResponse.to_json(workstations.ListWorkstationConfigsResponse()) + req.return_value.content = return_value + + request = workstations.ListWorkstationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationConfigsResponse() + + client.list_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_usable_workstation_configs_rest_bad_request(request_type=workstations.ListUsableWorkstationConfigsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 + client.list_usable_workstation_configs(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListUsableWorkstationConfigsRequest, + dict, +]) +def test_list_usable_workstation_configs_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_usable_workstation_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_usable_workstation_configs_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstation_configs") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstation_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListUsableWorkstationConfigsRequest.pb(workstations.ListUsableWorkstationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListUsableWorkstationConfigsResponse.to_json(workstations.ListUsableWorkstationConfigsResponse()) + req.return_value.content = return_value + + request = workstations.ListUsableWorkstationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListUsableWorkstationConfigsResponse() + + client.list_usable_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_config_rest_bad_request(request_type=workstations.CreateWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 + client.create_workstation_config(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationConfigRequest, + dict, +]) +def test_create_workstation_config_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'service_account_scopes': ['service_account_scopes_value1', 'service_account_scopes_value2'], 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'ephemeral_directories': [{'gce_pd': {'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'source_image': 'source_image_value', 'read_only': True}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'replica_zones': ['replica_zones_value1', 'replica_zones_value2'], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': 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 = workstations.CreateWorkstationConfigRequest.meta.fields["workstation_config"] + + 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["workstation_config"].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["workstation_config"][field])): + del request_init["workstation_config"][field][i][subfield] + else: + del request_init["workstation_config"][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 = 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 + response = client.create_workstation_config(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_create_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationConfigRequest.pb(workstations.CreateWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.CreateWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_config_rest_bad_request(request_type=workstations.UpdateWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_workstation_config(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationConfigRequest, + dict, +]) +def test_update_workstation_config_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'service_account_scopes': ['service_account_scopes_value1', 'service_account_scopes_value2'], 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'ephemeral_directories': [{'gce_pd': {'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'source_image': 'source_image_value', 'read_only': True}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'replica_zones': ['replica_zones_value1', 'replica_zones_value2'], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': 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 = workstations.UpdateWorkstationConfigRequest.meta.fields["workstation_config"] + + 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["workstation_config"].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["workstation_config"][field])): + del request_init["workstation_config"][field][i][subfield] + else: + del request_init["workstation_config"][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 = 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 + response = client.update_workstation_config(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_update_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationConfigRequest.pb(workstations.UpdateWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.UpdateWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_config_rest_bad_request(request_type=workstations.DeleteWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_workstation_config(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationConfigRequest, + dict, +]) +def test_delete_workstation_config_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # 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 + response = client.delete_workstation_config(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_delete_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationConfigRequest.pb(workstations.DeleteWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.DeleteWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_rest_bad_request(request_type=workstations.GetWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationRequest, + dict, +]) +def test_get_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_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 = workstations.Workstation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_workstation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationRequest.pb(workstations.GetWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.Workstation.to_json(workstations.Workstation()) + req.return_value.content = return_value + + request = workstations.GetWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.Workstation() + + client.get_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstations_rest_bad_request(request_type=workstations.ListWorkstationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_workstations(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationsRequest, + dict, +]) +def test_list_workstations_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_workstations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstations_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstations") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationsRequest.pb(workstations.ListWorkstationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListWorkstationsResponse.to_json(workstations.ListWorkstationsResponse()) + req.return_value.content = return_value + + request = workstations.ListWorkstationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationsResponse() + + client.list_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_usable_workstations_rest_bad_request(request_type=workstations.ListUsableWorkstationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_usable_workstations(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListUsableWorkstationsRequest, + dict, +]) +def test_list_usable_workstations_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_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 = workstations.ListUsableWorkstationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_usable_workstations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_usable_workstations_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstations") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListUsableWorkstationsRequest.pb(workstations.ListUsableWorkstationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.ListUsableWorkstationsResponse.to_json(workstations.ListUsableWorkstationsResponse()) + req.return_value.content = return_value + + request = workstations.ListUsableWorkstationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListUsableWorkstationsResponse() + + client.list_usable_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_rest_bad_request(request_type=workstations.CreateWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationRequest, + dict, +]) +def test_create_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'start_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} + # 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 = workstations.CreateWorkstationRequest.meta.fields["workstation"] + + 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["workstation"].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["workstation"][field])): + del request_init["workstation"][field][i][subfield] + else: + del request_init["workstation"][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 = 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 + response = client.create_workstation(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_create_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationRequest.pb(workstations.CreateWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.CreateWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_rest_bad_request(request_type=workstations.UpdateWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationRequest, + dict, +]) +def test_update_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'start_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} + # 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 = workstations.UpdateWorkstationRequest.meta.fields["workstation"] + + 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["workstation"].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["workstation"][field])): + del request_init["workstation"][field][i][subfield] + else: + del request_init["workstation"][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 = 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 + response = client.update_workstation(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_update_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationRequest.pb(workstations.UpdateWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.UpdateWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_rest_bad_request(request_type=workstations.DeleteWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationRequest, + dict, +]) +def test_delete_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and 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 + response = client.delete_workstation(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_delete_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationRequest.pb(workstations.DeleteWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.DeleteWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_workstation_rest_bad_request(request_type=workstations.StartWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.start_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.StartWorkstationRequest, + dict, +]) +def test_start_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and 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 + response = client.start_workstation(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_start_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_start_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_start_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.StartWorkstationRequest.pb(workstations.StartWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.StartWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.start_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_workstation_rest_bad_request(request_type=workstations.StopWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.stop_workstation(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.StopWorkstationRequest, + dict, +]) +def test_stop_workstation_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and 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 + response = client.stop_workstation(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_stop_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_stop_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_stop_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.StopWorkstationRequest.pb(workstations.StopWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = workstations.StopWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.stop_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_access_token_rest_bad_request(request_type=workstations.GenerateAccessTokenRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.generate_access_token(request) + + +@pytest.mark.parametrize("request_type", [ + workstations.GenerateAccessTokenRequest, + dict, +]) +def test_generate_access_token_rest_call_success(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse( + access_token='access_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 = workstations.GenerateAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.generate_access_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_access_token_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_generate_access_token") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_generate_access_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GenerateAccessTokenRequest.pb(workstations.GenerateAccessTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = workstations.GenerateAccessTokenResponse.to_json(workstations.GenerateAccessTokenResponse()) + req.return_value.content = return_value + + request = workstations.GenerateAccessTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.GenerateAccessTokenResponse() + + client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + 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 = policy_pb2.Policy() + + # 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 + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + 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 = policy_pb2.Policy() + + # 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 + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + 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 = iam_policy_pb2.TestIamPermissionsResponse() + + # 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 + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = WorkstationsClient( + 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 + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = WorkstationsClient( + 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 = 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 + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = WorkstationsClient( + 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 + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = WorkstationsClient( + 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 = 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 + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = WorkstationsClient( + 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 + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = WorkstationsClient( + 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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 + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': '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(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = WorkstationsClient( + 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_workstation_cluster_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + client.get_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_clusters_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + client.list_workstation_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationClustersRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + client.create_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + client.update_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_cluster_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + client.delete_workstation_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationClusterRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + client.get_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_configs_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + client.list_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This 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_usable_workstation_configs_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + client.list_usable_workstation_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationConfigsRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + client.create_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + client.update_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_config_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + client.delete_workstation_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationConfigRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + client.get_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GetWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstations_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + client.list_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListWorkstationsRequest() + + assert args[0] == request_msg + + +# This 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_usable_workstations_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + client.list_usable_workstations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.ListUsableWorkstationsRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + client.create_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.CreateWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + client.update_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.UpdateWorkstationRequest() + + assert args[0] == request_msg + + +# This 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_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + client.delete_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.DeleteWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + client.start_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StartWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_workstation_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + client.stop_workstation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.StopWorkstationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_access_token_empty_call_rest(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + client.generate_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = workstations.GenerateAccessTokenRequest() + + assert args[0] == request_msg + + +def test_workstations_rest_lro_client(): + client = WorkstationsClient( + 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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WorkstationsGrpcTransport, + ) + +def test_workstations_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WorkstationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_workstations_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WorkstationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_workstation_cluster', + 'list_workstation_clusters', + 'create_workstation_cluster', + 'update_workstation_cluster', + 'delete_workstation_cluster', + 'get_workstation_config', + 'list_workstation_configs', + 'list_usable_workstation_configs', + 'create_workstation_config', + 'update_workstation_config', + 'delete_workstation_config', + 'get_workstation', + 'list_workstations', + 'list_usable_workstations', + 'create_workstation', + 'update_workstation', + 'delete_workstation', + 'start_workstation', + 'stop_workstation', + 'generate_access_token', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + 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_workstations_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkstationsTransport( + 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_workstations_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkstationsTransport() + adc.assert_called_once() + + +def test_workstations_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) + WorkstationsClient() + 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.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + ], +) +def test_workstations_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.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + transports.WorkstationsRestTransport, + ], +) +def test_workstations_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.WorkstationsGrpcTransport, grpc_helpers), + (transports.WorkstationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_workstations_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( + "workstations.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="workstations.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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_workstations_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.WorkstationsRestTransport ( + 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_workstations_host_no_port(transport_name): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workstations.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_workstations_host_with_port(transport_name): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workstations.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workstations.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_workstations_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WorkstationsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WorkstationsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_workstation_cluster._session + session2 = client2.transport.get_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.list_workstation_clusters._session + session2 = client2.transport.list_workstation_clusters._session + assert session1 != session2 + session1 = client1.transport.create_workstation_cluster._session + session2 = client2.transport.create_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.update_workstation_cluster._session + session2 = client2.transport.update_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_workstation_cluster._session + session2 = client2.transport.delete_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.get_workstation_config._session + session2 = client2.transport.get_workstation_config._session + assert session1 != session2 + session1 = client1.transport.list_workstation_configs._session + session2 = client2.transport.list_workstation_configs._session + assert session1 != session2 + session1 = client1.transport.list_usable_workstation_configs._session + session2 = client2.transport.list_usable_workstation_configs._session + assert session1 != session2 + session1 = client1.transport.create_workstation_config._session + session2 = client2.transport.create_workstation_config._session + assert session1 != session2 + session1 = client1.transport.update_workstation_config._session + session2 = client2.transport.update_workstation_config._session + assert session1 != session2 + session1 = client1.transport.delete_workstation_config._session + session2 = client2.transport.delete_workstation_config._session + assert session1 != session2 + session1 = client1.transport.get_workstation._session + session2 = client2.transport.get_workstation._session + assert session1 != session2 + session1 = client1.transport.list_workstations._session + session2 = client2.transport.list_workstations._session + assert session1 != session2 + session1 = client1.transport.list_usable_workstations._session + session2 = client2.transport.list_usable_workstations._session + assert session1 != session2 + session1 = client1.transport.create_workstation._session + session2 = client2.transport.create_workstation._session + assert session1 != session2 + session1 = client1.transport.update_workstation._session + session2 = client2.transport.update_workstation._session + assert session1 != session2 + session1 = client1.transport.delete_workstation._session + session2 = client2.transport.delete_workstation._session + assert session1 != session2 + session1 = client1.transport.start_workstation._session + session2 = client2.transport.start_workstation._session + assert session1 != session2 + session1 = client1.transport.stop_workstation._session + session2 = client2.transport.stop_workstation._session + assert session1 != session2 + session1 = client1.transport.generate_access_token._session + session2 = client2.transport.generate_access_token._session + assert session1 != session2 +def test_workstations_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkstationsGrpcTransport( + 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_workstations_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkstationsGrpcAsyncIOTransport( + 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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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_workstations_grpc_lro_client(): + client = WorkstationsClient( + 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_workstations_grpc_lro_async_client(): + client = WorkstationsAsyncClient( + 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_workstation_path(): + project = "squid" + location = "clam" + workstation_cluster = "whelk" + workstation_config = "octopus" + workstation = "oyster" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) + actual = WorkstationsClient.workstation_path(project, location, workstation_cluster, workstation_config, workstation) + assert expected == actual + + +def test_parse_workstation_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "workstation_cluster": "mussel", + "workstation_config": "winkle", + "workstation": "nautilus", + } + path = WorkstationsClient.workstation_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_path(path) + assert expected == actual + +def test_workstation_cluster_path(): + project = "scallop" + location = "abalone" + workstation_cluster = "squid" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) + actual = WorkstationsClient.workstation_cluster_path(project, location, workstation_cluster) + assert expected == actual + + +def test_parse_workstation_cluster_path(): + expected = { + "project": "clam", + "location": "whelk", + "workstation_cluster": "octopus", + } + path = WorkstationsClient.workstation_cluster_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_cluster_path(path) + assert expected == actual + +def test_workstation_config_path(): + project = "oyster" + location = "nudibranch" + workstation_cluster = "cuttlefish" + workstation_config = "mussel" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) + actual = WorkstationsClient.workstation_config_path(project, location, workstation_cluster, workstation_config) + assert expected == actual + + +def test_parse_workstation_config_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "workstation_cluster": "scallop", + "workstation_config": "abalone", + } + path = WorkstationsClient.workstation_config_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WorkstationsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = WorkstationsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = WorkstationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = WorkstationsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WorkstationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = WorkstationsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = WorkstationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = WorkstationsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.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 = WorkstationsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = WorkstationsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.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.WorkstationsTransport, '_prep_wrapped_messages') as prep: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WorkstationsTransport, '_prep_wrapped_messages') as prep: + transport_class = WorkstationsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_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 response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_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 response is None + +def test_delete_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_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_delete_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_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_delete_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_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 response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_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 response is None + +def test_cancel_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_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_cancel_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_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_cancel_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = WorkstationsClient( + 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 = WorkstationsAsyncClient( + 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_list_operations(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the 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.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional 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.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the 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.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_list_operations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_list_operations_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_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", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_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", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_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", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_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", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = WorkstationsClient( + 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 = WorkstationsAsyncClient( + 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 = WorkstationsClient( + 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 = WorkstationsClient( + 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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport), +]) +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-geo-type/viewport-py/.coveragerc b/owl-bot-staging/google-geo-type/viewport-py/.coveragerc new file mode 100644 index 000000000000..e4af1d8d84ca --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/geo/type/__init__.py + google/geo/type/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-geo-type/viewport-py/.flake8 b/owl-bot-staging/google-geo-type/viewport-py/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/.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-geo-type/viewport-py/MANIFEST.in b/owl-bot-staging/google-geo-type/viewport-py/MANIFEST.in new file mode 100644 index 000000000000..736f6f23c6ae --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/geo/type *.py +recursive-include google/geo/type *.py diff --git a/owl-bot-staging/google-geo-type/viewport-py/README.rst b/owl-bot-staging/google-geo-type/viewport-py/README.rst new file mode 100644 index 000000000000..82c7fce9ba73 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Geo Type 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 Geo Type 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-geo-type/viewport-py/docs/_static/custom.css b/owl-bot-staging/google-geo-type/viewport-py/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-geo-type/viewport-py/docs/conf.py b/owl-bot-staging/google-geo-type/viewport-py/docs/conf.py new file mode 100644 index 000000000000..0a0ece936017 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type 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-geo-type" +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 Geo 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-geo-type-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-geo-type.tex", + u"google-geo-type 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-geo-type", + u"Google Geo Type 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-geo-type", + u"google-geo-type Documentation", + author, + "google-geo-type", + "GAPIC library for Google Geo Type 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-geo-type/viewport-py/docs/index.rst b/owl-bot-staging/google-geo-type/viewport-py/docs/index.rst new file mode 100644 index 000000000000..2605a730d688 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + type/services_ + type/types_ diff --git a/owl-bot-staging/google-geo-type/viewport-py/docs/type/services_.rst b/owl-bot-staging/google-geo-type/viewport-py/docs/type/services_.rst new file mode 100644 index 000000000000..dd35c5318c16 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/docs/type/services_.rst @@ -0,0 +1,4 @@ +Services for Google Geo Type API +================================= +.. toctree:: + :maxdepth: 2 diff --git a/owl-bot-staging/google-geo-type/viewport-py/docs/type/types_.rst b/owl-bot-staging/google-geo-type/viewport-py/docs/type/types_.rst new file mode 100644 index 000000000000..e35c4d36c639 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/docs/type/types_.rst @@ -0,0 +1,6 @@ +Types for Google Geo Type API +============================== + +.. automodule:: google.geo.type.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/__init__.py new file mode 100644 index 000000000000..25f9431db757 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/__init__.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. +# +from google.geo.type import gapic_version as package_version + +__version__ = package_version.__version__ + + + +from .types.viewport import Viewport + +__all__ = ( +'Viewport', +) diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_metadata.json b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_metadata.json new file mode 100644 index 000000000000..4be1a3ac6e07 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_metadata.json @@ -0,0 +1,7 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.geo.type", + "protoPackage": "google.geo.type", + "schema": "1.0" +} diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_version.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/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-geo-type/viewport-py/google/geo/type/py.typed b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/py.typed new file mode 100644 index 000000000000..0e339d46fd3d --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-geo-type package uses inline types. diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/services/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/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-geo-type/viewport-py/google/geo/type/types/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/__init__.py new file mode 100644 index 000000000000..c7e53503d3fb --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/__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 .viewport import ( + Viewport, +) + +__all__ = ( + 'Viewport', +) diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/viewport.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/viewport.py new file mode 100644 index 000000000000..745655ca0561 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/viewport.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 __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.geo.type', + manifest={ + 'Viewport', + }, +) + + +class Viewport(proto.Message): + r"""A latitude-longitude viewport, represented as two diagonally + opposite ``low`` and ``high`` points. A viewport is considered a + closed region, i.e. it includes its boundary. The latitude bounds + must range between -90 to 90 degrees inclusive, and the longitude + bounds must range between -180 to 180 degrees inclusive. Various + cases include: + + - If ``low`` = ``high``, the viewport consists of that single + point. + + - If ``low.longitude`` > ``high.longitude``, the longitude range is + inverted (the viewport crosses the 180 degree longitude line). + + - If ``low.longitude`` = -180 degrees and ``high.longitude`` = 180 + degrees, the viewport includes all longitudes. + + - If ``low.longitude`` = 180 degrees and ``high.longitude`` = -180 + degrees, the longitude range is empty. + + - If ``low.latitude`` > ``high.latitude``, the latitude range is + empty. + + Both ``low`` and ``high`` must be populated, and the represented box + cannot be empty (as specified by the definitions above). An empty + viewport will result in an error. + + For example, this viewport fully encloses New York City: + + { "low": { "latitude": 40.477398, "longitude": -74.259087 }, "high": + { "latitude": 40.91618, "longitude": -73.70018 } } + + Attributes: + low (google.type.latlng_pb2.LatLng): + Required. The low point of the viewport. + high (google.type.latlng_pb2.LatLng): + Required. The high point of the viewport. + """ + + low: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + high: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=2, + message=latlng_pb2.LatLng, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-geo-type/viewport-py/mypy.ini b/owl-bot-staging/google-geo-type/viewport-py/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-geo-type/viewport-py/noxfile.py b/owl-bot-staging/google-geo-type/viewport-py/noxfile.py new file mode 100644 index 000000000000..50140b2929b3 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type' + +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/geo/type/', + '--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/geo/type/', + '--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-geo-type/viewport-py/scripts/fixup_type_keywords.py b/owl-bot-staging/google-geo-type/viewport-py/scripts/fixup_type_keywords.py new file mode 100644 index 000000000000..bae51b8ecbd3 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/scripts/fixup_type_keywords.py @@ -0,0 +1,175 @@ +#! /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 typeCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + } + + 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=typeCallTransformer(), +): + """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 type 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-geo-type/viewport-py/setup.py b/owl-bot-staging/google-geo-type/viewport-py/setup.py new file mode 100644 index 000000000000..aee4ccc5c261 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type' + + +description = "Google Geo Type API client library" + +version = None + +with open(os.path.join(package_root, 'google/geo/type/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-geo-type" + +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-geo-type/viewport-py/testing/constraints-3.10.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.11.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.12.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.13.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.7.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.8.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.9.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/tests/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/tests/unit/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/tests/unit/gapic/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/tests/unit/gapic/type/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/type/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/type/__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-addressvalidation/v1/.coveragerc b/owl-bot-staging/google-maps-addressvalidation/v1/.coveragerc new file mode 100644 index 000000000000..e4692ea29e6d --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/addressvalidation/__init__.py + google/maps/addressvalidation/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-addressvalidation/v1/.flake8 b/owl-bot-staging/google-maps-addressvalidation/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/MANIFEST.in b/owl-bot-staging/google-maps-addressvalidation/v1/MANIFEST.in new file mode 100644 index 000000000000..6d21915b6647 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/addressvalidation *.py +recursive-include google/maps/addressvalidation_v1 *.py diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/README.rst b/owl-bot-staging/google-maps-addressvalidation/v1/README.rst new file mode 100644 index 000000000000..6bce085c3115 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Addressvalidation 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 Addressvalidation 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-addressvalidation/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-addressvalidation/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/address_validation.rst b/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/address_validation.rst new file mode 100644 index 000000000000..bfcddd27291d --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/address_validation.rst @@ -0,0 +1,6 @@ +AddressValidation +----------------------------------- + +.. automodule:: google.maps.addressvalidation_v1.services.address_validation + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/services_.rst b/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/services_.rst new file mode 100644 index 000000000000..44fb49f7a1cb --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Addressvalidation v1 API +================================================= +.. toctree:: + :maxdepth: 2 + + address_validation diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/types_.rst b/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/types_.rst new file mode 100644 index 000000000000..454488a7c78b --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Addressvalidation v1 API +============================================== + +.. automodule:: google.maps.addressvalidation_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/docs/conf.py b/owl-bot-staging/google-maps-addressvalidation/v1/docs/conf.py new file mode 100644 index 000000000000..9d5b6f3e706d --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation 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-addressvalidation" +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-addressvalidation-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-addressvalidation.tex", + u"google-maps-addressvalidation 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-addressvalidation", + u"Google Maps Addressvalidation 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-addressvalidation", + u"google-maps-addressvalidation Documentation", + author, + "google-maps-addressvalidation", + "GAPIC library for Google Maps Addressvalidation 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-addressvalidation/v1/docs/index.rst b/owl-bot-staging/google-maps-addressvalidation/v1/docs/index.rst new file mode 100644 index 000000000000..cd7722de7e1b --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + addressvalidation_v1/services_ + addressvalidation_v1/types_ diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/__init__.py new file mode 100644 index 000000000000..96f9e6d5ca84 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/__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.addressvalidation import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.addressvalidation_v1.services.address_validation.client import AddressValidationClient +from google.maps.addressvalidation_v1.services.address_validation.async_client import AddressValidationAsyncClient + +from google.maps.addressvalidation_v1.types.address import Address +from google.maps.addressvalidation_v1.types.address import AddressComponent +from google.maps.addressvalidation_v1.types.address import ComponentName +from google.maps.addressvalidation_v1.types.address_validation_service import ProvideValidationFeedbackRequest +from google.maps.addressvalidation_v1.types.address_validation_service import ProvideValidationFeedbackResponse +from google.maps.addressvalidation_v1.types.address_validation_service import ValidateAddressRequest +from google.maps.addressvalidation_v1.types.address_validation_service import ValidateAddressResponse +from google.maps.addressvalidation_v1.types.address_validation_service import ValidationResult +from google.maps.addressvalidation_v1.types.address_validation_service import Verdict +from google.maps.addressvalidation_v1.types.geocode import Geocode +from google.maps.addressvalidation_v1.types.geocode import PlusCode +from google.maps.addressvalidation_v1.types.metadata_ import AddressMetadata +from google.maps.addressvalidation_v1.types.usps_data import UspsAddress +from google.maps.addressvalidation_v1.types.usps_data import UspsData + +__all__ = ('AddressValidationClient', + 'AddressValidationAsyncClient', + 'Address', + 'AddressComponent', + 'ComponentName', + 'ProvideValidationFeedbackRequest', + 'ProvideValidationFeedbackResponse', + 'ValidateAddressRequest', + 'ValidateAddressResponse', + 'ValidationResult', + 'Verdict', + 'Geocode', + 'PlusCode', + 'AddressMetadata', + 'UspsAddress', + 'UspsData', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/gapic_version.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/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-addressvalidation/v1/google/maps/addressvalidation/py.typed b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/py.typed new file mode 100644 index 000000000000..1e46c59c8e22 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-addressvalidation package uses inline types. diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/__init__.py new file mode 100644 index 000000000000..b93f37bdcafd --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_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.addressvalidation_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.address_validation import AddressValidationClient +from .services.address_validation import AddressValidationAsyncClient + +from .types.address import Address +from .types.address import AddressComponent +from .types.address import ComponentName +from .types.address_validation_service import ProvideValidationFeedbackRequest +from .types.address_validation_service import ProvideValidationFeedbackResponse +from .types.address_validation_service import ValidateAddressRequest +from .types.address_validation_service import ValidateAddressResponse +from .types.address_validation_service import ValidationResult +from .types.address_validation_service import Verdict +from .types.geocode import Geocode +from .types.geocode import PlusCode +from .types.metadata_ import AddressMetadata +from .types.usps_data import UspsAddress +from .types.usps_data import UspsData + +__all__ = ( + 'AddressValidationAsyncClient', +'Address', +'AddressComponent', +'AddressMetadata', +'AddressValidationClient', +'ComponentName', +'Geocode', +'PlusCode', +'ProvideValidationFeedbackRequest', +'ProvideValidationFeedbackResponse', +'UspsAddress', +'UspsData', +'ValidateAddressRequest', +'ValidateAddressResponse', +'ValidationResult', +'Verdict', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_metadata.json b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_metadata.json new file mode 100644 index 000000000000..c521c066be76 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_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.addressvalidation_v1", + "protoPackage": "google.maps.addressvalidation.v1", + "schema": "1.0", + "services": { + "AddressValidation": { + "clients": { + "grpc": { + "libraryClient": "AddressValidationClient", + "rpcs": { + "ProvideValidationFeedback": { + "methods": [ + "provide_validation_feedback" + ] + }, + "ValidateAddress": { + "methods": [ + "validate_address" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AddressValidationAsyncClient", + "rpcs": { + "ProvideValidationFeedback": { + "methods": [ + "provide_validation_feedback" + ] + }, + "ValidateAddress": { + "methods": [ + "validate_address" + ] + } + } + }, + "rest": { + "libraryClient": "AddressValidationClient", + "rpcs": { + "ProvideValidationFeedback": { + "methods": [ + "provide_validation_feedback" + ] + }, + "ValidateAddress": { + "methods": [ + "validate_address" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_version.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_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-addressvalidation/v1/google/maps/addressvalidation_v1/py.typed b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/py.typed new file mode 100644 index 000000000000..1e46c59c8e22 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-addressvalidation package uses inline types. diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_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-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/__init__.py new file mode 100644 index 000000000000..913dcf3e63eb --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/__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 AddressValidationClient +from .async_client import AddressValidationAsyncClient + +__all__ = ( + 'AddressValidationClient', + 'AddressValidationAsyncClient', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/async_client.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/async_client.py new file mode 100644 index 000000000000..5a472ca3006e --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/async_client.py @@ -0,0 +1,392 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.maps.addressvalidation_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.addressvalidation_v1.types import address_validation_service +from .transports.base import AddressValidationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AddressValidationGrpcAsyncIOTransport +from .client import AddressValidationClient + + +class AddressValidationAsyncClient: + """The service for validating addresses.""" + + _client: AddressValidationClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AddressValidationClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AddressValidationClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AddressValidationClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AddressValidationClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod(AddressValidationClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AddressValidationClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AddressValidationClient.common_folder_path) + parse_common_folder_path = staticmethod(AddressValidationClient.parse_common_folder_path) + common_organization_path = staticmethod(AddressValidationClient.common_organization_path) + parse_common_organization_path = staticmethod(AddressValidationClient.parse_common_organization_path) + common_project_path = staticmethod(AddressValidationClient.common_project_path) + parse_common_project_path = staticmethod(AddressValidationClient.parse_common_project_path) + common_location_path = staticmethod(AddressValidationClient.common_location_path) + parse_common_location_path = staticmethod(AddressValidationClient.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: + AddressValidationAsyncClient: The constructed client. + """ + return AddressValidationClient.from_service_account_info.__func__(AddressValidationAsyncClient, 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: + AddressValidationAsyncClient: The constructed client. + """ + return AddressValidationClient.from_service_account_file.__func__(AddressValidationAsyncClient, 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 AddressValidationClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AddressValidationTransport: + """Returns the transport used by the client instance. + + Returns: + AddressValidationTransport: 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 = AddressValidationClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AddressValidationTransport, Callable[..., AddressValidationTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the address validation 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,AddressValidationTransport,Callable[..., AddressValidationTransport]]]): + 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 AddressValidationTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = AddressValidationClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def validate_address(self, + request: Optional[Union[address_validation_service.ValidateAddressRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> address_validation_service.ValidateAddressResponse: + r"""Validates an address. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 addressvalidation_v1 + + async def sample_validate_address(): + # Create a client + client = addressvalidation_v1.AddressValidationAsyncClient() + + # Initialize request argument(s) + request = addressvalidation_v1.ValidateAddressRequest( + ) + + # Make the request + response = await client.validate_address(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.addressvalidation_v1.types.ValidateAddressRequest, dict]]): + The request object. The request for validating an + address. + retry (google.api_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. + + Returns: + google.maps.addressvalidation_v1.types.ValidateAddressResponse: + The response to an address validation + request. + + """ + # 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, address_validation_service.ValidateAddressRequest): + request = address_validation_service.ValidateAddressRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.validate_address] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def provide_validation_feedback(self, + request: Optional[Union[address_validation_service.ProvideValidationFeedbackRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> address_validation_service.ProvideValidationFeedbackResponse: + r"""Feedback about the outcome of the sequence of validation + attempts. This should be the last call made after a sequence of + validation calls for the same address, and should be called once + the transaction is concluded. This should only be sent once for + the sequence of ``ValidateAddress`` requests needed to validate + an address fully. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 addressvalidation_v1 + + async def sample_provide_validation_feedback(): + # Create a client + client = addressvalidation_v1.AddressValidationAsyncClient() + + # Initialize request argument(s) + request = addressvalidation_v1.ProvideValidationFeedbackRequest( + conclusion="UNUSED", + response_id="response_id_value", + ) + + # Make the request + response = await client.provide_validation_feedback(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest, dict]]): + The request object. The request for sending validation + feedback. + retry (google.api_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. + + Returns: + google.maps.addressvalidation_v1.types.ProvideValidationFeedbackResponse: + The response for validation feedback. + + The response is empty if the feedback is + sent successfully. + + """ + # 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, address_validation_service.ProvideValidationFeedbackRequest): + request = address_validation_service.ProvideValidationFeedbackRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.provide_validation_feedback] + + # Validate the universe domain. + self._client._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) -> "AddressValidationAsyncClient": + 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__ = ( + "AddressValidationAsyncClient", +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/client.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/client.py new file mode 100644 index 000000000000..bda137e9c64e --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/client.py @@ -0,0 +1,740 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.maps.addressvalidation_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 + +from google.maps.addressvalidation_v1.types import address_validation_service +from .transports.base import AddressValidationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AddressValidationGrpcTransport +from .transports.grpc_asyncio import AddressValidationGrpcAsyncIOTransport +from .transports.rest import AddressValidationRestTransport + + +class AddressValidationClientMeta(type): + """Metaclass for the AddressValidation 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[AddressValidationTransport]] + _transport_registry["grpc"] = AddressValidationGrpcTransport + _transport_registry["grpc_asyncio"] = AddressValidationGrpcAsyncIOTransport + _transport_registry["rest"] = AddressValidationRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AddressValidationTransport]: + """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 AddressValidationClient(metaclass=AddressValidationClientMeta): + """The service for validating addresses.""" + + @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 = "addressvalidation.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "addressvalidation.{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: + AddressValidationClient: 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: + AddressValidationClient: 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) -> AddressValidationTransport: + """Returns the transport used by the client instance. + + Returns: + AddressValidationTransport: 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 = AddressValidationClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AddressValidationClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AddressValidationClient._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 = AddressValidationClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = AddressValidationClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + AddressValidationClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, AddressValidationTransport, Callable[..., AddressValidationTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the address validation client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AddressValidationTransport,Callable[..., AddressValidationTransport]]]): + 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 AddressValidationTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = AddressValidationClient._read_environment_variables() + self._client_cert_source = AddressValidationClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AddressValidationClient._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 + + 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, AddressValidationTransport) + if transport_provided: + # transport is a AddressValidationTransport 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(AddressValidationTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AddressValidationClient._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[AddressValidationTransport], Callable[..., AddressValidationTransport]] = ( + AddressValidationClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AddressValidationTransport], 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, + ) + + def validate_address(self, + request: Optional[Union[address_validation_service.ValidateAddressRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> address_validation_service.ValidateAddressResponse: + r"""Validates an address. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 addressvalidation_v1 + + def sample_validate_address(): + # Create a client + client = addressvalidation_v1.AddressValidationClient() + + # Initialize request argument(s) + request = addressvalidation_v1.ValidateAddressRequest( + ) + + # Make the request + response = client.validate_address(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.addressvalidation_v1.types.ValidateAddressRequest, dict]): + The request object. The request for validating an + address. + retry (google.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. + + Returns: + google.maps.addressvalidation_v1.types.ValidateAddressResponse: + The response to an address validation + request. + + """ + # 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, address_validation_service.ValidateAddressRequest): + request = address_validation_service.ValidateAddressRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_address] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def provide_validation_feedback(self, + request: Optional[Union[address_validation_service.ProvideValidationFeedbackRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> address_validation_service.ProvideValidationFeedbackResponse: + r"""Feedback about the outcome of the sequence of validation + attempts. This should be the last call made after a sequence of + validation calls for the same address, and should be called once + the transaction is concluded. This should only be sent once for + the sequence of ``ValidateAddress`` requests needed to validate + an address fully. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 addressvalidation_v1 + + def sample_provide_validation_feedback(): + # Create a client + client = addressvalidation_v1.AddressValidationClient() + + # Initialize request argument(s) + request = addressvalidation_v1.ProvideValidationFeedbackRequest( + conclusion="UNUSED", + response_id="response_id_value", + ) + + # Make the request + response = client.provide_validation_feedback(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest, dict]): + The request object. The request for sending validation + feedback. + retry (google.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. + + Returns: + google.maps.addressvalidation_v1.types.ProvideValidationFeedbackResponse: + The response for validation feedback. + + The response is empty if the feedback is + sent successfully. + + """ + # 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, address_validation_service.ProvideValidationFeedbackRequest): + request = address_validation_service.ProvideValidationFeedbackRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.provide_validation_feedback] + + # Validate the universe 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) -> "AddressValidationClient": + 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__ = ( + "AddressValidationClient", +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/README.rst b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/README.rst new file mode 100644 index 000000000000..a4f79a60e995 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AddressValidationTransport` is the ABC for all transports. +- public child `AddressValidationGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AddressValidationGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAddressValidationRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AddressValidationRestTransport` 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-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/__init__.py new file mode 100644 index 000000000000..fb4627d8d61f --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/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 AddressValidationTransport +from .grpc import AddressValidationGrpcTransport +from .grpc_asyncio import AddressValidationGrpcAsyncIOTransport +from .rest import AddressValidationRestTransport +from .rest import AddressValidationRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AddressValidationTransport]] +_transport_registry['grpc'] = AddressValidationGrpcTransport +_transport_registry['grpc_asyncio'] = AddressValidationGrpcAsyncIOTransport +_transport_registry['rest'] = AddressValidationRestTransport + +__all__ = ( + 'AddressValidationTransport', + 'AddressValidationGrpcTransport', + 'AddressValidationGrpcAsyncIOTransport', + 'AddressValidationRestTransport', + 'AddressValidationRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/base.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/base.py new file mode 100644 index 000000000000..031c80651d72 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/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.addressvalidation_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.addressvalidation_v1.types import address_validation_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AddressValidationTransport(abc.ABC): + """Abstract transport class for AddressValidation.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'addressvalidation.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: 'addressvalidation.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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.validate_address: gapic_v1.method.wrap_method( + self.validate_address, + default_timeout=None, + client_info=client_info, + ), + self.provide_validation_feedback: gapic_v1.method.wrap_method( + self.provide_validation_feedback, + 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 validate_address(self) -> Callable[ + [address_validation_service.ValidateAddressRequest], + Union[ + address_validation_service.ValidateAddressResponse, + Awaitable[address_validation_service.ValidateAddressResponse] + ]]: + raise NotImplementedError() + + @property + def provide_validation_feedback(self) -> Callable[ + [address_validation_service.ProvideValidationFeedbackRequest], + Union[ + address_validation_service.ProvideValidationFeedbackResponse, + Awaitable[address_validation_service.ProvideValidationFeedbackResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AddressValidationTransport', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc.py new file mode 100644 index 000000000000..c88998ac09c9 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.maps.addressvalidation_v1.types import address_validation_service +from .base import AddressValidationTransport, DEFAULT_CLIENT_INFO + + +class AddressValidationGrpcTransport(AddressValidationTransport): + """gRPC backend transport for AddressValidation. + + The service for validating addresses. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'addressvalidation.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: 'addressvalidation.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'addressvalidation.googleapis.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 validate_address(self) -> Callable[ + [address_validation_service.ValidateAddressRequest], + address_validation_service.ValidateAddressResponse]: + r"""Return a callable for the validate address method over gRPC. + + Validates an address. + + Returns: + Callable[[~.ValidateAddressRequest], + ~.ValidateAddressResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_address' not in self._stubs: + self._stubs['validate_address'] = self.grpc_channel.unary_unary( + '/google.maps.addressvalidation.v1.AddressValidation/ValidateAddress', + request_serializer=address_validation_service.ValidateAddressRequest.serialize, + response_deserializer=address_validation_service.ValidateAddressResponse.deserialize, + ) + return self._stubs['validate_address'] + + @property + def provide_validation_feedback(self) -> Callable[ + [address_validation_service.ProvideValidationFeedbackRequest], + address_validation_service.ProvideValidationFeedbackResponse]: + r"""Return a callable for the provide validation feedback method over gRPC. + + Feedback about the outcome of the sequence of validation + attempts. This should be the last call made after a sequence of + validation calls for the same address, and should be called once + the transaction is concluded. This should only be sent once for + the sequence of ``ValidateAddress`` requests needed to validate + an address fully. + + Returns: + Callable[[~.ProvideValidationFeedbackRequest], + ~.ProvideValidationFeedbackResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'provide_validation_feedback' not in self._stubs: + self._stubs['provide_validation_feedback'] = self.grpc_channel.unary_unary( + '/google.maps.addressvalidation.v1.AddressValidation/ProvideValidationFeedback', + request_serializer=address_validation_service.ProvideValidationFeedbackRequest.serialize, + response_deserializer=address_validation_service.ProvideValidationFeedbackResponse.deserialize, + ) + return self._stubs['provide_validation_feedback'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AddressValidationGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc_asyncio.py new file mode 100644 index 000000000000..08c85a976410 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc_asyncio.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.addressvalidation_v1.types import address_validation_service +from .base import AddressValidationTransport, DEFAULT_CLIENT_INFO +from .grpc import AddressValidationGrpcTransport + + +class AddressValidationGrpcAsyncIOTransport(AddressValidationTransport): + """gRPC AsyncIO backend transport for AddressValidation. + + The service for validating addresses. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'addressvalidation.googleapis.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 = 'addressvalidation.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: 'addressvalidation.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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 validate_address(self) -> Callable[ + [address_validation_service.ValidateAddressRequest], + Awaitable[address_validation_service.ValidateAddressResponse]]: + r"""Return a callable for the validate address method over gRPC. + + Validates an address. + + Returns: + Callable[[~.ValidateAddressRequest], + Awaitable[~.ValidateAddressResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_address' not in self._stubs: + self._stubs['validate_address'] = self.grpc_channel.unary_unary( + '/google.maps.addressvalidation.v1.AddressValidation/ValidateAddress', + request_serializer=address_validation_service.ValidateAddressRequest.serialize, + response_deserializer=address_validation_service.ValidateAddressResponse.deserialize, + ) + return self._stubs['validate_address'] + + @property + def provide_validation_feedback(self) -> Callable[ + [address_validation_service.ProvideValidationFeedbackRequest], + Awaitable[address_validation_service.ProvideValidationFeedbackResponse]]: + r"""Return a callable for the provide validation feedback method over gRPC. + + Feedback about the outcome of the sequence of validation + attempts. This should be the last call made after a sequence of + validation calls for the same address, and should be called once + the transaction is concluded. This should only be sent once for + the sequence of ``ValidateAddress`` requests needed to validate + an address fully. + + Returns: + Callable[[~.ProvideValidationFeedbackRequest], + Awaitable[~.ProvideValidationFeedbackResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'provide_validation_feedback' not in self._stubs: + self._stubs['provide_validation_feedback'] = self.grpc_channel.unary_unary( + '/google.maps.addressvalidation.v1.AddressValidation/ProvideValidationFeedback', + request_serializer=address_validation_service.ProvideValidationFeedbackRequest.serialize, + response_deserializer=address_validation_service.ProvideValidationFeedbackResponse.deserialize, + ) + return self._stubs['provide_validation_feedback'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.validate_address: self._wrap_method( + self.validate_address, + default_timeout=None, + client_info=client_info, + ), + self.provide_validation_feedback: self._wrap_method( + self.provide_validation_feedback, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'AddressValidationGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py new file mode 100644 index 000000000000..7f8c3885e117 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest.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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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.addressvalidation_v1.types import address_validation_service + + +from .rest_base import _BaseAddressValidationRestTransport +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 + + +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 AddressValidationRestInterceptor: + """Interceptor for AddressValidation. + + 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 AddressValidationRestTransport. + + .. code-block:: python + class MyCustomAddressValidationInterceptor(AddressValidationRestInterceptor): + def pre_provide_validation_feedback(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_provide_validation_feedback(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_validate_address(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_validate_address(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AddressValidationRestTransport(interceptor=MyCustomAddressValidationInterceptor()) + client = AddressValidationClient(transport=transport) + + + """ + def pre_provide_validation_feedback(self, request: address_validation_service.ProvideValidationFeedbackRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[address_validation_service.ProvideValidationFeedbackRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for provide_validation_feedback + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressValidation server. + """ + return request, metadata + + def post_provide_validation_feedback(self, response: address_validation_service.ProvideValidationFeedbackResponse) -> address_validation_service.ProvideValidationFeedbackResponse: + """Post-rpc interceptor for provide_validation_feedback + + Override in a subclass to manipulate the response + after it is returned by the AddressValidation server but before + it is returned to user code. + """ + return response + + def pre_validate_address(self, request: address_validation_service.ValidateAddressRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[address_validation_service.ValidateAddressRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for validate_address + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressValidation server. + """ + return request, metadata + + def post_validate_address(self, response: address_validation_service.ValidateAddressResponse) -> address_validation_service.ValidateAddressResponse: + """Post-rpc interceptor for validate_address + + Override in a subclass to manipulate the response + after it is returned by the AddressValidation server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AddressValidationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AddressValidationRestInterceptor + + +class AddressValidationRestTransport(_BaseAddressValidationRestTransport): + """REST backend synchronous transport for AddressValidation. + + The service for validating addresses. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'addressvalidation.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[AddressValidationRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'addressvalidation.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 AddressValidationRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ProvideValidationFeedback(_BaseAddressValidationRestTransport._BaseProvideValidationFeedback, AddressValidationRestStub): + def __hash__(self): + return hash("AddressValidationRestTransport.ProvideValidationFeedback") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: address_validation_service.ProvideValidationFeedbackRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> address_validation_service.ProvideValidationFeedbackResponse: + r"""Call the provide validation + feedback method over HTTP. + + Args: + request (~.address_validation_service.ProvideValidationFeedbackRequest): + The request object. The request for sending validation + feedback. + retry (google.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. + + Returns: + ~.address_validation_service.ProvideValidationFeedbackResponse: + The response for validation feedback. + + The response is empty if the feedback is + sent successfully. + + """ + + http_options = _BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_http_options() + request, metadata = self._interceptor.pre_provide_validation_feedback(request, metadata) + transcoded_request = _BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_transcoded_request(http_options, request) + + body = _BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_query_params_json(transcoded_request) + + # Send the request + response = AddressValidationRestTransport._ProvideValidationFeedback._get_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 = address_validation_service.ProvideValidationFeedbackResponse() + pb_resp = address_validation_service.ProvideValidationFeedbackResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_provide_validation_feedback(resp) + return resp + + class _ValidateAddress(_BaseAddressValidationRestTransport._BaseValidateAddress, AddressValidationRestStub): + def __hash__(self): + return hash("AddressValidationRestTransport.ValidateAddress") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: address_validation_service.ValidateAddressRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> address_validation_service.ValidateAddressResponse: + r"""Call the validate address method over HTTP. + + Args: + request (~.address_validation_service.ValidateAddressRequest): + The request object. The request for validating an + address. + retry (google.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. + + Returns: + ~.address_validation_service.ValidateAddressResponse: + The response to an address validation + request. + + """ + + http_options = _BaseAddressValidationRestTransport._BaseValidateAddress._get_http_options() + request, metadata = self._interceptor.pre_validate_address(request, metadata) + transcoded_request = _BaseAddressValidationRestTransport._BaseValidateAddress._get_transcoded_request(http_options, request) + + body = _BaseAddressValidationRestTransport._BaseValidateAddress._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressValidationRestTransport._BaseValidateAddress._get_query_params_json(transcoded_request) + + # Send the request + response = AddressValidationRestTransport._ValidateAddress._get_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 = address_validation_service.ValidateAddressResponse() + pb_resp = address_validation_service.ValidateAddressResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_validate_address(resp) + return resp + + @property + def provide_validation_feedback(self) -> Callable[ + [address_validation_service.ProvideValidationFeedbackRequest], + address_validation_service.ProvideValidationFeedbackResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ProvideValidationFeedback(self._session, self._host, self._interceptor) # type: ignore + + @property + def validate_address(self) -> Callable[ + [address_validation_service.ValidateAddressRequest], + address_validation_service.ValidateAddressResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ValidateAddress(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AddressValidationRestTransport', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest_base.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest_base.py new file mode 100644 index 000000000000..b44693398055 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/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 AddressValidationTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.maps.addressvalidation_v1.types import address_validation_service + + +class _BaseAddressValidationRestTransport(AddressValidationTransport): + """Base REST backend transport for AddressValidation. + + 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 = 'addressvalidation.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: 'addressvalidation.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 _BaseProvideValidationFeedback: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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:provideValidationFeedback', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = address_validation_service.ProvideValidationFeedbackRequest.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(_BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseValidateAddress: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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:validateAddress', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = address_validation_service.ValidateAddressRequest.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(_BaseAddressValidationRestTransport._BaseValidateAddress._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAddressValidationRestTransport', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/__init__.py new file mode 100644 index 000000000000..c261d0bfa001 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/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 .address import ( + Address, + AddressComponent, + ComponentName, +) +from .address_validation_service import ( + ProvideValidationFeedbackRequest, + ProvideValidationFeedbackResponse, + ValidateAddressRequest, + ValidateAddressResponse, + ValidationResult, + Verdict, +) +from .geocode import ( + Geocode, + PlusCode, +) +from .metadata_ import ( + AddressMetadata, +) +from .usps_data import ( + UspsAddress, + UspsData, +) + +__all__ = ( + 'Address', + 'AddressComponent', + 'ComponentName', + 'ProvideValidationFeedbackRequest', + 'ProvideValidationFeedbackResponse', + 'ValidateAddressRequest', + 'ValidateAddressResponse', + 'ValidationResult', + 'Verdict', + 'Geocode', + 'PlusCode', + 'AddressMetadata', + 'UspsAddress', + 'UspsData', +) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address.py new file mode 100644 index 000000000000..9af37ec7d243 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.type import postal_address_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.addressvalidation.v1', + manifest={ + 'Address', + 'AddressComponent', + 'ComponentName', + }, +) + + +class Address(proto.Message): + r"""Details of the post-processed address. Post-processing + includes correcting misspelled parts of the address, replacing + incorrect parts, and inferring missing parts. + + Attributes: + formatted_address (str): + The post-processed address, formatted as a + single-line address following the address + formatting rules of the region where the address + is located. + postal_address (google.type.postal_address_pb2.PostalAddress): + The post-processed address represented as a + postal address. + address_components (MutableSequence[google.maps.addressvalidation_v1.types.AddressComponent]): + Unordered list. The individual address + components of the formatted and corrected + address, along with validation information. This + provides information on the validation status of + the individual components. + + Address components are not ordered in a + particular way. Do not make any assumptions on + the ordering of the address components in the + list. + missing_component_types (MutableSequence[str]): + The types of components that were expected to be present in + a correctly formatted mailing address but were not found in + the input AND could not be inferred. Components of this type + are not present in ``formatted_address``, + ``postal_address``, or ``address_components``. An example + might be ``['street_number', 'route']`` for an input like + "Boulder, Colorado, 80301, USA". The list of possible types + can be found + `here `__. + unconfirmed_component_types (MutableSequence[str]): + The types of the components that are present in the + ``address_components`` but could not be confirmed to be + correct. This field is provided for the sake of convenience: + its contents are equivalent to iterating through the + ``address_components`` to find the types of all the + components where the + [confirmation_level][google.maps.addressvalidation.v1.AddressComponent.confirmation_level] + is not + [CONFIRMED][google.maps.addressvalidation.v1.AddressComponent.ConfirmationLevel.CONFIRMED] + or the + [inferred][google.maps.addressvalidation.v1.AddressComponent.inferred] + flag is not set to ``true``. The list of possible types can + be found + `here `__. + unresolved_tokens (MutableSequence[str]): + Any tokens in the input that could not be resolved. This + might be an input that was not recognized as a valid part of + an address (for example in an input like "123235253253 Main + St, San Francisco, CA, 94105", the unresolved tokens may + look like ``["123235253253"]`` since that does not look like + a valid street number. + """ + + formatted_address: str = proto.Field( + proto.STRING, + number=2, + ) + postal_address: postal_address_pb2.PostalAddress = proto.Field( + proto.MESSAGE, + number=3, + message=postal_address_pb2.PostalAddress, + ) + address_components: MutableSequence['AddressComponent'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AddressComponent', + ) + missing_component_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + unconfirmed_component_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + unresolved_tokens: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class AddressComponent(proto.Message): + r"""Represents an address component, such as a street, city, or + state. + + Attributes: + component_name (google.maps.addressvalidation_v1.types.ComponentName): + The name for this component. + component_type (str): + The type of the address component. See `Table 2: Additional + types returned by the Places + service `__ + for a list of possible types. + confirmation_level (google.maps.addressvalidation_v1.types.AddressComponent.ConfirmationLevel): + Indicates the level of certainty that we have + that the component is correct. + inferred (bool): + Indicates that the component was not part of + the input, but we inferred it for the address + location and believe it should be provided for a + complete address. + spell_corrected (bool): + Indicates a correction to a misspelling in + the component name. The API does not always + flag changes from one spelling variant to + another, such as when changing "centre" to + "center". It also does not always flag common + misspellings, such as when changing + "Amphitheater Pkwy" to "Amphitheatre Pkwy". + replaced (bool): + Indicates the name of the component was + replaced with a completely different one, for + example a wrong postal code being replaced with + one that is correct for the address. This is not + a cosmetic change, the input component has been + changed to a different one. + unexpected (bool): + Indicates an address component that is not + expected to be present in a postal address for + the given region. We have retained it only + because it was part of the input. + """ + class ConfirmationLevel(proto.Enum): + r"""The different possible values for confirmation levels. + + Values: + CONFIRMATION_LEVEL_UNSPECIFIED (0): + Default value. This value is unused. + CONFIRMED (1): + We were able to verify that this component + exists and makes sense in the context of the + rest of the address. + UNCONFIRMED_BUT_PLAUSIBLE (2): + This component could not be confirmed, but it + is plausible that it exists. For example, a + street number within a known valid range of + numbers on a street where specific house numbers + are not known. + UNCONFIRMED_AND_SUSPICIOUS (3): + This component was not confirmed and is + likely to be wrong. For example, a neighborhood + that does not fit the rest of the address. + """ + CONFIRMATION_LEVEL_UNSPECIFIED = 0 + CONFIRMED = 1 + UNCONFIRMED_BUT_PLAUSIBLE = 2 + UNCONFIRMED_AND_SUSPICIOUS = 3 + + component_name: 'ComponentName' = proto.Field( + proto.MESSAGE, + number=1, + message='ComponentName', + ) + component_type: str = proto.Field( + proto.STRING, + number=2, + ) + confirmation_level: ConfirmationLevel = proto.Field( + proto.ENUM, + number=3, + enum=ConfirmationLevel, + ) + inferred: bool = proto.Field( + proto.BOOL, + number=4, + ) + spell_corrected: bool = proto.Field( + proto.BOOL, + number=5, + ) + replaced: bool = proto.Field( + proto.BOOL, + number=6, + ) + unexpected: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +class ComponentName(proto.Message): + r"""A wrapper for the name of the component. + + Attributes: + text (str): + The name text. For example, "5th Avenue" for + a street name or "1253" for a street number. + language_code (str): + The BCP-47 language code. This will not be + present if the component name is not associated + with a language, such as a street number. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + language_code: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address_validation_service.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address_validation_service.py new file mode 100644 index 000000000000..b9af9ae8fbf6 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address_validation_service.py @@ -0,0 +1,413 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.addressvalidation_v1.types import address as gma_address +from google.maps.addressvalidation_v1.types import geocode as gma_geocode +from google.maps.addressvalidation_v1.types import metadata_ +from google.maps.addressvalidation_v1.types import usps_data as gma_usps_data +from google.type import postal_address_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.addressvalidation.v1', + manifest={ + 'ValidateAddressRequest', + 'ValidateAddressResponse', + 'ProvideValidationFeedbackRequest', + 'ProvideValidationFeedbackResponse', + 'ValidationResult', + 'Verdict', + }, +) + + +class ValidateAddressRequest(proto.Message): + r"""The request for validating an address. + + Attributes: + address (google.type.postal_address_pb2.PostalAddress): + Required. The address being validated. Unformatted addresses + should be submitted via + [``address_lines``][google.type.PostalAddress.address_lines]. + + The total length of the fields in this input must not exceed + 280 characters. + + Supported regions can be found + `here `__. + + The [language_code][google.type.PostalAddress.language_code] + value in the input address is reserved for future uses and + is ignored today. The validated address result will be + populated based on the preferred language for the given + address, as identified by the system. + + The Address Validation API ignores the values in + [recipients][google.type.PostalAddress.recipients] and + [organization][google.type.PostalAddress.organization]. Any + values in those fields will be discarded and not returned. + Please do not set them. + previous_response_id (str): + This field must be empty for the first address validation + request. If more requests are necessary to fully validate a + single address (for example if the changes the user makes + after the initial validation need to be re-validated), then + each followup request must populate this field with the + [response_id][google.maps.addressvalidation.v1.ValidateAddressResponse.response_id] + from the very first response in the validation sequence. + enable_usps_cass (bool): + Enables USPS CASS compatible mode. This affects *only* the + [google.maps.addressvalidation.v1.ValidationResult.usps_data] + field of + [google.maps.addressvalidation.v1.ValidationResult]. Note: + for USPS CASS enabled requests for addresses in Puerto Rico, + a [google.type.PostalAddress.region_code] of the ``address`` + must be provided as "PR", or an + [google.type.PostalAddress.administrative_area] of the + ``address`` must be provided as "Puerto Rico" + (case-insensitive) or "PR". + + It's recommended to use a componentized ``address``, or + alternatively specify at least two + [google.type.PostalAddress.address_lines] where the first + line contains the street number and name and the second line + contains the city, state, and zip code. + 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 autocomplete 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). + + Note: Address Validation can only be used in sessions with + the Autocomplete (New) API, not the old Autocomplete API. + See + https://developers.google.com/maps/documentation/places/web-service/session-pricing + for more details. + """ + + address: postal_address_pb2.PostalAddress = proto.Field( + proto.MESSAGE, + number=1, + message=postal_address_pb2.PostalAddress, + ) + previous_response_id: str = proto.Field( + proto.STRING, + number=2, + ) + enable_usps_cass: bool = proto.Field( + proto.BOOL, + number=3, + ) + session_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ValidateAddressResponse(proto.Message): + r"""The response to an address validation request. + + Attributes: + result (google.maps.addressvalidation_v1.types.ValidationResult): + The result of the address validation. + response_id (str): + The UUID that identifies this response. If the address needs + to be re-validated, this UUID *must* accompany the new + request. + """ + + result: 'ValidationResult' = proto.Field( + proto.MESSAGE, + number=1, + message='ValidationResult', + ) + response_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ProvideValidationFeedbackRequest(proto.Message): + r"""The request for sending validation feedback. + + Attributes: + conclusion (google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest.ValidationConclusion): + Required. The outcome of the sequence of validation + attempts. + + If this field is set to + ``VALIDATION_CONCLUSION_UNSPECIFIED``, an + ``INVALID_ARGUMENT`` error will be returned. + response_id (str): + Required. The ID of the response that this feedback is for. + This should be the + [response_id][google.maps.addressvalidation.v1.ValidateAddressRequest.response_id] + from the first response in a series of address validation + attempts. + """ + class ValidationConclusion(proto.Enum): + r"""The possible final outcomes of the sequence of address + validation requests needed to validate an address. + + Values: + VALIDATION_CONCLUSION_UNSPECIFIED (0): + This value is unused. If the + ``ProvideValidationFeedbackRequest.conclusion`` field is set + to ``VALIDATION_CONCLUSION_UNSPECIFIED``, an + ``INVALID_ARGUMENT`` error will be returned. + VALIDATED_VERSION_USED (1): + The version of the address returned by the + Address Validation API was used for the + transaction. + USER_VERSION_USED (2): + The version of the address provided by the + user was used for the transaction + UNVALIDATED_VERSION_USED (3): + A version of the address that was entered + after the last validation attempt but that was + not re-validated was used for the transaction. + UNUSED (4): + The transaction was abandoned and the address + was not used. + """ + VALIDATION_CONCLUSION_UNSPECIFIED = 0 + VALIDATED_VERSION_USED = 1 + USER_VERSION_USED = 2 + UNVALIDATED_VERSION_USED = 3 + UNUSED = 4 + + conclusion: ValidationConclusion = proto.Field( + proto.ENUM, + number=1, + enum=ValidationConclusion, + ) + response_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ProvideValidationFeedbackResponse(proto.Message): + r"""The response for validation feedback. + + The response is empty if the feedback is sent successfully. + + """ + + +class ValidationResult(proto.Message): + r"""The result of validating an address. + + Attributes: + verdict (google.maps.addressvalidation_v1.types.Verdict): + Overall verdict flags + address (google.maps.addressvalidation_v1.types.Address): + Information about the address itself as + opposed to the geocode. + geocode (google.maps.addressvalidation_v1.types.Geocode): + Information about the location and place that + the address geocoded to. + metadata (google.maps.addressvalidation_v1.types.AddressMetadata): + Other information relevant to deliverability. ``metadata`` + is not guaranteed to be fully populated for every address + sent to the Address Validation API. + usps_data (google.maps.addressvalidation_v1.types.UspsData): + Extra deliverability flags provided by USPS. Only provided + in region ``US`` and ``PR``. + """ + + verdict: 'Verdict' = proto.Field( + proto.MESSAGE, + number=1, + message='Verdict', + ) + address: gma_address.Address = proto.Field( + proto.MESSAGE, + number=2, + message=gma_address.Address, + ) + geocode: gma_geocode.Geocode = proto.Field( + proto.MESSAGE, + number=3, + message=gma_geocode.Geocode, + ) + metadata: metadata_.AddressMetadata = proto.Field( + proto.MESSAGE, + number=4, + message=metadata_.AddressMetadata, + ) + usps_data: gma_usps_data.UspsData = proto.Field( + proto.MESSAGE, + number=5, + message=gma_usps_data.UspsData, + ) + + +class Verdict(proto.Message): + r"""High level overview of the address validation result and + geocode. + + Attributes: + input_granularity (google.maps.addressvalidation_v1.types.Verdict.Granularity): + The granularity of the **input** address. This is the result + of parsing the input address and does not give any + validation signals. For validation signals, refer to + ``validation_granularity`` below. + + For example, if the input address includes a specific + apartment number, then the ``input_granularity`` here will + be ``SUB_PREMISE``. If we cannot match the apartment number + in the databases or the apartment number is invalid, the + ``validation_granularity`` will likely be ``PREMISE`` or + below. + validation_granularity (google.maps.addressvalidation_v1.types.Verdict.Granularity): + The granularity level that the API can fully **validate** + the address to. For example, an ``validation_granularity`` + of ``PREMISE`` indicates all address components at the level + of ``PREMISE`` or more coarse can be validated. + + Per address component validation result can be found in + [google.maps.addressvalidation.v1.Address.address_components]. + geocode_granularity (google.maps.addressvalidation_v1.types.Verdict.Granularity): + Information about the granularity of the + [``geocode``][google.maps.addressvalidation.v1.ValidationResult.geocode]. + This can be understood as the semantic meaning of how coarse + or fine the geocoded location is. + + This can differ from the ``validation_granularity`` above + occasionally. For example, our database might record the + existence of an apartment number but do not have a precise + location for the apartment within a big apartment complex. + In that case, the ``validation_granularity`` will be + ``SUB_PREMISE`` but the ``geocode_granularity`` will be + ``PREMISE``. + address_complete (bool): + The address is considered complete if there are no + unresolved tokens, no unexpected or missing address + components. See + [``missing_component_types``][google.maps.addressvalidation.v1.Address.missing_component_types], + [``unresolved_tokens``][google.maps.addressvalidation.v1.Address.unresolved_tokens] + or + [``unexpected``][google.maps.addressvalidation.v1.AddressComponent.unexpected] + fields for more details. + has_unconfirmed_components (bool): + At least one address component cannot be categorized or + validated, see + [google.maps.addressvalidation.v1.Address.address_components] + for details. + has_inferred_components (bool): + At least one address component was inferred (added) that + wasn't in the input, see + [google.maps.addressvalidation.v1.Address.address_components] + for details. + has_replaced_components (bool): + At least one address component was replaced, see + [google.maps.addressvalidation.v1.Address.address_components] + for details. + """ + class Granularity(proto.Enum): + r"""The various granularities that an address or a geocode can have. + When used to indicate granularity for an *address*, these values + indicate with how fine a granularity the address identifies a + mailing destination. For example, an address such as "123 Main + Street, Redwood City, CA, 94061" identifies a ``PREMISE`` while + something like "Redwood City, CA, 94061" identifies a ``LOCALITY``. + However, if we are unable to find a geocode for "123 Main Street" in + Redwood City, the geocode returned might be of ``LOCALITY`` + granularity even though the address is more granular. + + Values: + GRANULARITY_UNSPECIFIED (0): + Default value. This value is unused. + SUB_PREMISE (1): + Below-building level result, such as an + apartment. + PREMISE (2): + Building-level result. + PREMISE_PROXIMITY (3): + A geocode that approximates the + building-level location of the address. + BLOCK (4): + The address or geocode indicates a block. + Only used in regions which have block-level + addressing, such as Japan. + ROUTE (5): + The geocode or address is granular to route, + such as a street, road, or highway. + OTHER (6): + All other granularities, which are bucketed + together since they are not deliverable. + """ + GRANULARITY_UNSPECIFIED = 0 + SUB_PREMISE = 1 + PREMISE = 2 + PREMISE_PROXIMITY = 3 + BLOCK = 4 + ROUTE = 5 + OTHER = 6 + + input_granularity: Granularity = proto.Field( + proto.ENUM, + number=1, + enum=Granularity, + ) + validation_granularity: Granularity = proto.Field( + proto.ENUM, + number=2, + enum=Granularity, + ) + geocode_granularity: Granularity = proto.Field( + proto.ENUM, + number=3, + enum=Granularity, + ) + address_complete: bool = proto.Field( + proto.BOOL, + number=4, + ) + has_unconfirmed_components: bool = proto.Field( + proto.BOOL, + number=5, + ) + has_inferred_components: bool = proto.Field( + proto.BOOL, + number=6, + ) + has_replaced_components: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/geocode.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/geocode.py new file mode 100644 index 000000000000..4e2d66b9ba63 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/geocode.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.addressvalidation.v1', + manifest={ + 'Geocode', + 'PlusCode', + }, +) + + +class Geocode(proto.Message): + r"""Contains information about the place the input was geocoded + to. + + Attributes: + location (google.type.latlng_pb2.LatLng): + The geocoded location of the input. + + Using place IDs is preferred over using + addresses, latitude/longitude coordinates, or + plus codes. Using coordinates when routing or + calculating driving directions will always + result in the point being snapped to the road + nearest to those coordinates. This may not be a + road that will quickly or safely lead to the + destination and may not be near an access point + to the property. Additionally, when a location + is reverse geocoded, there is no guarantee that + the returned address will match the original. + plus_code (google.maps.addressvalidation_v1.types.PlusCode): + The plus code corresponding to the ``location``. + bounds (google.geo.type.types.Viewport): + The bounds of the geocoded place. + feature_size_meters (float): + The size of the geocoded place, in meters. + This is another measure of the coarseness of the + geocoded location, but in physical size rather + than in semantic meaning. + place_id (str): + The PlaceID of the place this input geocodes to. + + For more information about Place IDs see + `here `__. + place_types (MutableSequence[str]): + The type(s) of place that the input geocoded to. For + example, ``['locality', 'political']``. The full list of + types can be found + `here `__. + """ + + location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + plus_code: 'PlusCode' = proto.Field( + proto.MESSAGE, + number=2, + message='PlusCode', + ) + bounds: viewport.Viewport = proto.Field( + proto.MESSAGE, + number=4, + message=viewport.Viewport, + ) + feature_size_meters: float = proto.Field( + proto.FLOAT, + number=5, + ) + place_id: str = proto.Field( + proto.STRING, + number=6, + ) + place_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +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, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/metadata_.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/metadata_.py new file mode 100644 index 000000000000..79a1779dd9f6 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/metadata_.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.addressvalidation.v1', + manifest={ + 'AddressMetadata', + }, +) + + +class AddressMetadata(proto.Message): + r"""The metadata for the address. ``metadata`` is not guaranteed to be + fully populated for every address sent to the Address Validation + API. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + business (bool): + Indicates that this is the address of a + business. If unset, indicates that the value is + unknown. + + This field is a member of `oneof`_ ``_business``. + po_box (bool): + Indicates that the address of a PO box. + If unset, indicates that the value is unknown. + + This field is a member of `oneof`_ ``_po_box``. + residential (bool): + Indicates that this is the address of a + residence. If unset, indicates that the value is + unknown. + + This field is a member of `oneof`_ ``_residential``. + """ + + business: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + po_box: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + residential: bool = proto.Field( + proto.BOOL, + number=6, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/usps_data.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/usps_data.py new file mode 100644 index 000000000000..5c99d6ab4462 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/usps_data.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.addressvalidation.v1', + manifest={ + 'UspsAddress', + 'UspsData', + }, +) + + +class UspsAddress(proto.Message): + r"""USPS representation of a US address. + + Attributes: + first_address_line (str): + First address line. + firm (str): + Firm name. + second_address_line (str): + Second address line. + urbanization (str): + Puerto Rican urbanization name. + city_state_zip_address_line (str): + City + state + postal code. + city (str): + City name. + state (str): + 2 letter state code. + zip_code (str): + Postal code e.g. 10009. + zip_code_extension (str): + 4-digit postal code extension e.g. 5023. + """ + + first_address_line: str = proto.Field( + proto.STRING, + number=1, + ) + firm: str = proto.Field( + proto.STRING, + number=2, + ) + second_address_line: str = proto.Field( + proto.STRING, + number=3, + ) + urbanization: str = proto.Field( + proto.STRING, + number=4, + ) + city_state_zip_address_line: str = proto.Field( + proto.STRING, + number=5, + ) + city: str = proto.Field( + proto.STRING, + number=6, + ) + state: str = proto.Field( + proto.STRING, + number=7, + ) + zip_code: str = proto.Field( + proto.STRING, + number=8, + ) + zip_code_extension: str = proto.Field( + proto.STRING, + number=9, + ) + + +class UspsData(proto.Message): + r"""The USPS data for the address. ``uspsData`` is not guaranteed to be + fully populated for every US or PR address sent to the Address + Validation API. It's recommended to integrate the backup address + fields in the response if you utilize uspsData as the primary part + of the response. + + Attributes: + standardized_address (google.maps.addressvalidation_v1.types.UspsAddress): + USPS standardized address. + delivery_point_code (str): + 2 digit delivery point code + delivery_point_check_digit (str): + The delivery point check digit. This number is added to the + end of the delivery_point_barcode for mechanically scanned + mail. Adding all the digits of the delivery_point_barcode, + delivery_point_check_digit, postal code, and ZIP+4 together + should yield a number divisible by 10. + dpv_confirmation (str): + The possible values for DPV confirmation. Returns a single + character or returns no value. + + - ``N``: Primary and any secondary number information + failed to DPV confirm. + - ``D``: Address was DPV confirmed for the primary number + only, and the secondary number information was missing. + - ``S``: Address was DPV confirmed for the primary number + only, and the secondary number information was present + but not confirmed. + - ``Y``: Address was DPV confirmed for primary and any + secondary numbers. + - Empty: If the response does not contain a + ``dpv_confirmation`` value, the address was not submitted + for DPV confirmation. + dpv_footnote (str): + The footnotes from delivery point validation. Multiple + footnotes may be strung together in the same string. + + - ``AA``: Input address matched to the ZIP+4 file + - ``A1``: Input address was not matched to the ZIP+4 file + - ``BB``: Matched to DPV (all components) + - ``CC``: Secondary number not matched and not required + - ``C1``: Secondary number not matched but required + - ``N1``: High-rise address missing secondary number + - ``M1``: Primary number missing + - ``M3``: Primary number invalid + - ``P1``: Input address PO, RR or HC box number missing + - ``P3``: Input address PO, RR, or HC Box number invalid + - ``F1``: Input address matched to a military address + - ``G1``: Input address matched to a general delivery + address + - ``U1``: Input address matched to a unique ZIP code + - ``PB``: Input address matched to PBSA record + - ``RR``: DPV confirmed address with PMB information + - ``R1``: DPV confirmed address without PMB information + - ``R7``: Carrier Route R777 or R779 record + - ``IA``: Informed Address identified + - ``TA``: Primary number matched by dropping a trailing + alpha + dpv_cmra (str): + Indicates if the address is a CMRA (Commercial Mail + Receiving Agency)--a private business receiving mail for + clients. Returns a single character. + + - ``Y``: The address is a CMRA + - ``N``: The address is not a CMRA + dpv_vacant (str): + Is this place vacant? Returns a single character. + + - ``Y``: The address is vacant + - ``N``: The address is not vacant + dpv_no_stat (str): + Is this a no stat address or an active address? No stat + addresses are ones which are not continuously occupied or + addresses that the USPS does not service. Returns a single + character. + + - ``Y``: The address is not active + - ``N``: The address is active + dpv_no_stat_reason_code (int): + Indicates the NoStat type. Returns a reason code as int. + + - ``1``: IDA (Internal Drop Address) – Addresses that do + not receive mail directly from the USPS but are delivered + to a drop address that services them. + - ``2``: CDS - Addresses that have not yet become + deliverable. For example, a new subdivision where lots + and primary numbers have been determined, but no + structure exists yet for occupancy. + - ``3``: Collision - Addresses that do not actually DPV + confirm. + - ``4``: CMZ (College, Military and Other Types) - ZIP + 4 + records USPS has incorporated into the data. + - ``5``: Regular - Indicates addresses not receiving + delivery and the addresses are not counted as possible + deliveries. + - ``6``: Secondary Required - The address requires + secondary information. + dpv_drop (str): + Flag indicates mail is delivered to a single receptable at a + site. Returns a single character. + + - ``Y``: The mail is delivered to a single receptable at a + site. + - ``N``: The mail is not delivered to a single receptable + at a site. + dpv_throwback (str): + Indicates that mail is not delivered to the street address. + Returns a single character. + + - ``Y``: The mail is not delivered to the street address. + - ``N``: The mail is delivered to the street address. + dpv_non_delivery_days (str): + Flag indicates mail delivery is not performed every day of + the week. Returns a single character. + + - ``Y``: The mail delivery is not performed every day of + the week. + - ``N``: No indication the mail delivery is not performed + every day of the week. + dpv_non_delivery_days_values (int): + Integer identifying non-delivery days. It can + be interrogated using bit flags: + + 0x40 – Sunday is a non-delivery day + 0x20 – Monday is a non-delivery day + 0x10 – Tuesday is a non-delivery day + 0x08 – Wednesday is a non-delivery day + 0x04 – Thursday is a non-delivery day + 0x02 – Friday is a non-delivery day + 0x01 – Saturday is a non-delivery day + dpv_no_secure_location (str): + Flag indicates door is accessible, but package will not be + left due to security concerns. Returns a single character. + + - ``Y``: The package will not be left due to security + concerns. + - ``N``: No indication the package will not be left due to + security concerns. + dpv_pbsa (str): + Indicates the address was matched to PBSA record. Returns a + single character. + + - ``Y``: The address was matched to PBSA record. + - ``N``: The address was not matched to PBSA record. + dpv_door_not_accessible (str): + Flag indicates addresses where USPS cannot knock on a door + to deliver mail. Returns a single character. + + - ``Y``: The door is not accessible. + - ``N``: No indication the door is not accessible. + dpv_enhanced_delivery_code (str): + Indicates that more than one DPV return code is valid for + the address. Returns a single character. + + - ``Y``: Address was DPV confirmed for primary and any + secondary numbers. + - ``N``: Primary and any secondary number information + failed to DPV confirm. + - ``S``: Address was DPV confirmed for the primary number + only, and the secondary number information was present by + not confirmed, or a single trailing alpha on a primary + number was dropped to make a DPV match and secondary + information required. + - ``D``: Address was DPV confirmed for the primary number + only, and the secondary number information was missing. + - ``R``: Address confirmed but assigned to phantom route + R777 and R779 and USPS delivery is not provided. + carrier_route (str): + The carrier route code. A four character code consisting of + a one letter prefix and a three digit route designator. + + Prefixes: + + - ``C``: Carrier route (or city route) + - ``R``: Rural route + - ``H``: Highway Contract Route + - ``B``: Post Office Box Section + - ``G``: General delivery unit + carrier_route_indicator (str): + Carrier route rate sort indicator. + ews_no_match (bool): + The delivery address is matchable, but the + EWS file indicates that an exact match will be + available soon. + post_office_city (str): + Main post office city. + post_office_state (str): + Main post office state. + abbreviated_city (str): + Abbreviated city. + fips_county_code (str): + FIPS county code. + county (str): + County name. + elot_number (str): + Enhanced Line of Travel (eLOT) number. + elot_flag (str): + eLOT Ascending/Descending Flag (A/D). + lacs_link_return_code (str): + LACSLink return code. + lacs_link_indicator (str): + LACSLink indicator. + po_box_only_postal_code (bool): + PO Box only postal code. + suitelink_footnote (str): + Footnotes from matching a street or highrise record to suite + information. If business name match is found, the secondary + number is returned. + + - ``A``: SuiteLink record match, business address improved. + - ``00``: No match, business address is not improved. + pmb_designator (str): + PMB (Private Mail Box) unit designator. + pmb_number (str): + PMB (Private Mail Box) number; + address_record_type (str): + Type of the address record that matches the input address. + + - ``F``: FIRM. This is a match to a Firm Record, which is + the finest level of match available for an address. + - ``G``: GENERAL DELIVERY. This is a match to a General + Delivery record. + - ``H``: BUILDING / APARTMENT. This is a match to a + Building or Apartment record. + - ``P``: POST OFFICE BOX. This is a match to a Post Office + Box. + - ``R``: RURAL ROUTE or HIGHWAY CONTRACT: This is a match + to either a Rural Route or a Highway Contract record, + both of which may have associated Box Number ranges. + - ``S``: STREET RECORD: This is a match to a Street record + containing a valid primary number range. + default_address (bool): + Indicator that a default address was found, + but more specific addresses exists. + error_message (str): + Error message for USPS data retrieval. This + is populated when USPS processing is suspended + because of the detection of artificially created + addresses. + + The USPS data fields might not be populated when + this error is present. + cass_processed (bool): + Indicator that the request has been CASS + processed. + """ + + standardized_address: 'UspsAddress' = proto.Field( + proto.MESSAGE, + number=1, + message='UspsAddress', + ) + delivery_point_code: str = proto.Field( + proto.STRING, + number=2, + ) + delivery_point_check_digit: str = proto.Field( + proto.STRING, + number=3, + ) + dpv_confirmation: str = proto.Field( + proto.STRING, + number=4, + ) + dpv_footnote: str = proto.Field( + proto.STRING, + number=5, + ) + dpv_cmra: str = proto.Field( + proto.STRING, + number=6, + ) + dpv_vacant: str = proto.Field( + proto.STRING, + number=7, + ) + dpv_no_stat: str = proto.Field( + proto.STRING, + number=8, + ) + dpv_no_stat_reason_code: int = proto.Field( + proto.INT32, + number=29, + ) + dpv_drop: str = proto.Field( + proto.STRING, + number=30, + ) + dpv_throwback: str = proto.Field( + proto.STRING, + number=31, + ) + dpv_non_delivery_days: str = proto.Field( + proto.STRING, + number=32, + ) + dpv_non_delivery_days_values: int = proto.Field( + proto.INT32, + number=33, + ) + dpv_no_secure_location: str = proto.Field( + proto.STRING, + number=34, + ) + dpv_pbsa: str = proto.Field( + proto.STRING, + number=35, + ) + dpv_door_not_accessible: str = proto.Field( + proto.STRING, + number=36, + ) + dpv_enhanced_delivery_code: str = proto.Field( + proto.STRING, + number=37, + ) + carrier_route: str = proto.Field( + proto.STRING, + number=9, + ) + carrier_route_indicator: str = proto.Field( + proto.STRING, + number=10, + ) + ews_no_match: bool = proto.Field( + proto.BOOL, + number=11, + ) + post_office_city: str = proto.Field( + proto.STRING, + number=12, + ) + post_office_state: str = proto.Field( + proto.STRING, + number=13, + ) + abbreviated_city: str = proto.Field( + proto.STRING, + number=14, + ) + fips_county_code: str = proto.Field( + proto.STRING, + number=15, + ) + county: str = proto.Field( + proto.STRING, + number=16, + ) + elot_number: str = proto.Field( + proto.STRING, + number=17, + ) + elot_flag: str = proto.Field( + proto.STRING, + number=18, + ) + lacs_link_return_code: str = proto.Field( + proto.STRING, + number=19, + ) + lacs_link_indicator: str = proto.Field( + proto.STRING, + number=20, + ) + po_box_only_postal_code: bool = proto.Field( + proto.BOOL, + number=21, + ) + suitelink_footnote: str = proto.Field( + proto.STRING, + number=22, + ) + pmb_designator: str = proto.Field( + proto.STRING, + number=23, + ) + pmb_number: str = proto.Field( + proto.STRING, + number=24, + ) + address_record_type: str = proto.Field( + proto.STRING, + number=25, + ) + default_address: bool = proto.Field( + proto.BOOL, + number=26, + ) + error_message: str = proto.Field( + proto.STRING, + number=27, + ) + cass_processed: bool = proto.Field( + proto.BOOL, + number=28, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/mypy.ini b/owl-bot-staging/google-maps-addressvalidation/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/noxfile.py b/owl-bot-staging/google-maps-addressvalidation/v1/noxfile.py new file mode 100644 index 000000000000..40d06dd046c5 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation' + +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/addressvalidation_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/addressvalidation_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-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py new file mode 100644 index 000000000000..5694fbaa5b87 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_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 ProvideValidationFeedback +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-addressvalidation + + +# [START addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 addressvalidation_v1 + + +async def sample_provide_validation_feedback(): + # Create a client + client = addressvalidation_v1.AddressValidationAsyncClient() + + # Initialize request argument(s) + request = addressvalidation_v1.ProvideValidationFeedbackRequest( + conclusion="UNUSED", + response_id="response_id_value", + ) + + # Make the request + response = await client.provide_validation_feedback(request=request) + + # Handle the response + print(response) + +# [END addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_async] diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py new file mode 100644 index 000000000000..a1611f9bfaba --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_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 ProvideValidationFeedback +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-addressvalidation + + +# [START addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 addressvalidation_v1 + + +def sample_provide_validation_feedback(): + # Create a client + client = addressvalidation_v1.AddressValidationClient() + + # Initialize request argument(s) + request = addressvalidation_v1.ProvideValidationFeedbackRequest( + conclusion="UNUSED", + response_id="response_id_value", + ) + + # Make the request + response = client.provide_validation_feedback(request=request) + + # Handle the response + print(response) + +# [END addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_sync] diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_async.py b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_async.py new file mode 100644 index 000000000000..19457cbd1d8e --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_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 ValidateAddress +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-addressvalidation + + +# [START addressvalidation_v1_generated_AddressValidation_ValidateAddress_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 addressvalidation_v1 + + +async def sample_validate_address(): + # Create a client + client = addressvalidation_v1.AddressValidationAsyncClient() + + # Initialize request argument(s) + request = addressvalidation_v1.ValidateAddressRequest( + ) + + # Make the request + response = await client.validate_address(request=request) + + # Handle the response + print(response) + +# [END addressvalidation_v1_generated_AddressValidation_ValidateAddress_async] diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_sync.py b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_sync.py new file mode 100644 index 000000000000..361e727d5bff --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_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 ValidateAddress +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-addressvalidation + + +# [START addressvalidation_v1_generated_AddressValidation_ValidateAddress_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 addressvalidation_v1 + + +def sample_validate_address(): + # Create a client + client = addressvalidation_v1.AddressValidationClient() + + # Initialize request argument(s) + request = addressvalidation_v1.ValidateAddressRequest( + ) + + # Make the request + response = client.validate_address(request=request) + + # Handle the response + print(response) + +# [END addressvalidation_v1_generated_AddressValidation_ValidateAddress_sync] diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json new file mode 100644 index 000000000000..b8aeda3afd23 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.addressvalidation.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-addressvalidation", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.addressvalidation_v1.AddressValidationAsyncClient", + "shortName": "AddressValidationAsyncClient" + }, + "fullName": "google.maps.addressvalidation_v1.AddressValidationAsyncClient.provide_validation_feedback", + "method": { + "fullName": "google.maps.addressvalidation.v1.AddressValidation.ProvideValidationFeedback", + "service": { + "fullName": "google.maps.addressvalidation.v1.AddressValidation", + "shortName": "AddressValidation" + }, + "shortName": "ProvideValidationFeedback" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.addressvalidation_v1.types.ProvideValidationFeedbackResponse", + "shortName": "provide_validation_feedback" + }, + "description": "Sample for ProvideValidationFeedback", + "file": "addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_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": "addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.addressvalidation_v1.AddressValidationClient", + "shortName": "AddressValidationClient" + }, + "fullName": "google.maps.addressvalidation_v1.AddressValidationClient.provide_validation_feedback", + "method": { + "fullName": "google.maps.addressvalidation.v1.AddressValidation.ProvideValidationFeedback", + "service": { + "fullName": "google.maps.addressvalidation.v1.AddressValidation", + "shortName": "AddressValidation" + }, + "shortName": "ProvideValidationFeedback" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.addressvalidation_v1.types.ProvideValidationFeedbackResponse", + "shortName": "provide_validation_feedback" + }, + "description": "Sample for ProvideValidationFeedback", + "file": "addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_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": "addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.addressvalidation_v1.AddressValidationAsyncClient", + "shortName": "AddressValidationAsyncClient" + }, + "fullName": "google.maps.addressvalidation_v1.AddressValidationAsyncClient.validate_address", + "method": { + "fullName": "google.maps.addressvalidation.v1.AddressValidation.ValidateAddress", + "service": { + "fullName": "google.maps.addressvalidation.v1.AddressValidation", + "shortName": "AddressValidation" + }, + "shortName": "ValidateAddress" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.addressvalidation_v1.types.ValidateAddressRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.addressvalidation_v1.types.ValidateAddressResponse", + "shortName": "validate_address" + }, + "description": "Sample for ValidateAddress", + "file": "addressvalidation_v1_generated_address_validation_validate_address_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "addressvalidation_v1_generated_AddressValidation_ValidateAddress_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": "addressvalidation_v1_generated_address_validation_validate_address_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.addressvalidation_v1.AddressValidationClient", + "shortName": "AddressValidationClient" + }, + "fullName": "google.maps.addressvalidation_v1.AddressValidationClient.validate_address", + "method": { + "fullName": "google.maps.addressvalidation.v1.AddressValidation.ValidateAddress", + "service": { + "fullName": "google.maps.addressvalidation.v1.AddressValidation", + "shortName": "AddressValidation" + }, + "shortName": "ValidateAddress" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.addressvalidation_v1.types.ValidateAddressRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.addressvalidation_v1.types.ValidateAddressResponse", + "shortName": "validate_address" + }, + "description": "Sample for ValidateAddress", + "file": "addressvalidation_v1_generated_address_validation_validate_address_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "addressvalidation_v1_generated_AddressValidation_ValidateAddress_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": "addressvalidation_v1_generated_address_validation_validate_address_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/scripts/fixup_addressvalidation_v1_keywords.py b/owl-bot-staging/google-maps-addressvalidation/v1/scripts/fixup_addressvalidation_v1_keywords.py new file mode 100644 index 000000000000..4dfe232a0943 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/scripts/fixup_addressvalidation_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 addressvalidationCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'provide_validation_feedback': ('conclusion', 'response_id', ), + 'validate_address': ('address', 'previous_response_id', 'enable_usps_cass', 'session_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=addressvalidationCallTransformer(), +): + """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 addressvalidation 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-addressvalidation/v1/setup.py b/owl-bot-staging/google-maps-addressvalidation/v1/setup.py new file mode 100644 index 000000000000..c24c77e55e90 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation' + + +description = "Google Maps Addressvalidation API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/addressvalidation/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-addressvalidation" + +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-addressvalidation/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..277853c664a0 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/tests/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_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-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/test_address_validation.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/test_address_validation.py new file mode 100644 index 000000000000..54ae9e6c5b4d --- /dev/null +++ b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/test_address_validation.py @@ -0,0 +1,2364 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.addressvalidation_v1.services.address_validation import AddressValidationAsyncClient +from google.maps.addressvalidation_v1.services.address_validation import AddressValidationClient +from google.maps.addressvalidation_v1.services.address_validation import transports +from google.maps.addressvalidation_v1.types import address_validation_service +from google.oauth2 import service_account +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 AddressValidationClient._get_default_mtls_endpoint(None) is None + assert AddressValidationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AddressValidationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AddressValidationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AddressValidationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AddressValidationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AddressValidationClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AddressValidationClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AddressValidationClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AddressValidationClient._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 AddressValidationClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AddressValidationClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AddressValidationClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AddressValidationClient._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 AddressValidationClient._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 AddressValidationClient._get_client_cert_source(None, False) is None + assert AddressValidationClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AddressValidationClient._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 AddressValidationClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AddressValidationClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AddressValidationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationClient)) +@mock.patch.object(AddressValidationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AddressValidationClient._DEFAULT_UNIVERSE + default_endpoint = AddressValidationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AddressValidationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AddressValidationClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AddressValidationClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AddressValidationClient.DEFAULT_MTLS_ENDPOINT + assert AddressValidationClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AddressValidationClient._get_api_endpoint(None, None, default_universe, "always") == AddressValidationClient.DEFAULT_MTLS_ENDPOINT + assert AddressValidationClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AddressValidationClient.DEFAULT_MTLS_ENDPOINT + assert AddressValidationClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AddressValidationClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AddressValidationClient._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 AddressValidationClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AddressValidationClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AddressValidationClient._get_universe_domain(None, None) == AddressValidationClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AddressValidationClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc"), + (AddressValidationClient, transports.AddressValidationRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AddressValidationClient, "grpc"), + (AddressValidationAsyncClient, "grpc_asyncio"), + (AddressValidationClient, "rest"), +]) +def test_address_validation_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 == ( + 'addressvalidation.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://addressvalidation.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AddressValidationGrpcTransport, "grpc"), + (transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AddressValidationRestTransport, "rest"), +]) +def test_address_validation_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", [ + (AddressValidationClient, "grpc"), + (AddressValidationAsyncClient, "grpc_asyncio"), + (AddressValidationClient, "rest"), +]) +def test_address_validation_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 == ( + 'addressvalidation.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://addressvalidation.googleapis.com' + ) + + +def test_address_validation_client_get_transport_class(): + transport = AddressValidationClient.get_transport_class() + available_transports = [ + transports.AddressValidationGrpcTransport, + transports.AddressValidationRestTransport, + ] + assert transport in available_transports + + transport = AddressValidationClient.get_transport_class("grpc") + assert transport == transports.AddressValidationGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc"), + (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio"), + (AddressValidationClient, transports.AddressValidationRestTransport, "rest"), +]) +@mock.patch.object(AddressValidationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationClient)) +@mock.patch.object(AddressValidationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationAsyncClient)) +def test_address_validation_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(AddressValidationClient, '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(AddressValidationClient, '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", [ + (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc", "true"), + (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc", "false"), + (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AddressValidationClient, transports.AddressValidationRestTransport, "rest", "true"), + (AddressValidationClient, transports.AddressValidationRestTransport, "rest", "false"), +]) +@mock.patch.object(AddressValidationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationClient)) +@mock.patch.object(AddressValidationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_address_validation_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", [ + AddressValidationClient, AddressValidationAsyncClient +]) +@mock.patch.object(AddressValidationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AddressValidationClient)) +@mock.patch.object(AddressValidationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AddressValidationAsyncClient)) +def test_address_validation_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", [ + AddressValidationClient, AddressValidationAsyncClient +]) +@mock.patch.object(AddressValidationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationClient)) +@mock.patch.object(AddressValidationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationAsyncClient)) +def test_address_validation_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AddressValidationClient._DEFAULT_UNIVERSE + default_endpoint = AddressValidationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AddressValidationClient._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", [ + (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc"), + (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio"), + (AddressValidationClient, transports.AddressValidationRestTransport, "rest"), +]) +def test_address_validation_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", [ + (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc", grpc_helpers), + (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AddressValidationClient, transports.AddressValidationRestTransport, "rest", None), +]) +def test_address_validation_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_address_validation_client_client_options_from_dict(): + with mock.patch('google.maps.addressvalidation_v1.services.address_validation.transports.AddressValidationGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AddressValidationClient( + 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", [ + (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc", grpc_helpers), + (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_address_validation_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( + "addressvalidation.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="addressvalidation.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + address_validation_service.ValidateAddressRequest, + dict, +]) +def test_validate_address(request_type, transport: str = 'grpc'): + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_address), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_validation_service.ValidateAddressResponse( + response_id='response_id_value', + ) + response = client.validate_address(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = address_validation_service.ValidateAddressRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, address_validation_service.ValidateAddressResponse) + assert response.response_id == 'response_id_value' + + +def test_validate_address_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = address_validation_service.ValidateAddressRequest( + previous_response_id='previous_response_id_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.validate_address), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.validate_address(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == address_validation_service.ValidateAddressRequest( + previous_response_id='previous_response_id_value', + session_token='session_token_value', + ) + +def test_validate_address_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.validate_address in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.validate_address] = mock_rpc + request = {} + client.validate_address(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.validate_address(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_validate_address_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressValidationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.validate_address in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.validate_address] = mock_rpc + + request = {} + await client.validate_address(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.validate_address(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_validate_address_async(transport: str = 'grpc_asyncio', request_type=address_validation_service.ValidateAddressRequest): + client = AddressValidationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_address), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_validation_service.ValidateAddressResponse( + response_id='response_id_value', + )) + response = await client.validate_address(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = address_validation_service.ValidateAddressRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, address_validation_service.ValidateAddressResponse) + assert response.response_id == 'response_id_value' + + +@pytest.mark.asyncio +async def test_validate_address_async_from_dict(): + await test_validate_address_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + address_validation_service.ProvideValidationFeedbackRequest, + dict, +]) +def test_provide_validation_feedback(request_type, transport: str = 'grpc'): + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provide_validation_feedback), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_validation_service.ProvideValidationFeedbackResponse( + ) + response = client.provide_validation_feedback(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = address_validation_service.ProvideValidationFeedbackRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, address_validation_service.ProvideValidationFeedbackResponse) + + +def test_provide_validation_feedback_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = address_validation_service.ProvideValidationFeedbackRequest( + response_id='response_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provide_validation_feedback), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.provide_validation_feedback(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == address_validation_service.ProvideValidationFeedbackRequest( + response_id='response_id_value', + ) + +def test_provide_validation_feedback_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.provide_validation_feedback in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.provide_validation_feedback] = mock_rpc + request = {} + client.provide_validation_feedback(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provide_validation_feedback(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_provide_validation_feedback_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressValidationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.provide_validation_feedback in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.provide_validation_feedback] = mock_rpc + + request = {} + await client.provide_validation_feedback(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.provide_validation_feedback(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_provide_validation_feedback_async(transport: str = 'grpc_asyncio', request_type=address_validation_service.ProvideValidationFeedbackRequest): + client = AddressValidationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provide_validation_feedback), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_validation_service.ProvideValidationFeedbackResponse( + )) + response = await client.provide_validation_feedback(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = address_validation_service.ProvideValidationFeedbackRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, address_validation_service.ProvideValidationFeedbackResponse) + + +@pytest.mark.asyncio +async def test_provide_validation_feedback_async_from_dict(): + await test_provide_validation_feedback_async(request_type=dict) + + +def test_validate_address_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.validate_address in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.validate_address] = mock_rpc + + request = {} + client.validate_address(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.validate_address(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_validate_address_rest_required_fields(request_type=address_validation_service.ValidateAddressRequest): + transport_class = transports.AddressValidationRestTransport + + 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()).validate_address._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()).validate_address._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = address_validation_service.ValidateAddressResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = address_validation_service.ValidateAddressResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.validate_address(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_validate_address_rest_unset_required_fields(): + transport = transports.AddressValidationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.validate_address._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("address", ))) + + +def test_provide_validation_feedback_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.provide_validation_feedback in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.provide_validation_feedback] = mock_rpc + + request = {} + client.provide_validation_feedback(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provide_validation_feedback(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_provide_validation_feedback_rest_required_fields(request_type=address_validation_service.ProvideValidationFeedbackRequest): + transport_class = transports.AddressValidationRestTransport + + request_init = {} + request_init["response_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).provide_validation_feedback._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["responseId"] = 'response_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).provide_validation_feedback._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "responseId" in jsonified_request + assert jsonified_request["responseId"] == 'response_id_value' + + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = address_validation_service.ProvideValidationFeedbackResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = address_validation_service.ProvideValidationFeedbackResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.provide_validation_feedback(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_provide_validation_feedback_rest_unset_required_fields(): + transport = transports.AddressValidationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.provide_validation_feedback._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("conclusion", "responseId", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AddressValidationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AddressValidationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AddressValidationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AddressValidationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AddressValidationClient( + 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 = AddressValidationClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AddressValidationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AddressValidationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AddressValidationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AddressValidationClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AddressValidationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AddressValidationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AddressValidationGrpcTransport, + transports.AddressValidationGrpcAsyncIOTransport, + transports.AddressValidationRestTransport, +]) +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 = AddressValidationClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AddressValidationClient( + 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_validate_address_empty_call_grpc(): + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.validate_address), + '__call__') as call: + call.return_value = address_validation_service.ValidateAddressResponse() + client.validate_address(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_validation_service.ValidateAddressRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_provide_validation_feedback_empty_call_grpc(): + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.provide_validation_feedback), + '__call__') as call: + call.return_value = address_validation_service.ProvideValidationFeedbackResponse() + client.provide_validation_feedback(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_validation_service.ProvideValidationFeedbackRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AddressValidationAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AddressValidationAsyncClient( + 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_validate_address_empty_call_grpc_asyncio(): + client = AddressValidationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.validate_address), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_validation_service.ValidateAddressResponse( + response_id='response_id_value', + )) + await client.validate_address(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_validation_service.ValidateAddressRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_provide_validation_feedback_empty_call_grpc_asyncio(): + client = AddressValidationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.provide_validation_feedback), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_validation_service.ProvideValidationFeedbackResponse( + )) + await client.provide_validation_feedback(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_validation_service.ProvideValidationFeedbackRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AddressValidationClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_validate_address_rest_bad_request(request_type=address_validation_service.ValidateAddressRequest): + client = AddressValidationClient( + 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 + client.validate_address(request) + + +@pytest.mark.parametrize("request_type", [ + address_validation_service.ValidateAddressRequest, + dict, +]) +def test_validate_address_rest_call_success(request_type): + client = AddressValidationClient( + 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 = address_validation_service.ValidateAddressResponse( + response_id='response_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_validation_service.ValidateAddressResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.validate_address(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, address_validation_service.ValidateAddressResponse) + assert response.response_id == 'response_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_validate_address_rest_interceptors(null_interceptor): + transport = transports.AddressValidationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressValidationRestInterceptor(), + ) + client = AddressValidationClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AddressValidationRestInterceptor, "post_validate_address") as post, \ + mock.patch.object(transports.AddressValidationRestInterceptor, "pre_validate_address") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = address_validation_service.ValidateAddressRequest.pb(address_validation_service.ValidateAddressRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = address_validation_service.ValidateAddressResponse.to_json(address_validation_service.ValidateAddressResponse()) + req.return_value.content = return_value + + request = address_validation_service.ValidateAddressRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = address_validation_service.ValidateAddressResponse() + + client.validate_address(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_provide_validation_feedback_rest_bad_request(request_type=address_validation_service.ProvideValidationFeedbackRequest): + client = AddressValidationClient( + 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 + client.provide_validation_feedback(request) + + +@pytest.mark.parametrize("request_type", [ + address_validation_service.ProvideValidationFeedbackRequest, + dict, +]) +def test_provide_validation_feedback_rest_call_success(request_type): + client = AddressValidationClient( + 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 = address_validation_service.ProvideValidationFeedbackResponse( + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_validation_service.ProvideValidationFeedbackResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.provide_validation_feedback(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, address_validation_service.ProvideValidationFeedbackResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_provide_validation_feedback_rest_interceptors(null_interceptor): + transport = transports.AddressValidationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressValidationRestInterceptor(), + ) + client = AddressValidationClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AddressValidationRestInterceptor, "post_provide_validation_feedback") as post, \ + mock.patch.object(transports.AddressValidationRestInterceptor, "pre_provide_validation_feedback") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = address_validation_service.ProvideValidationFeedbackRequest.pb(address_validation_service.ProvideValidationFeedbackRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = address_validation_service.ProvideValidationFeedbackResponse.to_json(address_validation_service.ProvideValidationFeedbackResponse()) + req.return_value.content = return_value + + request = address_validation_service.ProvideValidationFeedbackRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = address_validation_service.ProvideValidationFeedbackResponse() + + client.provide_validation_feedback(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = AddressValidationClient( + 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_validate_address_empty_call_rest(): + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.validate_address), + '__call__') as call: + client.validate_address(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_validation_service.ValidateAddressRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_provide_validation_feedback_empty_call_rest(): + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.provide_validation_feedback), + '__call__') as call: + client.provide_validation_feedback(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_validation_service.ProvideValidationFeedbackRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AddressValidationGrpcTransport, + ) + +def test_address_validation_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AddressValidationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_address_validation_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.addressvalidation_v1.services.address_validation.transports.AddressValidationTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AddressValidationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'validate_address', + 'provide_validation_feedback', + ) + 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_address_validation_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.addressvalidation_v1.services.address_validation.transports.AddressValidationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AddressValidationTransport( + 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_address_validation_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.addressvalidation_v1.services.address_validation.transports.AddressValidationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AddressValidationTransport() + adc.assert_called_once() + + +def test_address_validation_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) + AddressValidationClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AddressValidationGrpcTransport, + transports.AddressValidationGrpcAsyncIOTransport, + ], +) +def test_address_validation_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.AddressValidationGrpcTransport, + transports.AddressValidationGrpcAsyncIOTransport, + transports.AddressValidationRestTransport, + ], +) +def test_address_validation_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.AddressValidationGrpcTransport, grpc_helpers), + (transports.AddressValidationGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_address_validation_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( + "addressvalidation.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="addressvalidation.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AddressValidationGrpcTransport, transports.AddressValidationGrpcAsyncIOTransport]) +def test_address_validation_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_address_validation_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.AddressValidationRestTransport ( + 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_address_validation_host_no_port(transport_name): + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='addressvalidation.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'addressvalidation.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://addressvalidation.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_address_validation_host_with_port(transport_name): + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='addressvalidation.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'addressvalidation.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://addressvalidation.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_address_validation_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AddressValidationClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AddressValidationClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.validate_address._session + session2 = client2.transport.validate_address._session + assert session1 != session2 + session1 = client1.transport.provide_validation_feedback._session + session2 = client2.transport.provide_validation_feedback._session + assert session1 != session2 +def test_address_validation_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AddressValidationGrpcTransport( + 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_address_validation_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AddressValidationGrpcAsyncIOTransport( + 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.AddressValidationGrpcTransport, transports.AddressValidationGrpcAsyncIOTransport]) +def test_address_validation_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.AddressValidationGrpcTransport, transports.AddressValidationGrpcAsyncIOTransport]) +def test_address_validation_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 = AddressValidationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AddressValidationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AddressValidationClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AddressValidationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AddressValidationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AddressValidationClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AddressValidationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AddressValidationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AddressValidationClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AddressValidationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AddressValidationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AddressValidationClient.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 = AddressValidationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AddressValidationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AddressValidationClient.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.AddressValidationTransport, '_prep_wrapped_messages') as prep: + client = AddressValidationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AddressValidationTransport, '_prep_wrapped_messages') as prep: + transport_class = AddressValidationClient.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 = AddressValidationClient( + 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 = AddressValidationAsyncClient( + 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 = AddressValidationClient( + 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 = AddressValidationClient( + 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", [ + (AddressValidationClient, transports.AddressValidationGrpcTransport), + (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport), +]) +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-areainsights/v1/.coveragerc b/owl-bot-staging/google-maps-areainsights/v1/.coveragerc new file mode 100644 index 000000000000..612fd0382a68 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/areainsights/__init__.py + google/maps/areainsights/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-areainsights/v1/.flake8 b/owl-bot-staging/google-maps-areainsights/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/MANIFEST.in b/owl-bot-staging/google-maps-areainsights/v1/MANIFEST.in new file mode 100644 index 000000000000..6f1322254e3a --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/areainsights *.py +recursive-include google/maps/areainsights_v1 *.py diff --git a/owl-bot-staging/google-maps-areainsights/v1/README.rst b/owl-bot-staging/google-maps-areainsights/v1/README.rst new file mode 100644 index 000000000000..85225fe6e116 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Areainsights 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 Areainsights 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-areainsights/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-areainsights/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/area_insights.rst b/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/area_insights.rst new file mode 100644 index 000000000000..78835e4cf335 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/area_insights.rst @@ -0,0 +1,6 @@ +AreaInsights +------------------------------ + +.. automodule:: google.maps.areainsights_v1.services.area_insights + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/services_.rst b/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/services_.rst new file mode 100644 index 000000000000..54fbea792518 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Areainsights v1 API +============================================ +.. toctree:: + :maxdepth: 2 + + area_insights diff --git a/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/types_.rst b/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/types_.rst new file mode 100644 index 000000000000..4774a4b375c1 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Areainsights v1 API +========================================= + +.. automodule:: google.maps.areainsights_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-areainsights/v1/docs/conf.py b/owl-bot-staging/google-maps-areainsights/v1/docs/conf.py new file mode 100644 index 000000000000..c2b8f89658a8 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights 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-areainsights" +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-areainsights-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-areainsights.tex", + u"google-maps-areainsights 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-areainsights", + u"Google Maps Areainsights 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-areainsights", + u"google-maps-areainsights Documentation", + author, + "google-maps-areainsights", + "GAPIC library for Google Maps Areainsights 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-areainsights/v1/docs/index.rst b/owl-bot-staging/google-maps-areainsights/v1/docs/index.rst new file mode 100644 index 000000000000..2371f3c41e8a --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + areainsights_v1/services_ + areainsights_v1/types_ diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/__init__.py new file mode 100644 index 000000000000..155569990ce6 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/__init__.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 google.maps.areainsights import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.areainsights_v1.services.area_insights.client import AreaInsightsClient +from google.maps.areainsights_v1.services.area_insights.async_client import AreaInsightsAsyncClient + +from google.maps.areainsights_v1.types.area_insights_service import ComputeInsightsRequest +from google.maps.areainsights_v1.types.area_insights_service import ComputeInsightsResponse +from google.maps.areainsights_v1.types.area_insights_service import Filter +from google.maps.areainsights_v1.types.area_insights_service import LocationFilter +from google.maps.areainsights_v1.types.area_insights_service import PlaceInsight +from google.maps.areainsights_v1.types.area_insights_service import RatingFilter +from google.maps.areainsights_v1.types.area_insights_service import TypeFilter +from google.maps.areainsights_v1.types.area_insights_service import Insight +from google.maps.areainsights_v1.types.area_insights_service import OperatingStatus +from google.maps.areainsights_v1.types.area_insights_service import PriceLevel + +__all__ = ('AreaInsightsClient', + 'AreaInsightsAsyncClient', + 'ComputeInsightsRequest', + 'ComputeInsightsResponse', + 'Filter', + 'LocationFilter', + 'PlaceInsight', + 'RatingFilter', + 'TypeFilter', + 'Insight', + 'OperatingStatus', + 'PriceLevel', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/gapic_version.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/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-areainsights/v1/google/maps/areainsights/py.typed b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/py.typed new file mode 100644 index 000000000000..b098dc9b9f40 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-areainsights package uses inline types. diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/__init__.py new file mode 100644 index 000000000000..0b2859bdd2ca --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/__init__.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.areainsights_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.area_insights import AreaInsightsClient +from .services.area_insights import AreaInsightsAsyncClient + +from .types.area_insights_service import ComputeInsightsRequest +from .types.area_insights_service import ComputeInsightsResponse +from .types.area_insights_service import Filter +from .types.area_insights_service import LocationFilter +from .types.area_insights_service import PlaceInsight +from .types.area_insights_service import RatingFilter +from .types.area_insights_service import TypeFilter +from .types.area_insights_service import Insight +from .types.area_insights_service import OperatingStatus +from .types.area_insights_service import PriceLevel + +__all__ = ( + 'AreaInsightsAsyncClient', +'AreaInsightsClient', +'ComputeInsightsRequest', +'ComputeInsightsResponse', +'Filter', +'Insight', +'LocationFilter', +'OperatingStatus', +'PlaceInsight', +'PriceLevel', +'RatingFilter', +'TypeFilter', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_metadata.json b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_metadata.json new file mode 100644 index 000000000000..413146689761 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_metadata.json @@ -0,0 +1,43 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.areainsights_v1", + "protoPackage": "google.maps.areainsights.v1", + "schema": "1.0", + "services": { + "AreaInsights": { + "clients": { + "grpc": { + "libraryClient": "AreaInsightsClient", + "rpcs": { + "ComputeInsights": { + "methods": [ + "compute_insights" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AreaInsightsAsyncClient", + "rpcs": { + "ComputeInsights": { + "methods": [ + "compute_insights" + ] + } + } + }, + "rest": { + "libraryClient": "AreaInsightsClient", + "rpcs": { + "ComputeInsights": { + "methods": [ + "compute_insights" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_version.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_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-areainsights/v1/google/maps/areainsights_v1/py.typed b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/py.typed new file mode 100644 index 000000000000..b098dc9b9f40 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-areainsights package uses inline types. diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_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-areainsights/v1/google/maps/areainsights_v1/services/area_insights/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/__init__.py new file mode 100644 index 000000000000..39f60ebeeb2e --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/__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 AreaInsightsClient +from .async_client import AreaInsightsAsyncClient + +__all__ = ( + 'AreaInsightsClient', + 'AreaInsightsAsyncClient', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/async_client.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/async_client.py new file mode 100644 index 000000000000..9722e6501448 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/async_client.py @@ -0,0 +1,321 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.maps.areainsights_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.areainsights_v1.types import area_insights_service +from .transports.base import AreaInsightsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AreaInsightsGrpcAsyncIOTransport +from .client import AreaInsightsClient + + +class AreaInsightsAsyncClient: + """Service definition for the Places Insights API.""" + + _client: AreaInsightsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AreaInsightsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AreaInsightsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AreaInsightsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AreaInsightsClient._DEFAULT_UNIVERSE + + place_path = staticmethod(AreaInsightsClient.place_path) + parse_place_path = staticmethod(AreaInsightsClient.parse_place_path) + common_billing_account_path = staticmethod(AreaInsightsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AreaInsightsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AreaInsightsClient.common_folder_path) + parse_common_folder_path = staticmethod(AreaInsightsClient.parse_common_folder_path) + common_organization_path = staticmethod(AreaInsightsClient.common_organization_path) + parse_common_organization_path = staticmethod(AreaInsightsClient.parse_common_organization_path) + common_project_path = staticmethod(AreaInsightsClient.common_project_path) + parse_common_project_path = staticmethod(AreaInsightsClient.parse_common_project_path) + common_location_path = staticmethod(AreaInsightsClient.common_location_path) + parse_common_location_path = staticmethod(AreaInsightsClient.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: + AreaInsightsAsyncClient: The constructed client. + """ + return AreaInsightsClient.from_service_account_info.__func__(AreaInsightsAsyncClient, 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: + AreaInsightsAsyncClient: The constructed client. + """ + return AreaInsightsClient.from_service_account_file.__func__(AreaInsightsAsyncClient, 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 AreaInsightsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AreaInsightsTransport: + """Returns the transport used by the client instance. + + Returns: + AreaInsightsTransport: 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 = AreaInsightsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AreaInsightsTransport, Callable[..., AreaInsightsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the area insights 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,AreaInsightsTransport,Callable[..., AreaInsightsTransport]]]): + 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 AreaInsightsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = AreaInsightsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def compute_insights(self, + request: Optional[Union[area_insights_service.ComputeInsightsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> area_insights_service.ComputeInsightsResponse: + r"""Compute Insights RPC + + This method lets you retrieve insights about areas using a + variaty of filter such as: area, place type, operating status, + price level and ratings. Currently "count" and "places" insights + are supported. With "count" insights you can answer questions + such as "How many restaurant are located in California that are + operational, are inexpensive and have an average rating of at + least 4 stars" (see ``insight`` enum for more details). With + "places" insights, you can determine which places match the + requested filter. Clients can then use those place resource + names to fetch more details about each individual place using + the Places API. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 areainsights_v1 + + async def sample_compute_insights(): + # Create a client + client = areainsights_v1.AreaInsightsAsyncClient() + + # Initialize request argument(s) + request = areainsights_v1.ComputeInsightsRequest( + insights=['INSIGHT_PLACES'], + ) + + # Make the request + response = await client.compute_insights(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.areainsights_v1.types.ComputeInsightsRequest, dict]]): + The request object. Request for the ComputeInsights RPC. + retry (google.api_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. + + Returns: + google.maps.areainsights_v1.types.ComputeInsightsResponse: + Response for the ComputeInsights RPC. + """ + # 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, area_insights_service.ComputeInsightsRequest): + request = area_insights_service.ComputeInsightsRequest(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_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 __aenter__(self) -> "AreaInsightsAsyncClient": + 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__ = ( + "AreaInsightsAsyncClient", +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/client.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/client.py new file mode 100644 index 000000000000..dd9e11628f77 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/client.py @@ -0,0 +1,678 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.maps.areainsights_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 + +from google.maps.areainsights_v1.types import area_insights_service +from .transports.base import AreaInsightsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AreaInsightsGrpcTransport +from .transports.grpc_asyncio import AreaInsightsGrpcAsyncIOTransport +from .transports.rest import AreaInsightsRestTransport + + +class AreaInsightsClientMeta(type): + """Metaclass for the AreaInsights 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[AreaInsightsTransport]] + _transport_registry["grpc"] = AreaInsightsGrpcTransport + _transport_registry["grpc_asyncio"] = AreaInsightsGrpcAsyncIOTransport + _transport_registry["rest"] = AreaInsightsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AreaInsightsTransport]: + """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 AreaInsightsClient(metaclass=AreaInsightsClientMeta): + """Service definition for the Places Insights 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 = "areainsights.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "areainsights.{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: + AreaInsightsClient: 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: + AreaInsightsClient: 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) -> AreaInsightsTransport: + """Returns the transport used by the client instance. + + Returns: + AreaInsightsTransport: The transport used by the client + instance. + """ + return self._transport + + @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 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 = AreaInsightsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AreaInsightsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AreaInsightsClient._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 = AreaInsightsClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = AreaInsightsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + AreaInsightsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, AreaInsightsTransport, Callable[..., AreaInsightsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the area insights client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AreaInsightsTransport,Callable[..., AreaInsightsTransport]]]): + 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 AreaInsightsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = AreaInsightsClient._read_environment_variables() + self._client_cert_source = AreaInsightsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AreaInsightsClient._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 + + 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, AreaInsightsTransport) + if transport_provided: + # transport is a AreaInsightsTransport 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(AreaInsightsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AreaInsightsClient._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[AreaInsightsTransport], Callable[..., AreaInsightsTransport]] = ( + AreaInsightsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AreaInsightsTransport], 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, + ) + + def compute_insights(self, + request: Optional[Union[area_insights_service.ComputeInsightsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> area_insights_service.ComputeInsightsResponse: + r"""Compute Insights RPC + + This method lets you retrieve insights about areas using a + variaty of filter such as: area, place type, operating status, + price level and ratings. Currently "count" and "places" insights + are supported. With "count" insights you can answer questions + such as "How many restaurant are located in California that are + operational, are inexpensive and have an average rating of at + least 4 stars" (see ``insight`` enum for more details). With + "places" insights, you can determine which places match the + requested filter. Clients can then use those place resource + names to fetch more details about each individual place using + the Places API. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 areainsights_v1 + + def sample_compute_insights(): + # Create a client + client = areainsights_v1.AreaInsightsClient() + + # Initialize request argument(s) + request = areainsights_v1.ComputeInsightsRequest( + insights=['INSIGHT_PLACES'], + ) + + # Make the request + response = client.compute_insights(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.areainsights_v1.types.ComputeInsightsRequest, dict]): + The request object. Request for the ComputeInsights RPC. + retry (google.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. + + Returns: + google.maps.areainsights_v1.types.ComputeInsightsResponse: + Response for the ComputeInsights RPC. + """ + # 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, area_insights_service.ComputeInsightsRequest): + request = area_insights_service.ComputeInsightsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_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 __enter__(self) -> "AreaInsightsClient": + 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__ = ( + "AreaInsightsClient", +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/README.rst b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/README.rst new file mode 100644 index 000000000000..bb3b3fd75775 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AreaInsightsTransport` is the ABC for all transports. +- public child `AreaInsightsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AreaInsightsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAreaInsightsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AreaInsightsRestTransport` 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-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/__init__.py new file mode 100644 index 000000000000..2155301953d7 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/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 AreaInsightsTransport +from .grpc import AreaInsightsGrpcTransport +from .grpc_asyncio import AreaInsightsGrpcAsyncIOTransport +from .rest import AreaInsightsRestTransport +from .rest import AreaInsightsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AreaInsightsTransport]] +_transport_registry['grpc'] = AreaInsightsGrpcTransport +_transport_registry['grpc_asyncio'] = AreaInsightsGrpcAsyncIOTransport +_transport_registry['rest'] = AreaInsightsRestTransport + +__all__ = ( + 'AreaInsightsTransport', + 'AreaInsightsGrpcTransport', + 'AreaInsightsGrpcAsyncIOTransport', + 'AreaInsightsRestTransport', + 'AreaInsightsRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/base.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/base.py new file mode 100644 index 000000000000..57c23d3efe13 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/base.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.areainsights_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.areainsights_v1.types import area_insights_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AreaInsightsTransport(abc.ABC): + """Abstract transport class for AreaInsights.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'areainsights.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: 'areainsights.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_insights: gapic_v1.method.wrap_method( + self.compute_insights, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.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 compute_insights(self) -> Callable[ + [area_insights_service.ComputeInsightsRequest], + Union[ + area_insights_service.ComputeInsightsResponse, + Awaitable[area_insights_service.ComputeInsightsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AreaInsightsTransport', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc.py new file mode 100644 index 000000000000..ab0371a36a28 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.maps.areainsights_v1.types import area_insights_service +from .base import AreaInsightsTransport, DEFAULT_CLIENT_INFO + + +class AreaInsightsGrpcTransport(AreaInsightsTransport): + """gRPC backend transport for AreaInsights. + + Service definition for the Places Insights 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 = 'areainsights.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: 'areainsights.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'areainsights.googleapis.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_insights(self) -> Callable[ + [area_insights_service.ComputeInsightsRequest], + area_insights_service.ComputeInsightsResponse]: + r"""Return a callable for the compute insights method over gRPC. + + Compute Insights RPC + + This method lets you retrieve insights about areas using a + variaty of filter such as: area, place type, operating status, + price level and ratings. Currently "count" and "places" insights + are supported. With "count" insights you can answer questions + such as "How many restaurant are located in California that are + operational, are inexpensive and have an average rating of at + least 4 stars" (see ``insight`` enum for more details). With + "places" insights, you can determine which places match the + requested filter. Clients can then use those place resource + names to fetch more details about each individual place using + the Places API. + + Returns: + Callable[[~.ComputeInsightsRequest], + ~.ComputeInsightsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_insights' not in self._stubs: + self._stubs['compute_insights'] = self.grpc_channel.unary_unary( + '/google.maps.areainsights.v1.AreaInsights/ComputeInsights', + request_serializer=area_insights_service.ComputeInsightsRequest.serialize, + response_deserializer=area_insights_service.ComputeInsightsResponse.deserialize, + ) + return self._stubs['compute_insights'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AreaInsightsGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc_asyncio.py new file mode 100644 index 000000000000..bf60bfa9fa69 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc_asyncio.py @@ -0,0 +1,312 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.areainsights_v1.types import area_insights_service +from .base import AreaInsightsTransport, DEFAULT_CLIENT_INFO +from .grpc import AreaInsightsGrpcTransport + + +class AreaInsightsGrpcAsyncIOTransport(AreaInsightsTransport): + """gRPC AsyncIO backend transport for AreaInsights. + + Service definition for the Places Insights 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 = 'areainsights.googleapis.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 = 'areainsights.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: 'areainsights.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_insights(self) -> Callable[ + [area_insights_service.ComputeInsightsRequest], + Awaitable[area_insights_service.ComputeInsightsResponse]]: + r"""Return a callable for the compute insights method over gRPC. + + Compute Insights RPC + + This method lets you retrieve insights about areas using a + variaty of filter such as: area, place type, operating status, + price level and ratings. Currently "count" and "places" insights + are supported. With "count" insights you can answer questions + such as "How many restaurant are located in California that are + operational, are inexpensive and have an average rating of at + least 4 stars" (see ``insight`` enum for more details). With + "places" insights, you can determine which places match the + requested filter. Clients can then use those place resource + names to fetch more details about each individual place using + the Places API. + + Returns: + Callable[[~.ComputeInsightsRequest], + Awaitable[~.ComputeInsightsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_insights' not in self._stubs: + self._stubs['compute_insights'] = self.grpc_channel.unary_unary( + '/google.maps.areainsights.v1.AreaInsights/ComputeInsights', + request_serializer=area_insights_service.ComputeInsightsRequest.serialize, + response_deserializer=area_insights_service.ComputeInsightsResponse.deserialize, + ) + return self._stubs['compute_insights'] + + 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_insights: self._wrap_method( + self.compute_insights, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'AreaInsightsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest.py new file mode 100644 index 000000000000..75d995749fa2 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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.areainsights_v1.types import area_insights_service + + +from .rest_base import _BaseAreaInsightsRestTransport +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 + + +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 AreaInsightsRestInterceptor: + """Interceptor for AreaInsights. + + 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 AreaInsightsRestTransport. + + .. code-block:: python + class MyCustomAreaInsightsInterceptor(AreaInsightsRestInterceptor): + def pre_compute_insights(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_insights(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AreaInsightsRestTransport(interceptor=MyCustomAreaInsightsInterceptor()) + client = AreaInsightsClient(transport=transport) + + + """ + def pre_compute_insights(self, request: area_insights_service.ComputeInsightsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[area_insights_service.ComputeInsightsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_insights + + Override in a subclass to manipulate the request or metadata + before they are sent to the AreaInsights server. + """ + return request, metadata + + def post_compute_insights(self, response: area_insights_service.ComputeInsightsResponse) -> area_insights_service.ComputeInsightsResponse: + """Post-rpc interceptor for compute_insights + + Override in a subclass to manipulate the response + after it is returned by the AreaInsights server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AreaInsightsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AreaInsightsRestInterceptor + + +class AreaInsightsRestTransport(_BaseAreaInsightsRestTransport): + """REST backend synchronous transport for AreaInsights. + + Service definition for the Places Insights 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 = 'areainsights.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[AreaInsightsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'areainsights.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 AreaInsightsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ComputeInsights(_BaseAreaInsightsRestTransport._BaseComputeInsights, AreaInsightsRestStub): + def __hash__(self): + return hash("AreaInsightsRestTransport.ComputeInsights") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: area_insights_service.ComputeInsightsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> area_insights_service.ComputeInsightsResponse: + r"""Call the compute insights method over HTTP. + + Args: + request (~.area_insights_service.ComputeInsightsRequest): + The request object. Request for the ComputeInsights RPC. + retry (google.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. + + Returns: + ~.area_insights_service.ComputeInsightsResponse: + Response for the ComputeInsights RPC. + """ + + http_options = _BaseAreaInsightsRestTransport._BaseComputeInsights._get_http_options() + request, metadata = self._interceptor.pre_compute_insights(request, metadata) + transcoded_request = _BaseAreaInsightsRestTransport._BaseComputeInsights._get_transcoded_request(http_options, request) + + body = _BaseAreaInsightsRestTransport._BaseComputeInsights._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAreaInsightsRestTransport._BaseComputeInsights._get_query_params_json(transcoded_request) + + # Send the request + response = AreaInsightsRestTransport._ComputeInsights._get_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 = area_insights_service.ComputeInsightsResponse() + pb_resp = area_insights_service.ComputeInsightsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_compute_insights(resp) + return resp + + @property + def compute_insights(self) -> Callable[ + [area_insights_service.ComputeInsightsRequest], + area_insights_service.ComputeInsightsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeInsights(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AreaInsightsRestTransport', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest_base.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest_base.py new file mode 100644 index 000000000000..10ffc4defde0 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/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 AreaInsightsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.maps.areainsights_v1.types import area_insights_service + + +class _BaseAreaInsightsRestTransport(AreaInsightsTransport): + """Base REST backend transport for AreaInsights. + + 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 = 'areainsights.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: 'areainsights.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 _BaseComputeInsights: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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:computeInsights', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = area_insights_service.ComputeInsightsRequest.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(_BaseAreaInsightsRestTransport._BaseComputeInsights._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAreaInsightsRestTransport', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/__init__.py new file mode 100644 index 000000000000..06ae52567693 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/__init__.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .area_insights_service import ( + ComputeInsightsRequest, + ComputeInsightsResponse, + Filter, + LocationFilter, + PlaceInsight, + RatingFilter, + TypeFilter, + Insight, + OperatingStatus, + PriceLevel, +) + +__all__ = ( + 'ComputeInsightsRequest', + 'ComputeInsightsResponse', + 'Filter', + 'LocationFilter', + 'PlaceInsight', + 'RatingFilter', + 'TypeFilter', + 'Insight', + 'OperatingStatus', + 'PriceLevel', +) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/area_insights_service.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/area_insights_service.py new file mode 100644 index 000000000000..e0796e3a9c67 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/area_insights_service.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.areainsights.v1', + manifest={ + 'Insight', + 'OperatingStatus', + 'PriceLevel', + 'ComputeInsightsRequest', + 'ComputeInsightsResponse', + 'PlaceInsight', + 'Filter', + 'LocationFilter', + 'TypeFilter', + 'RatingFilter', + }, +) + + +class Insight(proto.Enum): + r"""Supported insights. + + Values: + INSIGHT_UNSPECIFIED (0): + Not Specified. + INSIGHT_COUNT (1): + Count insight. + + When this insight is specified ComputeInsights returns the + number of places that match the specified filter criteria. + + :: + + For example if the request is: + ComputeInsightsRequest { + insights: INSIGHT_COUNT + filter { + location_filter {region: } + type_filter {included_types: "restaurant"} + operating_status: OPERATING_STATUS_OPERATIONAL + price_levels: PRICE_LEVEL_FREE + price_levels: PRICE_LEVEL_INEXPENSIVE + min_rating: 4.0 + } + } + + The method will return the count of restaurants in California that are + operational, with price level free or inexpensive and have an average + rating of at least 4 starts. + + Example response: + ComputeInsightsResponse { + count: + } + INSIGHT_PLACES (2): + Return Places + + When this insight is specified ComputeInsights returns + Places that match the specified filter criteria. + + :: + + For example if the request is: + ComputeInsightsRequest { + insights: INSIGHT_PLACES + filter { + location_filter {region: } + type_filter {included_types: "restaurant"} + operating_status: OPERATING_STATUS_OPERATIONAL + price_levels: PRICE_LEVEL_FREE + price_levels: PRICE_LEVEL_INEXPENSIVE + min_rating: 4.0 + } + } + + The method will return list of places of restaurants in + California that are operational, with price level free or inexpensive and + have an average rating of at least 4 stars. + + Example response: + ComputeInsightsResponse { + place_insights { place: "places/ABC" } + place_insights { place: "places/PQR" } + place_insights { place: "places/XYZ" } + } + """ + INSIGHT_UNSPECIFIED = 0 + INSIGHT_COUNT = 1 + INSIGHT_PLACES = 2 + + +class OperatingStatus(proto.Enum): + r"""Operating status of the place. + + Values: + OPERATING_STATUS_UNSPECIFIED (0): + Not Specified. + OPERATING_STATUS_OPERATIONAL (1): + The place is operational and its open during + its defined hours. + OPERATING_STATUS_PERMANENTLY_CLOSED (3): + The Place is no longer in business. + OPERATING_STATUS_TEMPORARILY_CLOSED (4): + The Place is temporarily closed and expected + to reopen in the future. + """ + OPERATING_STATUS_UNSPECIFIED = 0 + OPERATING_STATUS_OPERATIONAL = 1 + OPERATING_STATUS_PERMANENTLY_CLOSED = 3 + OPERATING_STATUS_TEMPORARILY_CLOSED = 4 + + +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 ComputeInsightsRequest(proto.Message): + r"""Request for the ComputeInsights RPC. + + Attributes: + insights (MutableSequence[google.maps.areainsights_v1.types.Insight]): + Required. Insights to compute. Currently only INSIGHT_COUNT + and INSIGHT_PLACES are supported. + filter (google.maps.areainsights_v1.types.Filter): + Required. Insight filter. + """ + + insights: MutableSequence['Insight'] = proto.RepeatedField( + proto.ENUM, + number=4, + enum='Insight', + ) + filter: 'Filter' = proto.Field( + proto.MESSAGE, + number=5, + message='Filter', + ) + + +class ComputeInsightsResponse(proto.Message): + r"""Response for the ComputeInsights RPC. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + count (int): + Result for Insights.INSIGHT_COUNT. + + This field is a member of `oneof`_ ``_count``. + place_insights (MutableSequence[google.maps.areainsights_v1.types.PlaceInsight]): + Result for Insights.INSIGHT_PLACES. + """ + + count: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + place_insights: MutableSequence['PlaceInsight'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='PlaceInsight', + ) + + +class PlaceInsight(proto.Message): + r"""Holds information about a place + + Attributes: + place (str): + The resource name of a place. This resource name can be used + to retrieve details about the place using the `Places + API `__. + """ + + place: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Filter(proto.Message): + r"""Filters for the ComputeInsights RPC. + + Attributes: + location_filter (google.maps.areainsights_v1.types.LocationFilter): + Required. Restricts results to places which + are located in the area specified by location + filters. + type_filter (google.maps.areainsights_v1.types.TypeFilter): + Required. Place type filters. + operating_status (MutableSequence[google.maps.areainsights_v1.types.OperatingStatus]): + Optional. Restricts results to places whose operating status + is included on this list. If operating_status is not set, + OPERATING_STATUS_OPERATIONAL is used as default. + price_levels (MutableSequence[google.maps.areainsights_v1.types.PriceLevel]): + Optional. Restricts results to places whose price level is + included on this list. If price_level is not set, all price + levels are included in the results. + rating_filter (google.maps.areainsights_v1.types.RatingFilter): + Optional. Restricts results to places whose average user + ratings are in the range specified by rating_filter. If + rating_filter is not set, all ratings are included in the + result. + """ + + location_filter: 'LocationFilter' = proto.Field( + proto.MESSAGE, + number=1, + message='LocationFilter', + ) + type_filter: 'TypeFilter' = proto.Field( + proto.MESSAGE, + number=2, + message='TypeFilter', + ) + operating_status: MutableSequence['OperatingStatus'] = proto.RepeatedField( + proto.ENUM, + number=3, + enum='OperatingStatus', + ) + price_levels: MutableSequence['PriceLevel'] = proto.RepeatedField( + proto.ENUM, + number=4, + enum='PriceLevel', + ) + rating_filter: 'RatingFilter' = proto.Field( + proto.MESSAGE, + number=5, + message='RatingFilter', + ) + + +class LocationFilter(proto.Message): + r"""Location filters. + + Specifies the area of interest for the insight. + + 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: + circle (google.maps.areainsights_v1.types.LocationFilter.Circle): + Area as a circle. + + This field is a member of `oneof`_ ``area``. + region (google.maps.areainsights_v1.types.LocationFilter.Region): + Area as region. + + This field is a member of `oneof`_ ``area``. + custom_area (google.maps.areainsights_v1.types.LocationFilter.CustomArea): + Custom area specified by a polygon. + + This field is a member of `oneof`_ ``area``. + """ + + class Circle(proto.Message): + r"""A circle is defined by a center point and radius in meters. + + 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: + lat_lng (google.type.latlng_pb2.LatLng): + The latitude and longitude of the center of + the circle. + + This field is a member of `oneof`_ ``center``. + place (str): + The Place resource name of the center of the + circle. Only point places are supported. + + This field is a member of `oneof`_ ``center``. + radius (int): + Optional. The radius of the circle in meters + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + oneof='center', + message=latlng_pb2.LatLng, + ) + place: str = proto.Field( + proto.STRING, + number=2, + oneof='center', + ) + radius: int = proto.Field( + proto.INT32, + number=3, + ) + + class Region(proto.Message): + r"""A region is a geographic boundary such as: cities, postal + codes, counties, states, etc. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + place (str): + The Place resource name of a region. + + This field is a member of `oneof`_ ``region``. + """ + + place: str = proto.Field( + proto.STRING, + number=1, + oneof='region', + ) + + class CustomArea(proto.Message): + r"""Custom Area. + + Attributes: + polygon (google.maps.areainsights_v1.types.LocationFilter.CustomArea.Polygon): + Required. The custom area represented as a + polygon + """ + + class Polygon(proto.Message): + r"""A polygon is represented by a series of connected coordinates + in an counterclockwise ordered sequence. The coordinates form a + closed loop and define a filled region. The first and last + coordinates are equivalent, and they must contain identical + values. The format is a simplified version of GeoJSON polygons + (we only support one counterclockwise exterior ring). + + Attributes: + coordinates (MutableSequence[google.type.latlng_pb2.LatLng]): + Optional. The coordinates that define the + polygon. + """ + + coordinates: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + + polygon: 'LocationFilter.CustomArea.Polygon' = proto.Field( + proto.MESSAGE, + number=1, + message='LocationFilter.CustomArea.Polygon', + ) + + circle: Circle = proto.Field( + proto.MESSAGE, + number=1, + oneof='area', + message=Circle, + ) + region: Region = proto.Field( + proto.MESSAGE, + number=2, + oneof='area', + message=Region, + ) + custom_area: CustomArea = proto.Field( + proto.MESSAGE, + number=3, + oneof='area', + message=CustomArea, + ) + + +class TypeFilter(proto.Message): + r"""Place type filters. + + Only Place types from `Table + a `__ + are supported. + + A place can only have a single primary type associated with it. For + example, the primary type might be "mexican_restaurant" or + "steak_house". Use included_primary_types and excluded_primary_types + to filter the results on a place's primary type. + + A place can also have multiple type values associated with it. For + example a restaurant might have the following types: + "seafood_restaurant", "restaurant", "food", "point_of_interest", + "establishment". Use included_types and excluded_types to filter the + results on the list of types associated with a place. + + If a search is specified with multiple type restrictions, only + places that satisfy all of the restrictions are returned. For + example, if you specify {"included_types": ["restaurant"], + "excluded_primary_types": ["steak_house"]}, the returned places + provide "restaurant" related services but do not operate primarily + as a "steak_house". + + If there are any conflicting types, i.e. a type appears in both + included_types and excluded_types types or included_primary_types + and excluded_primary_types, an INVALID_ARGUMENT error is returned. + + One of included_types or included_primary_types must be set. + + Attributes: + included_types (MutableSequence[str]): + Optional. Included Place types. + excluded_types (MutableSequence[str]): + Optional. Excluded Place types. + included_primary_types (MutableSequence[str]): + Optional. Included primary Place types. + excluded_primary_types (MutableSequence[str]): + Optional. Excluded primary Place types. + """ + + included_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + excluded_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + included_primary_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + excluded_primary_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class RatingFilter(proto.Message): + r"""Average user rating filters. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + min_rating (float): + Optional. Restricts results to places whose average user + rating is greater than or equal to min_rating. Values must + be between 1.0 and 5.0. + + This field is a member of `oneof`_ ``_min_rating``. + max_rating (float): + Optional. Restricts results to places whose average user + rating is strictly less than or equal to max_rating. Values + must be between 1.0 and 5.0. + + This field is a member of `oneof`_ ``_max_rating``. + """ + + min_rating: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + max_rating: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-areainsights/v1/mypy.ini b/owl-bot-staging/google-maps-areainsights/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-areainsights/v1/noxfile.py b/owl-bot-staging/google-maps-areainsights/v1/noxfile.py new file mode 100644 index 000000000000..c9af38e95ec1 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights' + +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/areainsights_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/areainsights_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-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_async.py b/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_async.py new file mode 100644 index 000000000000..880f4b4385cc --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_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 ComputeInsights +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-areainsights + + +# [START areainsights_v1_generated_AreaInsights_ComputeInsights_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 areainsights_v1 + + +async def sample_compute_insights(): + # Create a client + client = areainsights_v1.AreaInsightsAsyncClient() + + # Initialize request argument(s) + request = areainsights_v1.ComputeInsightsRequest( + insights=['INSIGHT_PLACES'], + ) + + # Make the request + response = await client.compute_insights(request=request) + + # Handle the response + print(response) + +# [END areainsights_v1_generated_AreaInsights_ComputeInsights_async] diff --git a/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_sync.py b/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_sync.py new file mode 100644 index 000000000000..cbf41464d3b3 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_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 ComputeInsights +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-areainsights + + +# [START areainsights_v1_generated_AreaInsights_ComputeInsights_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 areainsights_v1 + + +def sample_compute_insights(): + # Create a client + client = areainsights_v1.AreaInsightsClient() + + # Initialize request argument(s) + request = areainsights_v1.ComputeInsightsRequest( + insights=['INSIGHT_PLACES'], + ) + + # Make the request + response = client.compute_insights(request=request) + + # Handle the response + print(response) + +# [END areainsights_v1_generated_AreaInsights_ComputeInsights_sync] diff --git a/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/snippet_metadata_google.maps.areainsights.v1.json b/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/snippet_metadata_google.maps.areainsights.v1.json new file mode 100644 index 000000000000..508e4607c0f8 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/snippet_metadata_google.maps.areainsights.v1.json @@ -0,0 +1,168 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.areainsights.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-areainsights", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.areainsights_v1.AreaInsightsAsyncClient", + "shortName": "AreaInsightsAsyncClient" + }, + "fullName": "google.maps.areainsights_v1.AreaInsightsAsyncClient.compute_insights", + "method": { + "fullName": "google.maps.areainsights.v1.AreaInsights.ComputeInsights", + "service": { + "fullName": "google.maps.areainsights.v1.AreaInsights", + "shortName": "AreaInsights" + }, + "shortName": "ComputeInsights" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.areainsights_v1.types.ComputeInsightsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.areainsights_v1.types.ComputeInsightsResponse", + "shortName": "compute_insights" + }, + "description": "Sample for ComputeInsights", + "file": "areainsights_v1_generated_area_insights_compute_insights_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "areainsights_v1_generated_AreaInsights_ComputeInsights_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": "areainsights_v1_generated_area_insights_compute_insights_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.areainsights_v1.AreaInsightsClient", + "shortName": "AreaInsightsClient" + }, + "fullName": "google.maps.areainsights_v1.AreaInsightsClient.compute_insights", + "method": { + "fullName": "google.maps.areainsights.v1.AreaInsights.ComputeInsights", + "service": { + "fullName": "google.maps.areainsights.v1.AreaInsights", + "shortName": "AreaInsights" + }, + "shortName": "ComputeInsights" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.areainsights_v1.types.ComputeInsightsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.areainsights_v1.types.ComputeInsightsResponse", + "shortName": "compute_insights" + }, + "description": "Sample for ComputeInsights", + "file": "areainsights_v1_generated_area_insights_compute_insights_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "areainsights_v1_generated_AreaInsights_ComputeInsights_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": "areainsights_v1_generated_area_insights_compute_insights_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-areainsights/v1/scripts/fixup_areainsights_v1_keywords.py b/owl-bot-staging/google-maps-areainsights/v1/scripts/fixup_areainsights_v1_keywords.py new file mode 100644 index 000000000000..2b35b82f7b4e --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/scripts/fixup_areainsights_v1_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 areainsightsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'compute_insights': ('insights', 'filter', ), + } + + 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=areainsightsCallTransformer(), +): + """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 areainsights 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-areainsights/v1/setup.py b/owl-bot-staging/google-maps-areainsights/v1/setup.py new file mode 100644 index 000000000000..b4a51e3a8d23 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights' + + +description = "Google Maps Areainsights API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/areainsights/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-areainsights" + +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-areainsights/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/tests/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/tests/unit/gapic/areainsights_v1/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_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-areainsights/v1/tests/unit/gapic/areainsights_v1/test_area_insights.py b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/test_area_insights.py new file mode 100644 index 000000000000..7c2001255008 --- /dev/null +++ b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/test_area_insights.py @@ -0,0 +1,1935 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.areainsights_v1.services.area_insights import AreaInsightsAsyncClient +from google.maps.areainsights_v1.services.area_insights import AreaInsightsClient +from google.maps.areainsights_v1.services.area_insights import transports +from google.maps.areainsights_v1.types import area_insights_service +from google.oauth2 import service_account +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 AreaInsightsClient._get_default_mtls_endpoint(None) is None + assert AreaInsightsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AreaInsightsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AreaInsightsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AreaInsightsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AreaInsightsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AreaInsightsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AreaInsightsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AreaInsightsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AreaInsightsClient._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 AreaInsightsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AreaInsightsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AreaInsightsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AreaInsightsClient._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 AreaInsightsClient._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 AreaInsightsClient._get_client_cert_source(None, False) is None + assert AreaInsightsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AreaInsightsClient._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 AreaInsightsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AreaInsightsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AreaInsightsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsClient)) +@mock.patch.object(AreaInsightsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AreaInsightsClient._DEFAULT_UNIVERSE + default_endpoint = AreaInsightsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AreaInsightsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AreaInsightsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AreaInsightsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AreaInsightsClient.DEFAULT_MTLS_ENDPOINT + assert AreaInsightsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AreaInsightsClient._get_api_endpoint(None, None, default_universe, "always") == AreaInsightsClient.DEFAULT_MTLS_ENDPOINT + assert AreaInsightsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AreaInsightsClient.DEFAULT_MTLS_ENDPOINT + assert AreaInsightsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AreaInsightsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AreaInsightsClient._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 AreaInsightsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AreaInsightsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AreaInsightsClient._get_universe_domain(None, None) == AreaInsightsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AreaInsightsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc"), + (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AreaInsightsClient, "grpc"), + (AreaInsightsAsyncClient, "grpc_asyncio"), + (AreaInsightsClient, "rest"), +]) +def test_area_insights_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 == ( + 'areainsights.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://areainsights.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AreaInsightsGrpcTransport, "grpc"), + (transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AreaInsightsRestTransport, "rest"), +]) +def test_area_insights_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", [ + (AreaInsightsClient, "grpc"), + (AreaInsightsAsyncClient, "grpc_asyncio"), + (AreaInsightsClient, "rest"), +]) +def test_area_insights_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 == ( + 'areainsights.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://areainsights.googleapis.com' + ) + + +def test_area_insights_client_get_transport_class(): + transport = AreaInsightsClient.get_transport_class() + available_transports = [ + transports.AreaInsightsGrpcTransport, + transports.AreaInsightsRestTransport, + ] + assert transport in available_transports + + transport = AreaInsightsClient.get_transport_class("grpc") + assert transport == transports.AreaInsightsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc"), + (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio"), + (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest"), +]) +@mock.patch.object(AreaInsightsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsClient)) +@mock.patch.object(AreaInsightsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsAsyncClient)) +def test_area_insights_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(AreaInsightsClient, '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(AreaInsightsClient, '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", [ + (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc", "true"), + (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc", "false"), + (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest", "true"), + (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest", "false"), +]) +@mock.patch.object(AreaInsightsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsClient)) +@mock.patch.object(AreaInsightsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_area_insights_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", [ + AreaInsightsClient, AreaInsightsAsyncClient +]) +@mock.patch.object(AreaInsightsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AreaInsightsClient)) +@mock.patch.object(AreaInsightsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AreaInsightsAsyncClient)) +def test_area_insights_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", [ + AreaInsightsClient, AreaInsightsAsyncClient +]) +@mock.patch.object(AreaInsightsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsClient)) +@mock.patch.object(AreaInsightsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsAsyncClient)) +def test_area_insights_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AreaInsightsClient._DEFAULT_UNIVERSE + default_endpoint = AreaInsightsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AreaInsightsClient._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", [ + (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc"), + (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio"), + (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest"), +]) +def test_area_insights_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", [ + (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc", grpc_helpers), + (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest", None), +]) +def test_area_insights_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_area_insights_client_client_options_from_dict(): + with mock.patch('google.maps.areainsights_v1.services.area_insights.transports.AreaInsightsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AreaInsightsClient( + 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", [ + (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc", grpc_helpers), + (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_area_insights_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( + "areainsights.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="areainsights.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + area_insights_service.ComputeInsightsRequest, + dict, +]) +def test_compute_insights(request_type, transport: str = 'grpc'): + client = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_insights), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = area_insights_service.ComputeInsightsResponse( + count=553, + ) + response = client.compute_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = area_insights_service.ComputeInsightsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, area_insights_service.ComputeInsightsResponse) + assert response.count == 553 + + +def test_compute_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 = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = area_insights_service.ComputeInsightsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_insights), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.compute_insights(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == area_insights_service.ComputeInsightsRequest( + ) + +def test_compute_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 = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.compute_insights] = mock_rpc + request = {} + client.compute_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_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_compute_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 = AreaInsightsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_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.compute_insights] = mock_rpc + + request = {} + await client.compute_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.compute_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_compute_insights_async(transport: str = 'grpc_asyncio', request_type=area_insights_service.ComputeInsightsRequest): + client = AreaInsightsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_insights), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(area_insights_service.ComputeInsightsResponse( + count=553, + )) + response = await client.compute_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = area_insights_service.ComputeInsightsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, area_insights_service.ComputeInsightsResponse) + assert response.count == 553 + + +@pytest.mark.asyncio +async def test_compute_insights_async_from_dict(): + await test_compute_insights_async(request_type=dict) + + +def test_compute_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 = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.compute_insights] = mock_rpc + + request = {} + client.compute_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_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_compute_insights_rest_required_fields(request_type=area_insights_service.ComputeInsightsRequest): + transport_class = transports.AreaInsightsRestTransport + + 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_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()).compute_insights._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = area_insights_service.ComputeInsightsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = area_insights_service.ComputeInsightsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.compute_insights(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_insights_rest_unset_required_fields(): + transport = transports.AreaInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_insights._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("insights", "filter", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AreaInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AreaInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AreaInsightsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AreaInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AreaInsightsClient( + 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 = AreaInsightsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AreaInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AreaInsightsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AreaInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AreaInsightsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AreaInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AreaInsightsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AreaInsightsGrpcTransport, + transports.AreaInsightsGrpcAsyncIOTransport, + transports.AreaInsightsRestTransport, +]) +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 = AreaInsightsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AreaInsightsClient( + 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_insights_empty_call_grpc(): + client = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_insights), + '__call__') as call: + call.return_value = area_insights_service.ComputeInsightsResponse() + client.compute_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = area_insights_service.ComputeInsightsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AreaInsightsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AreaInsightsAsyncClient( + 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_insights_empty_call_grpc_asyncio(): + client = AreaInsightsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_insights), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(area_insights_service.ComputeInsightsResponse( + count=553, + )) + await client.compute_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = area_insights_service.ComputeInsightsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AreaInsightsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_compute_insights_rest_bad_request(request_type=area_insights_service.ComputeInsightsRequest): + client = AreaInsightsClient( + 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 + client.compute_insights(request) + + +@pytest.mark.parametrize("request_type", [ + area_insights_service.ComputeInsightsRequest, + dict, +]) +def test_compute_insights_rest_call_success(request_type): + client = AreaInsightsClient( + 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 = area_insights_service.ComputeInsightsResponse( + count=553, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = area_insights_service.ComputeInsightsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.compute_insights(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, area_insights_service.ComputeInsightsResponse) + assert response.count == 553 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_insights_rest_interceptors(null_interceptor): + transport = transports.AreaInsightsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AreaInsightsRestInterceptor(), + ) + client = AreaInsightsClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AreaInsightsRestInterceptor, "post_compute_insights") as post, \ + mock.patch.object(transports.AreaInsightsRestInterceptor, "pre_compute_insights") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = area_insights_service.ComputeInsightsRequest.pb(area_insights_service.ComputeInsightsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = area_insights_service.ComputeInsightsResponse.to_json(area_insights_service.ComputeInsightsResponse()) + req.return_value.content = return_value + + request = area_insights_service.ComputeInsightsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = area_insights_service.ComputeInsightsResponse() + + client.compute_insights(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = AreaInsightsClient( + 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_insights_empty_call_rest(): + client = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_insights), + '__call__') as call: + client.compute_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = area_insights_service.ComputeInsightsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AreaInsightsGrpcTransport, + ) + +def test_area_insights_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AreaInsightsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_area_insights_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.areainsights_v1.services.area_insights.transports.AreaInsightsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AreaInsightsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'compute_insights', + ) + 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_area_insights_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.areainsights_v1.services.area_insights.transports.AreaInsightsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AreaInsightsTransport( + 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_area_insights_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.areainsights_v1.services.area_insights.transports.AreaInsightsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AreaInsightsTransport() + adc.assert_called_once() + + +def test_area_insights_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) + AreaInsightsClient() + 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.AreaInsightsGrpcTransport, + transports.AreaInsightsGrpcAsyncIOTransport, + ], +) +def test_area_insights_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.AreaInsightsGrpcTransport, + transports.AreaInsightsGrpcAsyncIOTransport, + transports.AreaInsightsRestTransport, + ], +) +def test_area_insights_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.AreaInsightsGrpcTransport, grpc_helpers), + (transports.AreaInsightsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_area_insights_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( + "areainsights.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="areainsights.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AreaInsightsGrpcTransport, transports.AreaInsightsGrpcAsyncIOTransport]) +def test_area_insights_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_area_insights_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.AreaInsightsRestTransport ( + 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_area_insights_host_no_port(transport_name): + client = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='areainsights.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'areainsights.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://areainsights.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_area_insights_host_with_port(transport_name): + client = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='areainsights.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'areainsights.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://areainsights.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_area_insights_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AreaInsightsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AreaInsightsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.compute_insights._session + session2 = client2.transport.compute_insights._session + assert session1 != session2 +def test_area_insights_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AreaInsightsGrpcTransport( + 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_area_insights_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AreaInsightsGrpcAsyncIOTransport( + 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.AreaInsightsGrpcTransport, transports.AreaInsightsGrpcAsyncIOTransport]) +def test_area_insights_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.AreaInsightsGrpcTransport, transports.AreaInsightsGrpcAsyncIOTransport]) +def test_area_insights_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_place_path(): + place_id = "squid" + expected = "places/{place_id}".format(place_id=place_id, ) + actual = AreaInsightsClient.place_path(place_id) + assert expected == actual + + +def test_parse_place_path(): + expected = { + "place_id": "clam", + } + path = AreaInsightsClient.place_path(**expected) + + # Check that the path construction is reversible. + actual = AreaInsightsClient.parse_place_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AreaInsightsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AreaInsightsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AreaInsightsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = AreaInsightsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AreaInsightsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AreaInsightsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AreaInsightsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AreaInsightsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AreaInsightsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = AreaInsightsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AreaInsightsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AreaInsightsClient.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 = AreaInsightsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AreaInsightsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AreaInsightsClient.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.AreaInsightsTransport, '_prep_wrapped_messages') as prep: + client = AreaInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AreaInsightsTransport, '_prep_wrapped_messages') as prep: + transport_class = AreaInsightsClient.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 = AreaInsightsClient( + 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 = AreaInsightsAsyncClient( + 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 = AreaInsightsClient( + 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 = AreaInsightsClient( + 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", [ + (AreaInsightsClient, transports.AreaInsightsGrpcTransport), + (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport), +]) +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-fleetengine-delivery/v1/.coveragerc b/owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc new file mode 100644 index 000000000000..4d78db33eace --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/fleetengine_delivery/__init__.py + google/maps/fleetengine_delivery/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-fleetengine-delivery/v1/.flake8 b/owl-bot-staging/google-maps-fleetengine-delivery/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/MANIFEST.in b/owl-bot-staging/google-maps-fleetengine-delivery/v1/MANIFEST.in new file mode 100644 index 000000000000..76734494c81d --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/fleetengine_delivery *.py +recursive-include google/maps/fleetengine_delivery_v1 *.py diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst new file mode 100644 index 000000000000..1261668cfc0b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Fleetengine Delivery 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 Fleetengine Delivery 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-fleetengine-delivery/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/conf.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/conf.py new file mode 100644 index 000000000000..ba785733498b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery 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-fleetengine-delivery" +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-fleetengine-delivery-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-fleetengine-delivery.tex", + u"google-maps-fleetengine-delivery 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-fleetengine-delivery", + u"Google Maps Fleetengine Delivery 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-fleetengine-delivery", + u"google-maps-fleetengine-delivery Documentation", + author, + "google-maps-fleetengine-delivery", + "GAPIC library for Google Maps Fleetengine Delivery 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-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst new file mode 100644 index 000000000000..88aac9c4fbb4 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst @@ -0,0 +1,10 @@ +DeliveryService +--------------------------------- + +.. automodule:: google.maps.fleetengine_delivery_v1.services.delivery_service + :members: + :inherited-members: + +.. automodule:: google.maps.fleetengine_delivery_v1.services.delivery_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst new file mode 100644 index 000000000000..97febb72086f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Fleetengine Delivery v1 API +==================================================== +.. toctree:: + :maxdepth: 2 + + delivery_service diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst new file mode 100644 index 000000000000..d633ae8b217f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Fleetengine Delivery v1 API +================================================= + +.. automodule:: google.maps.fleetengine_delivery_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst new file mode 100644 index 000000000000..a5601707f6f4 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + fleetengine_delivery_v1/services_ + fleetengine_delivery_v1/types_ diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py new file mode 100644 index 000000000000..9aceee6293a4 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__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.fleetengine_delivery import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.fleetengine_delivery_v1.services.delivery_service.client import DeliveryServiceClient +from google.maps.fleetengine_delivery_v1.services.delivery_service.async_client import DeliveryServiceAsyncClient + +from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleAttribute +from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleLocation +from google.maps.fleetengine_delivery_v1.types.common import TaskAttribute +from google.maps.fleetengine_delivery_v1.types.common import TimeWindow +from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleLocationSensor +from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleNavigationStatus +from google.maps.fleetengine_delivery_v1.types.delivery_api import BatchCreateTasksRequest +from google.maps.fleetengine_delivery_v1.types.delivery_api import BatchCreateTasksResponse +from google.maps.fleetengine_delivery_v1.types.delivery_api import CreateDeliveryVehicleRequest +from google.maps.fleetengine_delivery_v1.types.delivery_api import CreateTaskRequest +from google.maps.fleetengine_delivery_v1.types.delivery_api import GetDeliveryVehicleRequest +from google.maps.fleetengine_delivery_v1.types.delivery_api import GetTaskRequest +from google.maps.fleetengine_delivery_v1.types.delivery_api import GetTaskTrackingInfoRequest +from google.maps.fleetengine_delivery_v1.types.delivery_api import ListDeliveryVehiclesRequest +from google.maps.fleetengine_delivery_v1.types.delivery_api import ListDeliveryVehiclesResponse +from google.maps.fleetengine_delivery_v1.types.delivery_api import ListTasksRequest +from google.maps.fleetengine_delivery_v1.types.delivery_api import ListTasksResponse +from google.maps.fleetengine_delivery_v1.types.delivery_api import UpdateDeliveryVehicleRequest +from google.maps.fleetengine_delivery_v1.types.delivery_api import UpdateTaskRequest +from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import DeliveryVehicle +from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import LocationInfo +from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import VehicleJourneySegment +from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import VehicleStop +from google.maps.fleetengine_delivery_v1.types.header import DeliveryRequestHeader +from google.maps.fleetengine_delivery_v1.types.task_tracking_info import TaskTrackingInfo +from google.maps.fleetengine_delivery_v1.types.tasks import Task +from google.maps.fleetengine_delivery_v1.types.tasks import TaskTrackingViewConfig + +__all__ = ('DeliveryServiceClient', + 'DeliveryServiceAsyncClient', + 'DeliveryVehicleAttribute', + 'DeliveryVehicleLocation', + 'TaskAttribute', + 'TimeWindow', + 'DeliveryVehicleLocationSensor', + 'DeliveryVehicleNavigationStatus', + 'BatchCreateTasksRequest', + 'BatchCreateTasksResponse', + 'CreateDeliveryVehicleRequest', + 'CreateTaskRequest', + 'GetDeliveryVehicleRequest', + 'GetTaskRequest', + 'GetTaskTrackingInfoRequest', + 'ListDeliveryVehiclesRequest', + 'ListDeliveryVehiclesResponse', + 'ListTasksRequest', + 'ListTasksResponse', + 'UpdateDeliveryVehicleRequest', + 'UpdateTaskRequest', + 'DeliveryVehicle', + 'LocationInfo', + 'VehicleJourneySegment', + 'VehicleStop', + 'DeliveryRequestHeader', + 'TaskTrackingInfo', + 'Task', + 'TaskTrackingViewConfig', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/gapic_version.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/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-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed new file mode 100644 index 000000000000..8464ee4c8285 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-fleetengine-delivery package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py new file mode 100644 index 000000000000..3dee9f0b3f48 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_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.fleetengine_delivery_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.delivery_service import DeliveryServiceClient +from .services.delivery_service import DeliveryServiceAsyncClient + +from .types.common import DeliveryVehicleAttribute +from .types.common import DeliveryVehicleLocation +from .types.common import TaskAttribute +from .types.common import TimeWindow +from .types.common import DeliveryVehicleLocationSensor +from .types.common import DeliveryVehicleNavigationStatus +from .types.delivery_api import BatchCreateTasksRequest +from .types.delivery_api import BatchCreateTasksResponse +from .types.delivery_api import CreateDeliveryVehicleRequest +from .types.delivery_api import CreateTaskRequest +from .types.delivery_api import GetDeliveryVehicleRequest +from .types.delivery_api import GetTaskRequest +from .types.delivery_api import GetTaskTrackingInfoRequest +from .types.delivery_api import ListDeliveryVehiclesRequest +from .types.delivery_api import ListDeliveryVehiclesResponse +from .types.delivery_api import ListTasksRequest +from .types.delivery_api import ListTasksResponse +from .types.delivery_api import UpdateDeliveryVehicleRequest +from .types.delivery_api import UpdateTaskRequest +from .types.delivery_vehicles import DeliveryVehicle +from .types.delivery_vehicles import LocationInfo +from .types.delivery_vehicles import VehicleJourneySegment +from .types.delivery_vehicles import VehicleStop +from .types.header import DeliveryRequestHeader +from .types.task_tracking_info import TaskTrackingInfo +from .types.tasks import Task +from .types.tasks import TaskTrackingViewConfig + +__all__ = ( + 'DeliveryServiceAsyncClient', +'BatchCreateTasksRequest', +'BatchCreateTasksResponse', +'CreateDeliveryVehicleRequest', +'CreateTaskRequest', +'DeliveryRequestHeader', +'DeliveryServiceClient', +'DeliveryVehicle', +'DeliveryVehicleAttribute', +'DeliveryVehicleLocation', +'DeliveryVehicleLocationSensor', +'DeliveryVehicleNavigationStatus', +'GetDeliveryVehicleRequest', +'GetTaskRequest', +'GetTaskTrackingInfoRequest', +'ListDeliveryVehiclesRequest', +'ListDeliveryVehiclesResponse', +'ListTasksRequest', +'ListTasksResponse', +'LocationInfo', +'Task', +'TaskAttribute', +'TaskTrackingInfo', +'TaskTrackingViewConfig', +'TimeWindow', +'UpdateDeliveryVehicleRequest', +'UpdateTaskRequest', +'VehicleJourneySegment', +'VehicleStop', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json new file mode 100644 index 000000000000..8b15810ecafd --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json @@ -0,0 +1,178 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.fleetengine_delivery_v1", + "protoPackage": "maps.fleetengine.delivery.v1", + "schema": "1.0", + "services": { + "DeliveryService": { + "clients": { + "grpc": { + "libraryClient": "DeliveryServiceClient", + "rpcs": { + "BatchCreateTasks": { + "methods": [ + "batch_create_tasks" + ] + }, + "CreateDeliveryVehicle": { + "methods": [ + "create_delivery_vehicle" + ] + }, + "CreateTask": { + "methods": [ + "create_task" + ] + }, + "GetDeliveryVehicle": { + "methods": [ + "get_delivery_vehicle" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "GetTaskTrackingInfo": { + "methods": [ + "get_task_tracking_info" + ] + }, + "ListDeliveryVehicles": { + "methods": [ + "list_delivery_vehicles" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + }, + "UpdateDeliveryVehicle": { + "methods": [ + "update_delivery_vehicle" + ] + }, + "UpdateTask": { + "methods": [ + "update_task" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DeliveryServiceAsyncClient", + "rpcs": { + "BatchCreateTasks": { + "methods": [ + "batch_create_tasks" + ] + }, + "CreateDeliveryVehicle": { + "methods": [ + "create_delivery_vehicle" + ] + }, + "CreateTask": { + "methods": [ + "create_task" + ] + }, + "GetDeliveryVehicle": { + "methods": [ + "get_delivery_vehicle" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "GetTaskTrackingInfo": { + "methods": [ + "get_task_tracking_info" + ] + }, + "ListDeliveryVehicles": { + "methods": [ + "list_delivery_vehicles" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + }, + "UpdateDeliveryVehicle": { + "methods": [ + "update_delivery_vehicle" + ] + }, + "UpdateTask": { + "methods": [ + "update_task" + ] + } + } + }, + "rest": { + "libraryClient": "DeliveryServiceClient", + "rpcs": { + "BatchCreateTasks": { + "methods": [ + "batch_create_tasks" + ] + }, + "CreateDeliveryVehicle": { + "methods": [ + "create_delivery_vehicle" + ] + }, + "CreateTask": { + "methods": [ + "create_task" + ] + }, + "GetDeliveryVehicle": { + "methods": [ + "get_delivery_vehicle" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "GetTaskTrackingInfo": { + "methods": [ + "get_task_tracking_info" + ] + }, + "ListDeliveryVehicles": { + "methods": [ + "list_delivery_vehicles" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + }, + "UpdateDeliveryVehicle": { + "methods": [ + "update_delivery_vehicle" + ] + }, + "UpdateTask": { + "methods": [ + "update_task" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_version.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_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-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed new file mode 100644 index 000000000000..8464ee4c8285 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-fleetengine-delivery package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_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-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/__init__.py new file mode 100644 index 000000000000..4dc5b334d96a --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_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 DeliveryServiceClient +from .async_client import DeliveryServiceAsyncClient + +__all__ = ( + 'DeliveryServiceClient', + 'DeliveryServiceAsyncClient', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py new file mode 100644 index 000000000000..c42f336acb5c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py @@ -0,0 +1,1558 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.maps.fleetengine_delivery_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.fleetengine_delivery_v1.services.delivery_service import pagers +from google.maps.fleetengine_delivery_v1.types import common +from google.maps.fleetengine_delivery_v1.types import delivery_api +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import task_tracking_info +from google.maps.fleetengine_delivery_v1.types import tasks +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +from .transports.base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DeliveryServiceGrpcAsyncIOTransport +from .client import DeliveryServiceClient + + +class DeliveryServiceAsyncClient: + """The Last Mile Delivery service.""" + + _client: DeliveryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = DeliveryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = DeliveryServiceClient._DEFAULT_UNIVERSE + + delivery_vehicle_path = staticmethod(DeliveryServiceClient.delivery_vehicle_path) + parse_delivery_vehicle_path = staticmethod(DeliveryServiceClient.parse_delivery_vehicle_path) + task_path = staticmethod(DeliveryServiceClient.task_path) + parse_task_path = staticmethod(DeliveryServiceClient.parse_task_path) + task_tracking_info_path = staticmethod(DeliveryServiceClient.task_tracking_info_path) + parse_task_tracking_info_path = staticmethod(DeliveryServiceClient.parse_task_tracking_info_path) + common_billing_account_path = staticmethod(DeliveryServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DeliveryServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DeliveryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DeliveryServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DeliveryServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DeliveryServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DeliveryServiceClient.common_project_path) + parse_common_project_path = staticmethod(DeliveryServiceClient.parse_common_project_path) + common_location_path = staticmethod(DeliveryServiceClient.common_location_path) + parse_common_location_path = staticmethod(DeliveryServiceClient.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: + DeliveryServiceAsyncClient: The constructed client. + """ + return DeliveryServiceClient.from_service_account_info.__func__(DeliveryServiceAsyncClient, 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: + DeliveryServiceAsyncClient: The constructed client. + """ + return DeliveryServiceClient.from_service_account_file.__func__(DeliveryServiceAsyncClient, 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 DeliveryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DeliveryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DeliveryServiceTransport: 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 = DeliveryServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DeliveryServiceTransport, Callable[..., DeliveryServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the delivery 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,DeliveryServiceTransport,Callable[..., DeliveryServiceTransport]]]): + 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 DeliveryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = DeliveryServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_delivery_vehicle(self, + request: Optional[Union[delivery_api.CreateDeliveryVehicleRequest, dict]] = None, + *, + parent: Optional[str] = None, + delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = None, + delivery_vehicle_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> delivery_vehicles.DeliveryVehicle: + r"""Creates and returns a new ``DeliveryVehicle``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_create_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( + parent="parent_value", + delivery_vehicle_id="delivery_vehicle_id_value", + ) + + # Make the request + response = await client.create_delivery_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest, dict]]): + The request object. The ``CreateDeliveryVehicle`` request message. + parent (:class:`str`): + Required. Must be in the format + ``providers/{provider}``. The provider must be the + Google Cloud Project ID. For example, + ``sample-cloud-project``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delivery_vehicle (:class:`google.maps.fleetengine_delivery_v1.types.DeliveryVehicle`): + Required. The ``DeliveryVehicle`` entity to create. When + creating a new delivery vehicle, you may set the + following optional fields: + + - type + - last_location + - attributes + + Note: The DeliveryVehicle's ``name`` field is ignored. + All other DeliveryVehicle fields must not be set; + otherwise, an error is returned. + + This corresponds to the ``delivery_vehicle`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delivery_vehicle_id (:class:`str`): + Required. The Delivery Vehicle ID must be unique and + subject to the following restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form + C] (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII + characters: '/', ':', '?', ',', or '#'. + + This corresponds to the ``delivery_vehicle_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: + The DeliveryVehicle message. A delivery vehicle transports shipments from a + depot to a delivery location, and from a pickup + location to the depot. In some cases, delivery + vehicles also transport shipments directly from the + pickup location to the delivery location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + DeliveryVehicle.current_route_segment field in the + gRPC API and the DeliveryVehicle.currentRouteSegment + field in the REST API refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, delivery_vehicle, delivery_vehicle_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, delivery_api.CreateDeliveryVehicleRequest): + request = delivery_api.CreateDeliveryVehicleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if delivery_vehicle is not None: + request.delivery_vehicle = delivery_vehicle + if delivery_vehicle_id is not None: + request.delivery_vehicle_id = delivery_vehicle_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_delivery_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_delivery_vehicle(self, + request: Optional[Union[delivery_api.GetDeliveryVehicleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> delivery_vehicles.DeliveryVehicle: + r"""Returns the specified ``DeliveryVehicle`` instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_get_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_delivery_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest, dict]]): + The request object. The ``GetDeliveryVehicle`` request message. + name (:class:`str`): + Required. Must be in the format + ``providers/{provider}/deliveryVehicles/{delivery_vehicle}``. + The ``provider`` must be the Google Cloud Project ID. + For example, ``sample-cloud-project``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: + The DeliveryVehicle message. A delivery vehicle transports shipments from a + depot to a delivery location, and from a pickup + location to the depot. In some cases, delivery + vehicles also transport shipments directly from the + pickup location to the delivery location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + DeliveryVehicle.current_route_segment field in the + gRPC API and the DeliveryVehicle.currentRouteSegment + field in the REST API refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + 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, delivery_api.GetDeliveryVehicleRequest): + request = delivery_api.GetDeliveryVehicleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_delivery_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_delivery_vehicle(self, + request: Optional[Union[delivery_api.UpdateDeliveryVehicleRequest, dict]] = None, + *, + delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = 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, str]] = (), + ) -> delivery_vehicles.DeliveryVehicle: + r"""Writes updated ``DeliveryVehicle`` data to Fleet Engine, and + assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update + the name of the ``DeliveryVehicle``. You *can* update + ``remaining_vehicle_journey_segments``, but it must contain all + of the ``VehicleJourneySegment``\ s to be persisted on the + ``DeliveryVehicle``. The ``task_id``\ s are retrieved from + ``remaining_vehicle_journey_segments``, and their corresponding + ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have + not yet been assigned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_update_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( + ) + + # Make the request + response = await client.update_delivery_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest, dict]]): + The request object. The ``UpdateDeliveryVehicle`` request message. + delivery_vehicle (:class:`google.maps.fleetengine_delivery_v1.types.DeliveryVehicle`): + Required. The ``DeliveryVehicle`` entity update to + apply. Note: You cannot update the name of the + ``DeliveryVehicle``. + + This corresponds to the ``delivery_vehicle`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask that indicates which + ``DeliveryVehicle`` fields to update. Note that the + update_mask must contain at least one field. + + This is a comma-separated list of fully qualified names + of fields. Example: + ``"remaining_vehicle_journey_segments"``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: + The DeliveryVehicle message. A delivery vehicle transports shipments from a + depot to a delivery location, and from a pickup + location to the depot. In some cases, delivery + vehicles also transport shipments directly from the + pickup location to the delivery location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + DeliveryVehicle.current_route_segment field in the + gRPC API and the DeliveryVehicle.currentRouteSegment + field in the REST API refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([delivery_vehicle, 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, delivery_api.UpdateDeliveryVehicleRequest): + request = delivery_api.UpdateDeliveryVehicleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if delivery_vehicle is not None: + request.delivery_vehicle = delivery_vehicle + 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_delivery_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.delivery_vehicle.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_tasks(self, + request: Optional[Union[delivery_api.BatchCreateTasksRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> delivery_api.BatchCreateTasksResponse: + r"""Creates and returns a batch of new ``Task`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_batch_create_tasks(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + requests = fleetengine_delivery_v1.CreateTaskRequest() + requests.parent = "parent_value" + requests.task_id = "task_id_value" + requests.task.type_ = "UNAVAILABLE" + requests.task.state = "CLOSED" + + request = fleetengine_delivery_v1.BatchCreateTasksRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_tasks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest, dict]]): + The request object. The ``BatchCreateTask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse: + The BatchCreateTask 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, delivery_api.BatchCreateTasksRequest): + request = delivery_api.BatchCreateTasksRequest(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_create_tasks] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_task(self, + request: Optional[Union[delivery_api.CreateTaskRequest, dict]] = None, + *, + parent: Optional[str] = None, + task: Optional[tasks.Task] = None, + task_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tasks.Task: + r"""Creates and returns a new ``Task`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_create_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + task = fleetengine_delivery_v1.Task() + task.type_ = "UNAVAILABLE" + task.state = "CLOSED" + + request = fleetengine_delivery_v1.CreateTaskRequest( + parent="parent_value", + task_id="task_id_value", + task=task, + ) + + # Make the request + response = await client.create_task(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.CreateTaskRequest, dict]]): + The request object. The ``CreateTask`` request message. + parent (:class:`str`): + Required. Must be in the format + ``providers/{provider}``. The ``provider`` must be the + Google Cloud Project ID. For example, + ``sample-cloud-project``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + task (:class:`google.maps.fleetengine_delivery_v1.types.Task`): + Required. The Task entity to create. When creating a + Task, the following fields are required: + + - ``type`` + - ``state`` (must be set to ``OPEN``) + - ``tracking_id`` (must not be set for ``UNAVAILABLE`` + or ``SCHEDULED_STOP`` tasks, but required for all + other task types) + - ``planned_location`` (optional for ``UNAVAILABLE`` + tasks) + - ``task_duration`` + + Note: The Task's ``name`` field is ignored. All other + Task fields must not be set; otherwise, an error is + returned. + + This corresponds to the ``task`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + task_id (:class:`str`): + Required. The Task ID must be unique, but it should be + not a shipment tracking ID. To store a shipment tracking + ID, use the ``tracking_id`` field. Note that multiple + tasks can have the same ``tracking_id``. Task IDs are + subject to the following restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form + C] (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII + characters: '/', ':', '?', ',', or '#'. + + This corresponds to the ``task_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.Task: + A Task in the Delivery API represents a single action to track. In general, + there is a distinction between shipment-related Tasks + and break Tasks. A shipment can have multiple Tasks + associated with it. For example, there could be one + Task for the pickup, and one for the drop-off or + transfer. Also, different Tasks for a given shipment + can be handled by different vehicles. For example, + one vehicle could handle the pickup, driving the + shipment to the hub, while another vehicle drives the + same shipment from the hub to the drop-off location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + Task.journey_sharing_info field in the gRPC API and + the Task.journeySharingInfo field in the REST API + refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, task, task_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, delivery_api.CreateTaskRequest): + request = delivery_api.CreateTaskRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if task is not None: + request.task = task + if task_id is not None: + request.task_id = task_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_task] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_task(self, + request: Optional[Union[delivery_api.GetTaskRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tasks.Task: + r"""Gets information about a ``Task``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_get_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetTaskRequest( + name="name_value", + ) + + # Make the request + response = await client.get_task(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.GetTaskRequest, dict]]): + The request object. The ``GetTask`` request message. + name (:class:`str`): + Required. Must be in the format + ``providers/{provider}/tasks/{task}``. The ``provider`` + must be the Google Cloud Project ID. For example, + ``sample-cloud-project``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.Task: + A Task in the Delivery API represents a single action to track. In general, + there is a distinction between shipment-related Tasks + and break Tasks. A shipment can have multiple Tasks + associated with it. For example, there could be one + Task for the pickup, and one for the drop-off or + transfer. Also, different Tasks for a given shipment + can be handled by different vehicles. For example, + one vehicle could handle the pickup, driving the + shipment to the hub, while another vehicle drives the + same shipment from the hub to the drop-off location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + Task.journey_sharing_info field in the gRPC API and + the Task.journeySharingInfo field in the REST API + refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + 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, delivery_api.GetTaskRequest): + request = delivery_api.GetTaskRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_task] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_task(self, + request: Optional[Union[delivery_api.UpdateTaskRequest, dict]] = None, + *, + task: Optional[tasks.Task] = 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, str]] = (), + ) -> tasks.Task: + r"""Updates ``Task`` data. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_update_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + task = fleetengine_delivery_v1.Task() + task.type_ = "UNAVAILABLE" + task.state = "CLOSED" + + request = fleetengine_delivery_v1.UpdateTaskRequest( + task=task, + ) + + # Make the request + response = await client.update_task(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest, dict]]): + The request object. The ``UpdateTask`` request message. + task (:class:`google.maps.fleetengine_delivery_v1.types.Task`): + Required. The Task associated with the update. The + following fields are maintained by Fleet Engine. Do not + update them using ``Task.update``. + + - ``last_location``. + - ``last_location_snappable``. + - ``name``. + - ``remaining_vehicle_journey_segments``. + - ``task_outcome_location_source``. + + Note: You cannot change the value of ``task_outcome`` + once you set it. + + If the Task has been assigned to a delivery vehicle, + then don't set the Task state to CLOSED using + ``Task.update``. Instead, remove the ``VehicleStop`` + that contains the Task from the delivery vehicle, which + automatically sets the Task state to CLOSED. + + This corresponds to the ``task`` 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 field mask that indicates which Task + fields to update. Note: The ``update_mask`` must contain + at least one field. + + This is a comma-separated list of fully qualified names + of fields. Example: + ``"task_outcome,task_outcome_time,task_outcome_location"``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.Task: + A Task in the Delivery API represents a single action to track. In general, + there is a distinction between shipment-related Tasks + and break Tasks. A shipment can have multiple Tasks + associated with it. For example, there could be one + Task for the pickup, and one for the drop-off or + transfer. Also, different Tasks for a given shipment + can be handled by different vehicles. For example, + one vehicle could handle the pickup, driving the + shipment to the hub, while another vehicle drives the + same shipment from the hub to the drop-off location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + Task.journey_sharing_info field in the gRPC API and + the Task.journeySharingInfo field in the REST API + refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([task, 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, delivery_api.UpdateTaskRequest): + request = delivery_api.UpdateTaskRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if task is not None: + request.task = task + 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_task] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.task.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_tasks(self, + request: Optional[Union[delivery_api.ListTasksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTasksAsyncPager: + r"""Gets all ``Task``\ s that meet the specified filtering criteria. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_list_tasks(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.ListTasksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tasks(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.ListTasksRequest, dict]]): + The request object. The ``ListTasks`` request message. + parent (:class:`str`): + Required. Must be in the format + ``providers/{provider}``. The ``provider`` must be the + Google Cloud Project ID. For example, + ``sample-cloud-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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksAsyncPager: + The ListTasks response that contains the set of Tasks that meet the filter + criteria in the ListTasksRequest. + + 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, delivery_api.ListTasksRequest): + request = delivery_api.ListTasksRequest(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_tasks] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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.ListTasksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_task_tracking_info(self, + request: Optional[Union[delivery_api.GetTaskTrackingInfoRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> task_tracking_info.TaskTrackingInfo: + r"""Returns the specified ``TaskTrackingInfo`` instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_get_task_tracking_info(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( + name="name_value", + ) + + # Make the request + response = await client.get_task_tracking_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest, dict]]): + The request object. The ``GetTaskTrackingInfoRequest`` request message. + name (:class:`str`): + Required. Must be in the format + ``providers/{provider}/taskTrackingInfo/{tracking_id}``. + The ``provider`` must be the Google Cloud Project ID, + and the ``tracking_id`` must be the tracking ID + associated with the task. An example name can be + ``providers/sample-cloud-project/taskTrackingInfo/sample-tracking-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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo: + The TaskTrackingInfo message. The message contains task tracking + information which will be used for display. If a + tracking ID is associated with multiple Tasks, Fleet + Engine uses a heuristic to decide which Task's + TaskTrackingInfo to select. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, delivery_api.GetTaskTrackingInfoRequest): + request = delivery_api.GetTaskTrackingInfoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_task_tracking_info] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_delivery_vehicles(self, + request: Optional[Union[delivery_api.ListDeliveryVehiclesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeliveryVehiclesAsyncPager: + r"""Gets all ``DeliveryVehicle``\ s that meet the specified + filtering criteria. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + async def sample_list_delivery_vehicles(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_delivery_vehicles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest, dict]]): + The request object. The ``ListDeliveryVehicles`` request message. + parent (:class:`str`): + Required. Must be in the format + ``providers/{provider}``. The ``provider`` must be the + Google Cloud Project ID. For example, + ``sample-cloud-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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesAsyncPager: + The ListDeliveryVehicles response message. + + 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, delivery_api.ListDeliveryVehiclesRequest): + request = delivery_api.ListDeliveryVehiclesRequest(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_delivery_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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.ListDeliveryVehiclesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "DeliveryServiceAsyncClient": + 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__ = ( + "DeliveryServiceAsyncClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py new file mode 100644 index 000000000000..c4eae523cd1f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py @@ -0,0 +1,1924 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.maps.fleetengine_delivery_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 + +from google.maps.fleetengine_delivery_v1.services.delivery_service import pagers +from google.maps.fleetengine_delivery_v1.types import common +from google.maps.fleetengine_delivery_v1.types import delivery_api +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import task_tracking_info +from google.maps.fleetengine_delivery_v1.types import tasks +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +from .transports.base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DeliveryServiceGrpcTransport +from .transports.grpc_asyncio import DeliveryServiceGrpcAsyncIOTransport +from .transports.rest import DeliveryServiceRestTransport + + +class DeliveryServiceClientMeta(type): + """Metaclass for the DeliveryService 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[DeliveryServiceTransport]] + _transport_registry["grpc"] = DeliveryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DeliveryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DeliveryServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DeliveryServiceTransport]: + """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 DeliveryServiceClient(metaclass=DeliveryServiceClientMeta): + """The Last Mile Delivery service.""" + + @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 = "fleetengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: + DeliveryServiceClient: 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: + DeliveryServiceClient: 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) -> DeliveryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DeliveryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def delivery_vehicle_path(provider: str,vehicle: str,) -> str: + """Returns a fully-qualified delivery_vehicle string.""" + return "providers/{provider}/deliveryVehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) + + @staticmethod + def parse_delivery_vehicle_path(path: str) -> Dict[str,str]: + """Parses a delivery_vehicle path into its component segments.""" + m = re.match(r"^providers/(?P.+?)/deliveryVehicles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def task_path(provider: str,task: str,) -> str: + """Returns a fully-qualified task string.""" + return "providers/{provider}/tasks/{task}".format(provider=provider, task=task, ) + + @staticmethod + def parse_task_path(path: str) -> Dict[str,str]: + """Parses a task path into its component segments.""" + m = re.match(r"^providers/(?P.+?)/tasks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def task_tracking_info_path(provider: str,tracking: str,) -> str: + """Returns a fully-qualified task_tracking_info string.""" + return "providers/{provider}/taskTrackingInfo/{tracking}".format(provider=provider, tracking=tracking, ) + + @staticmethod + def parse_task_tracking_info_path(path: str) -> Dict[str,str]: + """Parses a task_tracking_info path into its component segments.""" + m = re.match(r"^providers/(?P.+?)/taskTrackingInfo/(?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 = DeliveryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = DeliveryServiceClient._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 = DeliveryServiceClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = DeliveryServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + DeliveryServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, DeliveryServiceTransport, Callable[..., DeliveryServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the delivery 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,DeliveryServiceTransport,Callable[..., DeliveryServiceTransport]]]): + 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 DeliveryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = DeliveryServiceClient._read_environment_variables() + self._client_cert_source = DeliveryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = DeliveryServiceClient._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 + + 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, DeliveryServiceTransport) + if transport_provided: + # transport is a DeliveryServiceTransport 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(DeliveryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + DeliveryServiceClient._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[DeliveryServiceTransport], Callable[..., DeliveryServiceTransport]] = ( + DeliveryServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., DeliveryServiceTransport], 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, + ) + + def create_delivery_vehicle(self, + request: Optional[Union[delivery_api.CreateDeliveryVehicleRequest, dict]] = None, + *, + parent: Optional[str] = None, + delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = None, + delivery_vehicle_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> delivery_vehicles.DeliveryVehicle: + r"""Creates and returns a new ``DeliveryVehicle``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_create_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( + parent="parent_value", + delivery_vehicle_id="delivery_vehicle_id_value", + ) + + # Make the request + response = client.create_delivery_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest, dict]): + The request object. The ``CreateDeliveryVehicle`` request message. + parent (str): + Required. Must be in the format + ``providers/{provider}``. The provider must be the + Google Cloud Project ID. For example, + ``sample-cloud-project``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): + Required. The ``DeliveryVehicle`` entity to create. When + creating a new delivery vehicle, you may set the + following optional fields: + + - type + - last_location + - attributes + + Note: The DeliveryVehicle's ``name`` field is ignored. + All other DeliveryVehicle fields must not be set; + otherwise, an error is returned. + + This corresponds to the ``delivery_vehicle`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + delivery_vehicle_id (str): + Required. The Delivery Vehicle ID must be unique and + subject to the following restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form + C] (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII + characters: '/', ':', '?', ',', or '#'. + + This corresponds to the ``delivery_vehicle_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: + The DeliveryVehicle message. A delivery vehicle transports shipments from a + depot to a delivery location, and from a pickup + location to the depot. In some cases, delivery + vehicles also transport shipments directly from the + pickup location to the delivery location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + DeliveryVehicle.current_route_segment field in the + gRPC API and the DeliveryVehicle.currentRouteSegment + field in the REST API refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, delivery_vehicle, delivery_vehicle_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, delivery_api.CreateDeliveryVehicleRequest): + request = delivery_api.CreateDeliveryVehicleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if delivery_vehicle is not None: + request.delivery_vehicle = delivery_vehicle + if delivery_vehicle_id is not None: + request.delivery_vehicle_id = delivery_vehicle_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_delivery_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_delivery_vehicle(self, + request: Optional[Union[delivery_api.GetDeliveryVehicleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> delivery_vehicles.DeliveryVehicle: + r"""Returns the specified ``DeliveryVehicle`` instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_get_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.get_delivery_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest, dict]): + The request object. The ``GetDeliveryVehicle`` request message. + name (str): + Required. Must be in the format + ``providers/{provider}/deliveryVehicles/{delivery_vehicle}``. + The ``provider`` must be the Google Cloud Project ID. + For example, ``sample-cloud-project``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: + The DeliveryVehicle message. A delivery vehicle transports shipments from a + depot to a delivery location, and from a pickup + location to the depot. In some cases, delivery + vehicles also transport shipments directly from the + pickup location to the delivery location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + DeliveryVehicle.current_route_segment field in the + gRPC API and the DeliveryVehicle.currentRouteSegment + field in the REST API refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + 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, delivery_api.GetDeliveryVehicleRequest): + request = delivery_api.GetDeliveryVehicleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_delivery_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_delivery_vehicle(self, + request: Optional[Union[delivery_api.UpdateDeliveryVehicleRequest, dict]] = None, + *, + delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = 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, str]] = (), + ) -> delivery_vehicles.DeliveryVehicle: + r"""Writes updated ``DeliveryVehicle`` data to Fleet Engine, and + assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update + the name of the ``DeliveryVehicle``. You *can* update + ``remaining_vehicle_journey_segments``, but it must contain all + of the ``VehicleJourneySegment``\ s to be persisted on the + ``DeliveryVehicle``. The ``task_id``\ s are retrieved from + ``remaining_vehicle_journey_segments``, and their corresponding + ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have + not yet been assigned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_update_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( + ) + + # Make the request + response = client.update_delivery_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest, dict]): + The request object. The ``UpdateDeliveryVehicle`` request message. + delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): + Required. The ``DeliveryVehicle`` entity update to + apply. Note: You cannot update the name of the + ``DeliveryVehicle``. + + This corresponds to the ``delivery_vehicle`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask that indicates which + ``DeliveryVehicle`` fields to update. Note that the + update_mask must contain at least one field. + + This is a comma-separated list of fully qualified names + of fields. Example: + ``"remaining_vehicle_journey_segments"``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: + The DeliveryVehicle message. A delivery vehicle transports shipments from a + depot to a delivery location, and from a pickup + location to the depot. In some cases, delivery + vehicles also transport shipments directly from the + pickup location to the delivery location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + DeliveryVehicle.current_route_segment field in the + gRPC API and the DeliveryVehicle.currentRouteSegment + field in the REST API refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([delivery_vehicle, 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, delivery_api.UpdateDeliveryVehicleRequest): + request = delivery_api.UpdateDeliveryVehicleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if delivery_vehicle is not None: + request.delivery_vehicle = delivery_vehicle + 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_delivery_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.delivery_vehicle.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_tasks(self, + request: Optional[Union[delivery_api.BatchCreateTasksRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> delivery_api.BatchCreateTasksResponse: + r"""Creates and returns a batch of new ``Task`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_batch_create_tasks(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + requests = fleetengine_delivery_v1.CreateTaskRequest() + requests.parent = "parent_value" + requests.task_id = "task_id_value" + requests.task.type_ = "UNAVAILABLE" + requests.task.state = "CLOSED" + + request = fleetengine_delivery_v1.BatchCreateTasksRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_tasks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest, dict]): + The request object. The ``BatchCreateTask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse: + The BatchCreateTask 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, delivery_api.BatchCreateTasksRequest): + request = delivery_api.BatchCreateTasksRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_tasks] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_task(self, + request: Optional[Union[delivery_api.CreateTaskRequest, dict]] = None, + *, + parent: Optional[str] = None, + task: Optional[tasks.Task] = None, + task_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tasks.Task: + r"""Creates and returns a new ``Task`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_create_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + task = fleetengine_delivery_v1.Task() + task.type_ = "UNAVAILABLE" + task.state = "CLOSED" + + request = fleetengine_delivery_v1.CreateTaskRequest( + parent="parent_value", + task_id="task_id_value", + task=task, + ) + + # Make the request + response = client.create_task(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.CreateTaskRequest, dict]): + The request object. The ``CreateTask`` request message. + parent (str): + Required. Must be in the format + ``providers/{provider}``. The ``provider`` must be the + Google Cloud Project ID. For example, + ``sample-cloud-project``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + task (google.maps.fleetengine_delivery_v1.types.Task): + Required. The Task entity to create. When creating a + Task, the following fields are required: + + - ``type`` + - ``state`` (must be set to ``OPEN``) + - ``tracking_id`` (must not be set for ``UNAVAILABLE`` + or ``SCHEDULED_STOP`` tasks, but required for all + other task types) + - ``planned_location`` (optional for ``UNAVAILABLE`` + tasks) + - ``task_duration`` + + Note: The Task's ``name`` field is ignored. All other + Task fields must not be set; otherwise, an error is + returned. + + This corresponds to the ``task`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + task_id (str): + Required. The Task ID must be unique, but it should be + not a shipment tracking ID. To store a shipment tracking + ID, use the ``tracking_id`` field. Note that multiple + tasks can have the same ``tracking_id``. Task IDs are + subject to the following restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form + C] (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII + characters: '/', ':', '?', ',', or '#'. + + This corresponds to the ``task_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.Task: + A Task in the Delivery API represents a single action to track. In general, + there is a distinction between shipment-related Tasks + and break Tasks. A shipment can have multiple Tasks + associated with it. For example, there could be one + Task for the pickup, and one for the drop-off or + transfer. Also, different Tasks for a given shipment + can be handled by different vehicles. For example, + one vehicle could handle the pickup, driving the + shipment to the hub, while another vehicle drives the + same shipment from the hub to the drop-off location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + Task.journey_sharing_info field in the gRPC API and + the Task.journeySharingInfo field in the REST API + refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, task, task_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, delivery_api.CreateTaskRequest): + request = delivery_api.CreateTaskRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if task is not None: + request.task = task + if task_id is not None: + request.task_id = task_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_task] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_task(self, + request: Optional[Union[delivery_api.GetTaskRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tasks.Task: + r"""Gets information about a ``Task``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_get_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetTaskRequest( + name="name_value", + ) + + # Make the request + response = client.get_task(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.GetTaskRequest, dict]): + The request object. The ``GetTask`` request message. + name (str): + Required. Must be in the format + ``providers/{provider}/tasks/{task}``. The ``provider`` + must be the Google Cloud Project ID. For example, + ``sample-cloud-project``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.Task: + A Task in the Delivery API represents a single action to track. In general, + there is a distinction between shipment-related Tasks + and break Tasks. A shipment can have multiple Tasks + associated with it. For example, there could be one + Task for the pickup, and one for the drop-off or + transfer. Also, different Tasks for a given shipment + can be handled by different vehicles. For example, + one vehicle could handle the pickup, driving the + shipment to the hub, while another vehicle drives the + same shipment from the hub to the drop-off location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + Task.journey_sharing_info field in the gRPC API and + the Task.journeySharingInfo field in the REST API + refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + 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, delivery_api.GetTaskRequest): + request = delivery_api.GetTaskRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_task] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_task(self, + request: Optional[Union[delivery_api.UpdateTaskRequest, dict]] = None, + *, + task: Optional[tasks.Task] = 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, str]] = (), + ) -> tasks.Task: + r"""Updates ``Task`` data. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_update_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + task = fleetengine_delivery_v1.Task() + task.type_ = "UNAVAILABLE" + task.state = "CLOSED" + + request = fleetengine_delivery_v1.UpdateTaskRequest( + task=task, + ) + + # Make the request + response = client.update_task(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest, dict]): + The request object. The ``UpdateTask`` request message. + task (google.maps.fleetengine_delivery_v1.types.Task): + Required. The Task associated with the update. The + following fields are maintained by Fleet Engine. Do not + update them using ``Task.update``. + + - ``last_location``. + - ``last_location_snappable``. + - ``name``. + - ``remaining_vehicle_journey_segments``. + - ``task_outcome_location_source``. + + Note: You cannot change the value of ``task_outcome`` + once you set it. + + If the Task has been assigned to a delivery vehicle, + then don't set the Task state to CLOSED using + ``Task.update``. Instead, remove the ``VehicleStop`` + that contains the Task from the delivery vehicle, which + automatically sets the Task state to CLOSED. + + This corresponds to the ``task`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field mask that indicates which Task + fields to update. Note: The ``update_mask`` must contain + at least one field. + + This is a comma-separated list of fully qualified names + of fields. Example: + ``"task_outcome,task_outcome_time,task_outcome_location"``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.Task: + A Task in the Delivery API represents a single action to track. In general, + there is a distinction between shipment-related Tasks + and break Tasks. A shipment can have multiple Tasks + associated with it. For example, there could be one + Task for the pickup, and one for the drop-off or + transfer. Also, different Tasks for a given shipment + can be handled by different vehicles. For example, + one vehicle could handle the pickup, driving the + shipment to the hub, while another vehicle drives the + same shipment from the hub to the drop-off location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + Task.journey_sharing_info field in the gRPC API and + the Task.journeySharingInfo field in the REST API + refer to the same field. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([task, 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, delivery_api.UpdateTaskRequest): + request = delivery_api.UpdateTaskRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if task is not None: + request.task = task + 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_task] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.task.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_tasks(self, + request: Optional[Union[delivery_api.ListTasksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTasksPager: + r"""Gets all ``Task``\ s that meet the specified filtering criteria. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_list_tasks(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.ListTasksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tasks(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.ListTasksRequest, dict]): + The request object. The ``ListTasks`` request message. + parent (str): + Required. Must be in the format + ``providers/{provider}``. The ``provider`` must be the + Google Cloud Project ID. For example, + ``sample-cloud-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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksPager: + The ListTasks response that contains the set of Tasks that meet the filter + criteria in the ListTasksRequest. + + 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, delivery_api.ListTasksRequest): + request = delivery_api.ListTasksRequest(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_tasks] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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.ListTasksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_task_tracking_info(self, + request: Optional[Union[delivery_api.GetTaskTrackingInfoRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> task_tracking_info.TaskTrackingInfo: + r"""Returns the specified ``TaskTrackingInfo`` instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_get_task_tracking_info(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( + name="name_value", + ) + + # Make the request + response = client.get_task_tracking_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest, dict]): + The request object. The ``GetTaskTrackingInfoRequest`` request message. + name (str): + Required. Must be in the format + ``providers/{provider}/taskTrackingInfo/{tracking_id}``. + The ``provider`` must be the Google Cloud Project ID, + and the ``tracking_id`` must be the tracking ID + associated with the task. An example name can be + ``providers/sample-cloud-project/taskTrackingInfo/sample-tracking-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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo: + The TaskTrackingInfo message. The message contains task tracking + information which will be used for display. If a + tracking ID is associated with multiple Tasks, Fleet + Engine uses a heuristic to decide which Task's + TaskTrackingInfo to select. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, delivery_api.GetTaskTrackingInfoRequest): + request = delivery_api.GetTaskTrackingInfoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_task_tracking_info] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_delivery_vehicles(self, + request: Optional[Union[delivery_api.ListDeliveryVehiclesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeliveryVehiclesPager: + r"""Gets all ``DeliveryVehicle``\ s that meet the specified + filtering criteria. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_delivery_v1 + + def sample_list_delivery_vehicles(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_delivery_vehicles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest, dict]): + The request object. The ``ListDeliveryVehicles`` request message. + parent (str): + Required. Must be in the format + ``providers/{provider}``. The ``provider`` must be the + Google Cloud Project ID. For example, + ``sample-cloud-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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesPager: + The ListDeliveryVehicles response message. + + 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, delivery_api.ListDeliveryVehiclesRequest): + request = delivery_api.ListDeliveryVehiclesRequest(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_delivery_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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.ListDeliveryVehiclesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DeliveryServiceClient": + 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__ = ( + "DeliveryServiceClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py new file mode 100644 index 000000000000..71e6a9f33252 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.fleetengine_delivery_v1.types import delivery_api +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import tasks + + +class ListTasksPager: + """A pager for iterating through ``list_tasks`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tasks`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTasks`` requests and continue to iterate + through the ``tasks`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., delivery_api.ListTasksResponse], + request: delivery_api.ListTasksRequest, + response: delivery_api.ListTasksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_delivery_v1.types.ListTasksRequest): + The initial request object. + response (google.maps.fleetengine_delivery_v1.types.ListTasksResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = delivery_api.ListTasksRequest(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[delivery_api.ListTasksResponse]: + 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[tasks.Task]: + for page in self.pages: + yield from page.tasks + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTasksAsyncPager: + """A pager for iterating through ``list_tasks`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tasks`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTasks`` requests and continue to iterate + through the ``tasks`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` + attributes are available on the 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[delivery_api.ListTasksResponse]], + request: delivery_api.ListTasksRequest, + response: delivery_api.ListTasksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_delivery_v1.types.ListTasksRequest): + The initial request object. + response (google.maps.fleetengine_delivery_v1.types.ListTasksResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = delivery_api.ListTasksRequest(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[delivery_api.ListTasksResponse]: + 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[tasks.Task]: + async def async_generator(): + async for page in self.pages: + for response in page.tasks: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDeliveryVehiclesPager: + """A pager for iterating through ``list_delivery_vehicles`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``delivery_vehicles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDeliveryVehicles`` requests and continue to iterate + through the ``delivery_vehicles`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., delivery_api.ListDeliveryVehiclesResponse], + request: delivery_api.ListDeliveryVehiclesRequest, + response: delivery_api.ListDeliveryVehiclesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest): + The initial request object. + response (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = delivery_api.ListDeliveryVehiclesRequest(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[delivery_api.ListDeliveryVehiclesResponse]: + 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[delivery_vehicles.DeliveryVehicle]: + for page in self.pages: + yield from page.delivery_vehicles + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDeliveryVehiclesAsyncPager: + """A pager for iterating through ``list_delivery_vehicles`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``delivery_vehicles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDeliveryVehicles`` requests and continue to iterate + through the ``delivery_vehicles`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` + attributes are available on the 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[delivery_api.ListDeliveryVehiclesResponse]], + request: delivery_api.ListDeliveryVehiclesRequest, + response: delivery_api.ListDeliveryVehiclesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest): + The initial request object. + response (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = delivery_api.ListDeliveryVehiclesRequest(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[delivery_api.ListDeliveryVehiclesResponse]: + 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[delivery_vehicles.DeliveryVehicle]: + async def async_generator(): + async for page in self.pages: + for response in page.delivery_vehicles: + 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-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/README.rst new file mode 100644 index 000000000000..db6050755ee5 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`DeliveryServiceTransport` is the ABC for all transports. +- public child `DeliveryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `DeliveryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseDeliveryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `DeliveryServiceRestTransport` 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-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py new file mode 100644 index 000000000000..bdf0ae0905a7 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_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 DeliveryServiceTransport +from .grpc import DeliveryServiceGrpcTransport +from .grpc_asyncio import DeliveryServiceGrpcAsyncIOTransport +from .rest import DeliveryServiceRestTransport +from .rest import DeliveryServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DeliveryServiceTransport]] +_transport_registry['grpc'] = DeliveryServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DeliveryServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DeliveryServiceRestTransport + +__all__ = ( + 'DeliveryServiceTransport', + 'DeliveryServiceGrpcTransport', + 'DeliveryServiceGrpcAsyncIOTransport', + 'DeliveryServiceRestTransport', + 'DeliveryServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py new file mode 100644 index 000000000000..fba0b4384257 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py @@ -0,0 +1,373 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.fleetengine_delivery_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.fleetengine_delivery_v1.types import delivery_api +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import task_tracking_info +from google.maps.fleetengine_delivery_v1.types import tasks + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DeliveryServiceTransport(abc.ABC): + """Abstract transport class for DeliveryService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_delivery_vehicle: gapic_v1.method.wrap_method( + self.create_delivery_vehicle, + 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_delivery_vehicle: gapic_v1.method.wrap_method( + self.get_delivery_vehicle, + 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.update_delivery_vehicle: gapic_v1.method.wrap_method( + self.update_delivery_vehicle, + 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.batch_create_tasks: gapic_v1.method.wrap_method( + self.batch_create_tasks, + 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.create_task: gapic_v1.method.wrap_method( + self.create_task, + 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_task: gapic_v1.method.wrap_method( + self.get_task, + 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.update_task: gapic_v1.method.wrap_method( + self.update_task, + 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_tasks: gapic_v1.method.wrap_method( + self.list_tasks, + 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_task_tracking_info: gapic_v1.method.wrap_method( + self.get_task_tracking_info, + 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_delivery_vehicles: gapic_v1.method.wrap_method( + self.list_delivery_vehicles, + 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 create_delivery_vehicle(self) -> Callable[ + [delivery_api.CreateDeliveryVehicleRequest], + Union[ + delivery_vehicles.DeliveryVehicle, + Awaitable[delivery_vehicles.DeliveryVehicle] + ]]: + raise NotImplementedError() + + @property + def get_delivery_vehicle(self) -> Callable[ + [delivery_api.GetDeliveryVehicleRequest], + Union[ + delivery_vehicles.DeliveryVehicle, + Awaitable[delivery_vehicles.DeliveryVehicle] + ]]: + raise NotImplementedError() + + @property + def update_delivery_vehicle(self) -> Callable[ + [delivery_api.UpdateDeliveryVehicleRequest], + Union[ + delivery_vehicles.DeliveryVehicle, + Awaitable[delivery_vehicles.DeliveryVehicle] + ]]: + raise NotImplementedError() + + @property + def batch_create_tasks(self) -> Callable[ + [delivery_api.BatchCreateTasksRequest], + Union[ + delivery_api.BatchCreateTasksResponse, + Awaitable[delivery_api.BatchCreateTasksResponse] + ]]: + raise NotImplementedError() + + @property + def create_task(self) -> Callable[ + [delivery_api.CreateTaskRequest], + Union[ + tasks.Task, + Awaitable[tasks.Task] + ]]: + raise NotImplementedError() + + @property + def get_task(self) -> Callable[ + [delivery_api.GetTaskRequest], + Union[ + tasks.Task, + Awaitable[tasks.Task] + ]]: + raise NotImplementedError() + + @property + def update_task(self) -> Callable[ + [delivery_api.UpdateTaskRequest], + Union[ + tasks.Task, + Awaitable[tasks.Task] + ]]: + raise NotImplementedError() + + @property + def list_tasks(self) -> Callable[ + [delivery_api.ListTasksRequest], + Union[ + delivery_api.ListTasksResponse, + Awaitable[delivery_api.ListTasksResponse] + ]]: + raise NotImplementedError() + + @property + def get_task_tracking_info(self) -> Callable[ + [delivery_api.GetTaskTrackingInfoRequest], + Union[ + task_tracking_info.TaskTrackingInfo, + Awaitable[task_tracking_info.TaskTrackingInfo] + ]]: + raise NotImplementedError() + + @property + def list_delivery_vehicles(self) -> Callable[ + [delivery_api.ListDeliveryVehiclesRequest], + Union[ + delivery_api.ListDeliveryVehiclesResponse, + Awaitable[delivery_api.ListDeliveryVehiclesResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DeliveryServiceTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py new file mode 100644 index 000000000000..03a7d345d054 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py @@ -0,0 +1,516 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.maps.fleetengine_delivery_v1.types import delivery_api +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import task_tracking_info +from google.maps.fleetengine_delivery_v1.types import tasks +from .base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO + + +class DeliveryServiceGrpcTransport(DeliveryServiceTransport): + """gRPC backend transport for DeliveryService. + + The Last Mile Delivery service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'fleetengine.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: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'fleetengine.googleapis.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_delivery_vehicle(self) -> Callable[ + [delivery_api.CreateDeliveryVehicleRequest], + delivery_vehicles.DeliveryVehicle]: + r"""Return a callable for the create delivery vehicle method over gRPC. + + Creates and returns a new ``DeliveryVehicle``. + + Returns: + Callable[[~.CreateDeliveryVehicleRequest], + ~.DeliveryVehicle]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: + self._stubs['create_delivery_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/CreateDeliveryVehicle', + request_serializer=delivery_api.CreateDeliveryVehicleRequest.serialize, + response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, + ) + return self._stubs['create_delivery_vehicle'] + + @property + def get_delivery_vehicle(self) -> Callable[ + [delivery_api.GetDeliveryVehicleRequest], + delivery_vehicles.DeliveryVehicle]: + r"""Return a callable for the get delivery vehicle method over gRPC. + + Returns the specified ``DeliveryVehicle`` instance. + + Returns: + Callable[[~.GetDeliveryVehicleRequest], + ~.DeliveryVehicle]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: + self._stubs['get_delivery_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/GetDeliveryVehicle', + request_serializer=delivery_api.GetDeliveryVehicleRequest.serialize, + response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, + ) + return self._stubs['get_delivery_vehicle'] + + @property + def update_delivery_vehicle(self) -> Callable[ + [delivery_api.UpdateDeliveryVehicleRequest], + delivery_vehicles.DeliveryVehicle]: + r"""Return a callable for the update delivery vehicle method over gRPC. + + Writes updated ``DeliveryVehicle`` data to Fleet Engine, and + assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update + the name of the ``DeliveryVehicle``. You *can* update + ``remaining_vehicle_journey_segments``, but it must contain all + of the ``VehicleJourneySegment``\ s to be persisted on the + ``DeliveryVehicle``. The ``task_id``\ s are retrieved from + ``remaining_vehicle_journey_segments``, and their corresponding + ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have + not yet been assigned. + + Returns: + Callable[[~.UpdateDeliveryVehicleRequest], + ~.DeliveryVehicle]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: + self._stubs['update_delivery_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/UpdateDeliveryVehicle', + request_serializer=delivery_api.UpdateDeliveryVehicleRequest.serialize, + response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, + ) + return self._stubs['update_delivery_vehicle'] + + @property + def batch_create_tasks(self) -> Callable[ + [delivery_api.BatchCreateTasksRequest], + delivery_api.BatchCreateTasksResponse]: + r"""Return a callable for the batch create tasks method over gRPC. + + Creates and returns a batch of new ``Task`` objects. + + Returns: + Callable[[~.BatchCreateTasksRequest], + ~.BatchCreateTasksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tasks' not in self._stubs: + self._stubs['batch_create_tasks'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/BatchCreateTasks', + request_serializer=delivery_api.BatchCreateTasksRequest.serialize, + response_deserializer=delivery_api.BatchCreateTasksResponse.deserialize, + ) + return self._stubs['batch_create_tasks'] + + @property + def create_task(self) -> Callable[ + [delivery_api.CreateTaskRequest], + tasks.Task]: + r"""Return a callable for the create task method over gRPC. + + Creates and returns a new ``Task`` object. + + Returns: + Callable[[~.CreateTaskRequest], + ~.Task]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_task' not in self._stubs: + self._stubs['create_task'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/CreateTask', + request_serializer=delivery_api.CreateTaskRequest.serialize, + response_deserializer=tasks.Task.deserialize, + ) + return self._stubs['create_task'] + + @property + def get_task(self) -> Callable[ + [delivery_api.GetTaskRequest], + tasks.Task]: + r"""Return a callable for the get task method over gRPC. + + Gets information about a ``Task``. + + Returns: + Callable[[~.GetTaskRequest], + ~.Task]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_task' not in self._stubs: + self._stubs['get_task'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/GetTask', + request_serializer=delivery_api.GetTaskRequest.serialize, + response_deserializer=tasks.Task.deserialize, + ) + return self._stubs['get_task'] + + @property + def update_task(self) -> Callable[ + [delivery_api.UpdateTaskRequest], + tasks.Task]: + r"""Return a callable for the update task method over gRPC. + + Updates ``Task`` data. + + Returns: + Callable[[~.UpdateTaskRequest], + ~.Task]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_task' not in self._stubs: + self._stubs['update_task'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/UpdateTask', + request_serializer=delivery_api.UpdateTaskRequest.serialize, + response_deserializer=tasks.Task.deserialize, + ) + return self._stubs['update_task'] + + @property + def list_tasks(self) -> Callable[ + [delivery_api.ListTasksRequest], + delivery_api.ListTasksResponse]: + r"""Return a callable for the list tasks method over gRPC. + + Gets all ``Task``\ s that meet the specified filtering criteria. + + Returns: + Callable[[~.ListTasksRequest], + ~.ListTasksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tasks' not in self._stubs: + self._stubs['list_tasks'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/ListTasks', + request_serializer=delivery_api.ListTasksRequest.serialize, + response_deserializer=delivery_api.ListTasksResponse.deserialize, + ) + return self._stubs['list_tasks'] + + @property + def get_task_tracking_info(self) -> Callable[ + [delivery_api.GetTaskTrackingInfoRequest], + task_tracking_info.TaskTrackingInfo]: + r"""Return a callable for the get task tracking info method over gRPC. + + Returns the specified ``TaskTrackingInfo`` instance. + + Returns: + Callable[[~.GetTaskTrackingInfoRequest], + ~.TaskTrackingInfo]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_task_tracking_info' not in self._stubs: + self._stubs['get_task_tracking_info'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/GetTaskTrackingInfo', + request_serializer=delivery_api.GetTaskTrackingInfoRequest.serialize, + response_deserializer=task_tracking_info.TaskTrackingInfo.deserialize, + ) + return self._stubs['get_task_tracking_info'] + + @property + def list_delivery_vehicles(self) -> Callable[ + [delivery_api.ListDeliveryVehiclesRequest], + delivery_api.ListDeliveryVehiclesResponse]: + r"""Return a callable for the list delivery vehicles method over gRPC. + + Gets all ``DeliveryVehicle``\ s that meet the specified + filtering criteria. + + Returns: + Callable[[~.ListDeliveryVehiclesRequest], + ~.ListDeliveryVehiclesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_delivery_vehicles' not in self._stubs: + self._stubs['list_delivery_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/ListDeliveryVehicles', + request_serializer=delivery_api.ListDeliveryVehiclesRequest.serialize, + response_deserializer=delivery_api.ListDeliveryVehiclesResponse.deserialize, + ) + return self._stubs['list_delivery_vehicles'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DeliveryServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e39deda49df2 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py @@ -0,0 +1,672 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.fleetengine_delivery_v1.types import delivery_api +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import task_tracking_info +from google.maps.fleetengine_delivery_v1.types import tasks +from .base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DeliveryServiceGrpcTransport + + +class DeliveryServiceGrpcAsyncIOTransport(DeliveryServiceTransport): + """gRPC AsyncIO backend transport for DeliveryService. + + The Last Mile Delivery service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'fleetengine.googleapis.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 = 'fleetengine.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: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_delivery_vehicle(self) -> Callable[ + [delivery_api.CreateDeliveryVehicleRequest], + Awaitable[delivery_vehicles.DeliveryVehicle]]: + r"""Return a callable for the create delivery vehicle method over gRPC. + + Creates and returns a new ``DeliveryVehicle``. + + Returns: + Callable[[~.CreateDeliveryVehicleRequest], + Awaitable[~.DeliveryVehicle]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: + self._stubs['create_delivery_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/CreateDeliveryVehicle', + request_serializer=delivery_api.CreateDeliveryVehicleRequest.serialize, + response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, + ) + return self._stubs['create_delivery_vehicle'] + + @property + def get_delivery_vehicle(self) -> Callable[ + [delivery_api.GetDeliveryVehicleRequest], + Awaitable[delivery_vehicles.DeliveryVehicle]]: + r"""Return a callable for the get delivery vehicle method over gRPC. + + Returns the specified ``DeliveryVehicle`` instance. + + Returns: + Callable[[~.GetDeliveryVehicleRequest], + Awaitable[~.DeliveryVehicle]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: + self._stubs['get_delivery_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/GetDeliveryVehicle', + request_serializer=delivery_api.GetDeliveryVehicleRequest.serialize, + response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, + ) + return self._stubs['get_delivery_vehicle'] + + @property + def update_delivery_vehicle(self) -> Callable[ + [delivery_api.UpdateDeliveryVehicleRequest], + Awaitable[delivery_vehicles.DeliveryVehicle]]: + r"""Return a callable for the update delivery vehicle method over gRPC. + + Writes updated ``DeliveryVehicle`` data to Fleet Engine, and + assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update + the name of the ``DeliveryVehicle``. You *can* update + ``remaining_vehicle_journey_segments``, but it must contain all + of the ``VehicleJourneySegment``\ s to be persisted on the + ``DeliveryVehicle``. The ``task_id``\ s are retrieved from + ``remaining_vehicle_journey_segments``, and their corresponding + ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have + not yet been assigned. + + Returns: + Callable[[~.UpdateDeliveryVehicleRequest], + Awaitable[~.DeliveryVehicle]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: + self._stubs['update_delivery_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/UpdateDeliveryVehicle', + request_serializer=delivery_api.UpdateDeliveryVehicleRequest.serialize, + response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, + ) + return self._stubs['update_delivery_vehicle'] + + @property + def batch_create_tasks(self) -> Callable[ + [delivery_api.BatchCreateTasksRequest], + Awaitable[delivery_api.BatchCreateTasksResponse]]: + r"""Return a callable for the batch create tasks method over gRPC. + + Creates and returns a batch of new ``Task`` objects. + + Returns: + Callable[[~.BatchCreateTasksRequest], + Awaitable[~.BatchCreateTasksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tasks' not in self._stubs: + self._stubs['batch_create_tasks'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/BatchCreateTasks', + request_serializer=delivery_api.BatchCreateTasksRequest.serialize, + response_deserializer=delivery_api.BatchCreateTasksResponse.deserialize, + ) + return self._stubs['batch_create_tasks'] + + @property + def create_task(self) -> Callable[ + [delivery_api.CreateTaskRequest], + Awaitable[tasks.Task]]: + r"""Return a callable for the create task method over gRPC. + + Creates and returns a new ``Task`` object. + + Returns: + Callable[[~.CreateTaskRequest], + Awaitable[~.Task]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_task' not in self._stubs: + self._stubs['create_task'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/CreateTask', + request_serializer=delivery_api.CreateTaskRequest.serialize, + response_deserializer=tasks.Task.deserialize, + ) + return self._stubs['create_task'] + + @property + def get_task(self) -> Callable[ + [delivery_api.GetTaskRequest], + Awaitable[tasks.Task]]: + r"""Return a callable for the get task method over gRPC. + + Gets information about a ``Task``. + + Returns: + Callable[[~.GetTaskRequest], + Awaitable[~.Task]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_task' not in self._stubs: + self._stubs['get_task'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/GetTask', + request_serializer=delivery_api.GetTaskRequest.serialize, + response_deserializer=tasks.Task.deserialize, + ) + return self._stubs['get_task'] + + @property + def update_task(self) -> Callable[ + [delivery_api.UpdateTaskRequest], + Awaitable[tasks.Task]]: + r"""Return a callable for the update task method over gRPC. + + Updates ``Task`` data. + + Returns: + Callable[[~.UpdateTaskRequest], + Awaitable[~.Task]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_task' not in self._stubs: + self._stubs['update_task'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/UpdateTask', + request_serializer=delivery_api.UpdateTaskRequest.serialize, + response_deserializer=tasks.Task.deserialize, + ) + return self._stubs['update_task'] + + @property + def list_tasks(self) -> Callable[ + [delivery_api.ListTasksRequest], + Awaitable[delivery_api.ListTasksResponse]]: + r"""Return a callable for the list tasks method over gRPC. + + Gets all ``Task``\ s that meet the specified filtering criteria. + + Returns: + Callable[[~.ListTasksRequest], + Awaitable[~.ListTasksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tasks' not in self._stubs: + self._stubs['list_tasks'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/ListTasks', + request_serializer=delivery_api.ListTasksRequest.serialize, + response_deserializer=delivery_api.ListTasksResponse.deserialize, + ) + return self._stubs['list_tasks'] + + @property + def get_task_tracking_info(self) -> Callable[ + [delivery_api.GetTaskTrackingInfoRequest], + Awaitable[task_tracking_info.TaskTrackingInfo]]: + r"""Return a callable for the get task tracking info method over gRPC. + + Returns the specified ``TaskTrackingInfo`` instance. + + Returns: + Callable[[~.GetTaskTrackingInfoRequest], + Awaitable[~.TaskTrackingInfo]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_task_tracking_info' not in self._stubs: + self._stubs['get_task_tracking_info'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/GetTaskTrackingInfo', + request_serializer=delivery_api.GetTaskTrackingInfoRequest.serialize, + response_deserializer=task_tracking_info.TaskTrackingInfo.deserialize, + ) + return self._stubs['get_task_tracking_info'] + + @property + def list_delivery_vehicles(self) -> Callable[ + [delivery_api.ListDeliveryVehiclesRequest], + Awaitable[delivery_api.ListDeliveryVehiclesResponse]]: + r"""Return a callable for the list delivery vehicles method over gRPC. + + Gets all ``DeliveryVehicle``\ s that meet the specified + filtering criteria. + + Returns: + Callable[[~.ListDeliveryVehiclesRequest], + Awaitable[~.ListDeliveryVehiclesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_delivery_vehicles' not in self._stubs: + self._stubs['list_delivery_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.delivery.v1.DeliveryService/ListDeliveryVehicles', + request_serializer=delivery_api.ListDeliveryVehiclesRequest.serialize, + response_deserializer=delivery_api.ListDeliveryVehiclesResponse.deserialize, + ) + return self._stubs['list_delivery_vehicles'] + + 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_delivery_vehicle: self._wrap_method( + self.create_delivery_vehicle, + 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_delivery_vehicle: self._wrap_method( + self.get_delivery_vehicle, + 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.update_delivery_vehicle: self._wrap_method( + self.update_delivery_vehicle, + 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.batch_create_tasks: self._wrap_method( + self.batch_create_tasks, + 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.create_task: self._wrap_method( + self.create_task, + 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_task: self._wrap_method( + self.get_task, + 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.update_task: self._wrap_method( + self.update_task, + 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_tasks: self._wrap_method( + self.list_tasks, + 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_task_tracking_info: self._wrap_method( + self.get_task_tracking_info, + 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_delivery_vehicles: self._wrap_method( + self.list_delivery_vehicles, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'DeliveryServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py new file mode 100644 index 000000000000..941973102e68 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py @@ -0,0 +1,1318 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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.fleetengine_delivery_v1.types import delivery_api +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import task_tracking_info +from google.maps.fleetengine_delivery_v1.types import tasks + + +from .rest_base import _BaseDeliveryServiceRestTransport +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 + + +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 DeliveryServiceRestInterceptor: + """Interceptor for DeliveryService. + + 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 DeliveryServiceRestTransport. + + .. code-block:: python + class MyCustomDeliveryServiceInterceptor(DeliveryServiceRestInterceptor): + def pre_batch_create_tasks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_tasks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_delivery_vehicle(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_delivery_vehicle(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_task(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_task(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_delivery_vehicle(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_delivery_vehicle(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_task(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_task(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_task_tracking_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_task_tracking_info(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_delivery_vehicles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_delivery_vehicles(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tasks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tasks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_delivery_vehicle(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_delivery_vehicle(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_task(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_task(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DeliveryServiceRestTransport(interceptor=MyCustomDeliveryServiceInterceptor()) + client = DeliveryServiceClient(transport=transport) + + + """ + def pre_batch_create_tasks(self, request: delivery_api.BatchCreateTasksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.BatchCreateTasksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_create_tasks + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_batch_create_tasks(self, response: delivery_api.BatchCreateTasksResponse) -> delivery_api.BatchCreateTasksResponse: + """Post-rpc interceptor for batch_create_tasks + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + def pre_create_delivery_vehicle(self, request: delivery_api.CreateDeliveryVehicleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.CreateDeliveryVehicleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_delivery_vehicle + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_create_delivery_vehicle(self, response: delivery_vehicles.DeliveryVehicle) -> delivery_vehicles.DeliveryVehicle: + """Post-rpc interceptor for create_delivery_vehicle + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + def pre_create_task(self, request: delivery_api.CreateTaskRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.CreateTaskRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_task + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_create_task(self, response: tasks.Task) -> tasks.Task: + """Post-rpc interceptor for create_task + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + def pre_get_delivery_vehicle(self, request: delivery_api.GetDeliveryVehicleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.GetDeliveryVehicleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_delivery_vehicle + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_get_delivery_vehicle(self, response: delivery_vehicles.DeliveryVehicle) -> delivery_vehicles.DeliveryVehicle: + """Post-rpc interceptor for get_delivery_vehicle + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + def pre_get_task(self, request: delivery_api.GetTaskRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.GetTaskRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_task + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_get_task(self, response: tasks.Task) -> tasks.Task: + """Post-rpc interceptor for get_task + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + def pre_get_task_tracking_info(self, request: delivery_api.GetTaskTrackingInfoRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.GetTaskTrackingInfoRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_task_tracking_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_get_task_tracking_info(self, response: task_tracking_info.TaskTrackingInfo) -> task_tracking_info.TaskTrackingInfo: + """Post-rpc interceptor for get_task_tracking_info + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + def pre_list_delivery_vehicles(self, request: delivery_api.ListDeliveryVehiclesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.ListDeliveryVehiclesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_delivery_vehicles + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_list_delivery_vehicles(self, response: delivery_api.ListDeliveryVehiclesResponse) -> delivery_api.ListDeliveryVehiclesResponse: + """Post-rpc interceptor for list_delivery_vehicles + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + def pre_list_tasks(self, request: delivery_api.ListTasksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.ListTasksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tasks + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_list_tasks(self, response: delivery_api.ListTasksResponse) -> delivery_api.ListTasksResponse: + """Post-rpc interceptor for list_tasks + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + def pre_update_delivery_vehicle(self, request: delivery_api.UpdateDeliveryVehicleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.UpdateDeliveryVehicleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_delivery_vehicle + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_update_delivery_vehicle(self, response: delivery_vehicles.DeliveryVehicle) -> delivery_vehicles.DeliveryVehicle: + """Post-rpc interceptor for update_delivery_vehicle + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + def pre_update_task(self, request: delivery_api.UpdateTaskRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.UpdateTaskRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_task + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeliveryService server. + """ + return request, metadata + + def post_update_task(self, response: tasks.Task) -> tasks.Task: + """Post-rpc interceptor for update_task + + Override in a subclass to manipulate the response + after it is returned by the DeliveryService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DeliveryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DeliveryServiceRestInterceptor + + +class DeliveryServiceRestTransport(_BaseDeliveryServiceRestTransport): + """REST backend synchronous transport for DeliveryService. + + The Last Mile Delivery service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'fleetengine.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[DeliveryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 DeliveryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchCreateTasks(_BaseDeliveryServiceRestTransport._BaseBatchCreateTasks, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.BatchCreateTasks") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: delivery_api.BatchCreateTasksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> delivery_api.BatchCreateTasksResponse: + r"""Call the batch create tasks method over HTTP. + + Args: + request (~.delivery_api.BatchCreateTasksRequest): + The request object. The ``BatchCreateTask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.delivery_api.BatchCreateTasksResponse: + The ``BatchCreateTask`` response message. + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_http_options() + request, metadata = self._interceptor.pre_batch_create_tasks(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_transcoded_request(http_options, request) + + body = _BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._BatchCreateTasks._get_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 = delivery_api.BatchCreateTasksResponse() + pb_resp = delivery_api.BatchCreateTasksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_create_tasks(resp) + return resp + + class _CreateDeliveryVehicle(_BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.CreateDeliveryVehicle") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: delivery_api.CreateDeliveryVehicleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> delivery_vehicles.DeliveryVehicle: + r"""Call the create delivery vehicle method over HTTP. + + Args: + request (~.delivery_api.CreateDeliveryVehicleRequest): + The request object. The ``CreateDeliveryVehicle`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.delivery_vehicles.DeliveryVehicle: + The ``DeliveryVehicle`` message. A delivery vehicle + transports shipments from a depot to a delivery + location, and from a pickup location to the depot. In + some cases, delivery vehicles also transport shipments + directly from the pickup location to the delivery + location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + ``DeliveryVehicle.current_route_segment`` field in the + gRPC API and the ``DeliveryVehicle.currentRouteSegment`` + field in the REST API refer to the same field. + + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_http_options() + request, metadata = self._interceptor.pre_create_delivery_vehicle(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_transcoded_request(http_options, request) + + body = _BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._CreateDeliveryVehicle._get_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 = delivery_vehicles.DeliveryVehicle() + pb_resp = delivery_vehicles.DeliveryVehicle.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_delivery_vehicle(resp) + return resp + + class _CreateTask(_BaseDeliveryServiceRestTransport._BaseCreateTask, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.CreateTask") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: delivery_api.CreateTaskRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tasks.Task: + r"""Call the create task method over HTTP. + + Args: + request (~.delivery_api.CreateTaskRequest): + The request object. The ``CreateTask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tasks.Task: + A Task in the Delivery API represents a single action to + track. In general, there is a distinction between + shipment-related Tasks and break Tasks. A shipment can + have multiple Tasks associated with it. For example, + there could be one Task for the pickup, and one for the + drop-off or transfer. Also, different Tasks for a given + shipment can be handled by different vehicles. For + example, one vehicle could handle the pickup, driving + the shipment to the hub, while another vehicle drives + the same shipment from the hub to the drop-off location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + ``Task.journey_sharing_info`` field in the gRPC API and + the ``Task.journeySharingInfo`` field in the REST API + refer to the same field. + + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseCreateTask._get_http_options() + request, metadata = self._interceptor.pre_create_task(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseCreateTask._get_transcoded_request(http_options, request) + + body = _BaseDeliveryServiceRestTransport._BaseCreateTask._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseCreateTask._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._CreateTask._get_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 = tasks.Task() + pb_resp = tasks.Task.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_task(resp) + return resp + + class _GetDeliveryVehicle(_BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.GetDeliveryVehicle") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: delivery_api.GetDeliveryVehicleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> delivery_vehicles.DeliveryVehicle: + r"""Call the get delivery vehicle method over HTTP. + + Args: + request (~.delivery_api.GetDeliveryVehicleRequest): + The request object. The ``GetDeliveryVehicle`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.delivery_vehicles.DeliveryVehicle: + The ``DeliveryVehicle`` message. A delivery vehicle + transports shipments from a depot to a delivery + location, and from a pickup location to the depot. In + some cases, delivery vehicles also transport shipments + directly from the pickup location to the delivery + location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + ``DeliveryVehicle.current_route_segment`` field in the + gRPC API and the ``DeliveryVehicle.currentRouteSegment`` + field in the REST API refer to the same field. + + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle._get_http_options() + request, metadata = self._interceptor.pre_get_delivery_vehicle(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._GetDeliveryVehicle._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = delivery_vehicles.DeliveryVehicle() + pb_resp = delivery_vehicles.DeliveryVehicle.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_delivery_vehicle(resp) + return resp + + class _GetTask(_BaseDeliveryServiceRestTransport._BaseGetTask, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.GetTask") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: delivery_api.GetTaskRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tasks.Task: + r"""Call the get task method over HTTP. + + Args: + request (~.delivery_api.GetTaskRequest): + The request object. The ``GetTask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tasks.Task: + A Task in the Delivery API represents a single action to + track. In general, there is a distinction between + shipment-related Tasks and break Tasks. A shipment can + have multiple Tasks associated with it. For example, + there could be one Task for the pickup, and one for the + drop-off or transfer. Also, different Tasks for a given + shipment can be handled by different vehicles. For + example, one vehicle could handle the pickup, driving + the shipment to the hub, while another vehicle drives + the same shipment from the hub to the drop-off location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + ``Task.journey_sharing_info`` field in the gRPC API and + the ``Task.journeySharingInfo`` field in the REST API + refer to the same field. + + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseGetTask._get_http_options() + request, metadata = self._interceptor.pre_get_task(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseGetTask._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseGetTask._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._GetTask._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tasks.Task() + pb_resp = tasks.Task.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_task(resp) + return resp + + class _GetTaskTrackingInfo(_BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.GetTaskTrackingInfo") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: delivery_api.GetTaskTrackingInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> task_tracking_info.TaskTrackingInfo: + r"""Call the get task tracking info method over HTTP. + + Args: + request (~.delivery_api.GetTaskTrackingInfoRequest): + The request object. The ``GetTaskTrackingInfoRequest`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.task_tracking_info.TaskTrackingInfo: + The ``TaskTrackingInfo`` message. The message contains + task tracking information which will be used for + display. If a tracking ID is associated with multiple + Tasks, Fleet Engine uses a heuristic to decide which + Task's TaskTrackingInfo to select. + + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo._get_http_options() + request, metadata = self._interceptor.pre_get_task_tracking_info(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._GetTaskTrackingInfo._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = task_tracking_info.TaskTrackingInfo() + pb_resp = task_tracking_info.TaskTrackingInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_task_tracking_info(resp) + return resp + + class _ListDeliveryVehicles(_BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.ListDeliveryVehicles") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: delivery_api.ListDeliveryVehiclesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> delivery_api.ListDeliveryVehiclesResponse: + r"""Call the list delivery vehicles method over HTTP. + + Args: + request (~.delivery_api.ListDeliveryVehiclesRequest): + The request object. The ``ListDeliveryVehicles`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.delivery_api.ListDeliveryVehiclesResponse: + The ``ListDeliveryVehicles`` response message. + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles._get_http_options() + request, metadata = self._interceptor.pre_list_delivery_vehicles(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._ListDeliveryVehicles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = delivery_api.ListDeliveryVehiclesResponse() + pb_resp = delivery_api.ListDeliveryVehiclesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_delivery_vehicles(resp) + return resp + + class _ListTasks(_BaseDeliveryServiceRestTransport._BaseListTasks, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.ListTasks") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: delivery_api.ListTasksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> delivery_api.ListTasksResponse: + r"""Call the list tasks method over HTTP. + + Args: + request (~.delivery_api.ListTasksRequest): + The request object. The ``ListTasks`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.delivery_api.ListTasksResponse: + The ``ListTasks`` response that contains the set of + Tasks that meet the filter criteria in the + ``ListTasksRequest``. + + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseListTasks._get_http_options() + request, metadata = self._interceptor.pre_list_tasks(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseListTasks._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseListTasks._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._ListTasks._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = delivery_api.ListTasksResponse() + pb_resp = delivery_api.ListTasksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tasks(resp) + return resp + + class _UpdateDeliveryVehicle(_BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.UpdateDeliveryVehicle") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: delivery_api.UpdateDeliveryVehicleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> delivery_vehicles.DeliveryVehicle: + r"""Call the update delivery vehicle method over HTTP. + + Args: + request (~.delivery_api.UpdateDeliveryVehicleRequest): + The request object. The ``UpdateDeliveryVehicle`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.delivery_vehicles.DeliveryVehicle: + The ``DeliveryVehicle`` message. A delivery vehicle + transports shipments from a depot to a delivery + location, and from a pickup location to the depot. In + some cases, delivery vehicles also transport shipments + directly from the pickup location to the delivery + location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + ``DeliveryVehicle.current_route_segment`` field in the + gRPC API and the ``DeliveryVehicle.currentRouteSegment`` + field in the REST API refer to the same field. + + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_http_options() + request, metadata = self._interceptor.pre_update_delivery_vehicle(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_transcoded_request(http_options, request) + + body = _BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._UpdateDeliveryVehicle._get_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 = delivery_vehicles.DeliveryVehicle() + pb_resp = delivery_vehicles.DeliveryVehicle.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_delivery_vehicle(resp) + return resp + + class _UpdateTask(_BaseDeliveryServiceRestTransport._BaseUpdateTask, DeliveryServiceRestStub): + def __hash__(self): + return hash("DeliveryServiceRestTransport.UpdateTask") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: delivery_api.UpdateTaskRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tasks.Task: + r"""Call the update task method over HTTP. + + Args: + request (~.delivery_api.UpdateTaskRequest): + The request object. The ``UpdateTask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tasks.Task: + A Task in the Delivery API represents a single action to + track. In general, there is a distinction between + shipment-related Tasks and break Tasks. A shipment can + have multiple Tasks associated with it. For example, + there could be one Task for the pickup, and one for the + drop-off or transfer. Also, different Tasks for a given + shipment can be handled by different vehicles. For + example, one vehicle could handle the pickup, driving + the shipment to the hub, while another vehicle drives + the same shipment from the hub to the drop-off location. + + Note: gRPC and REST APIs use different field naming + conventions. For example, the + ``Task.journey_sharing_info`` field in the gRPC API and + the ``Task.journeySharingInfo`` field in the REST API + refer to the same field. + + """ + + http_options = _BaseDeliveryServiceRestTransport._BaseUpdateTask._get_http_options() + request, metadata = self._interceptor.pre_update_task(request, metadata) + transcoded_request = _BaseDeliveryServiceRestTransport._BaseUpdateTask._get_transcoded_request(http_options, request) + + body = _BaseDeliveryServiceRestTransport._BaseUpdateTask._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDeliveryServiceRestTransport._BaseUpdateTask._get_query_params_json(transcoded_request) + + # Send the request + response = DeliveryServiceRestTransport._UpdateTask._get_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 = tasks.Task() + pb_resp = tasks.Task.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_task(resp) + return resp + + @property + def batch_create_tasks(self) -> Callable[ + [delivery_api.BatchCreateTasksRequest], + delivery_api.BatchCreateTasksResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateTasks(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_delivery_vehicle(self) -> Callable[ + [delivery_api.CreateDeliveryVehicleRequest], + delivery_vehicles.DeliveryVehicle]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDeliveryVehicle(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_task(self) -> Callable[ + [delivery_api.CreateTaskRequest], + tasks.Task]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateTask(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_delivery_vehicle(self) -> Callable[ + [delivery_api.GetDeliveryVehicleRequest], + delivery_vehicles.DeliveryVehicle]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDeliveryVehicle(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_task(self) -> Callable[ + [delivery_api.GetTaskRequest], + tasks.Task]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTask(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_task_tracking_info(self) -> Callable[ + [delivery_api.GetTaskTrackingInfoRequest], + task_tracking_info.TaskTrackingInfo]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTaskTrackingInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_delivery_vehicles(self) -> Callable[ + [delivery_api.ListDeliveryVehiclesRequest], + delivery_api.ListDeliveryVehiclesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDeliveryVehicles(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tasks(self) -> Callable[ + [delivery_api.ListTasksRequest], + delivery_api.ListTasksResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTasks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_delivery_vehicle(self) -> Callable[ + [delivery_api.UpdateDeliveryVehicleRequest], + delivery_vehicles.DeliveryVehicle]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDeliveryVehicle(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_task(self) -> Callable[ + [delivery_api.UpdateTaskRequest], + tasks.Task]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateTask(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DeliveryServiceRestTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest_base.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest_base.py new file mode 100644 index 000000000000..bd01a83a74f0 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest_base.py @@ -0,0 +1,514 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 DeliveryServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.maps.fleetengine_delivery_v1.types import delivery_api +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import task_tracking_info +from google.maps.fleetengine_delivery_v1.types import tasks + + +class _BaseDeliveryServiceRestTransport(DeliveryServiceTransport): + """Base REST backend transport for DeliveryService. + + 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 = 'fleetengine.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: 'fleetengine.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 _BaseBatchCreateTasks: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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=providers/*}/tasks:batchCreate', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.BatchCreateTasksRequest.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(_BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateDeliveryVehicle: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "deliveryVehicleId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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=providers/*}/deliveryVehicles', + 'body': 'delivery_vehicle', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.CreateDeliveryVehicleRequest.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(_BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateTask: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "taskId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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=providers/*}/tasks', + 'body': 'task', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.CreateTaskRequest.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(_BaseDeliveryServiceRestTransport._BaseCreateTask._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDeliveryVehicle: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_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=providers/*/deliveryVehicles/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.GetDeliveryVehicleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTask: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_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=providers/*/tasks/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.GetTaskRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseDeliveryServiceRestTransport._BaseGetTask._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTaskTrackingInfo: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_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=providers/*/taskTrackingInfo/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.GetTaskTrackingInfoRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListDeliveryVehicles: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_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=providers/*}/deliveryVehicles', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.ListDeliveryVehiclesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTasks: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_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=providers/*}/tasks', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.ListTasksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseDeliveryServiceRestTransport._BaseListTasks._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateDeliveryVehicle: + 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': '/v1/{delivery_vehicle.name=providers/*/deliveryVehicles/*}', + 'body': 'delivery_vehicle', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.UpdateDeliveryVehicleRequest.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(_BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateTask: + 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': '/v1/{task.name=providers/*/tasks/*}', + 'body': 'task', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = delivery_api.UpdateTaskRequest.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(_BaseDeliveryServiceRestTransport._BaseUpdateTask._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseDeliveryServiceRestTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py new file mode 100644 index 000000000000..e2051b3b85ad --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__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 .common import ( + DeliveryVehicleAttribute, + DeliveryVehicleLocation, + TaskAttribute, + TimeWindow, + DeliveryVehicleLocationSensor, + DeliveryVehicleNavigationStatus, +) +from .delivery_api import ( + BatchCreateTasksRequest, + BatchCreateTasksResponse, + CreateDeliveryVehicleRequest, + CreateTaskRequest, + GetDeliveryVehicleRequest, + GetTaskRequest, + GetTaskTrackingInfoRequest, + ListDeliveryVehiclesRequest, + ListDeliveryVehiclesResponse, + ListTasksRequest, + ListTasksResponse, + UpdateDeliveryVehicleRequest, + UpdateTaskRequest, +) +from .delivery_vehicles import ( + DeliveryVehicle, + LocationInfo, + VehicleJourneySegment, + VehicleStop, +) +from .header import ( + DeliveryRequestHeader, +) +from .task_tracking_info import ( + TaskTrackingInfo, +) +from .tasks import ( + Task, + TaskTrackingViewConfig, +) + +__all__ = ( + 'DeliveryVehicleAttribute', + 'DeliveryVehicleLocation', + 'TaskAttribute', + 'TimeWindow', + 'DeliveryVehicleLocationSensor', + 'DeliveryVehicleNavigationStatus', + 'BatchCreateTasksRequest', + 'BatchCreateTasksResponse', + 'CreateDeliveryVehicleRequest', + 'CreateTaskRequest', + 'GetDeliveryVehicleRequest', + 'GetTaskRequest', + 'GetTaskTrackingInfoRequest', + 'ListDeliveryVehiclesRequest', + 'ListDeliveryVehiclesResponse', + 'ListTasksRequest', + 'ListTasksResponse', + 'UpdateDeliveryVehicleRequest', + 'UpdateTaskRequest', + 'DeliveryVehicle', + 'LocationInfo', + 'VehicleJourneySegment', + 'VehicleStop', + 'DeliveryRequestHeader', + 'TaskTrackingInfo', + 'Task', + 'TaskTrackingViewConfig', +) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py new file mode 100644 index 000000000000..f0fa11ac4ff5 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.delivery.v1', + manifest={ + 'DeliveryVehicleLocationSensor', + 'DeliveryVehicleNavigationStatus', + 'DeliveryVehicleAttribute', + 'DeliveryVehicleLocation', + 'TimeWindow', + 'TaskAttribute', + }, +) + + +class DeliveryVehicleLocationSensor(proto.Enum): + r"""The sensor or methodology used to determine the location. + + Values: + UNKNOWN_SENSOR (0): + The sensor is unspecified or unknown. + GPS (1): + GPS or Assisted GPS. + NETWORK (2): + Assisted GPS, cell tower ID, or WiFi access + point. + PASSIVE (3): + Cell tower ID or WiFi access point. + ROAD_SNAPPED_LOCATION_PROVIDER (4): + A location determined by the mobile device to + be the most likely road position. + CUSTOMER_SUPPLIED_LOCATION (5): + A customer-supplied location from an independent source. + Typically, this value is used for a location provided from + sources other than the mobile device running Driver SDK. If + the original source is described by one of the other enum + values, use that value. Locations marked + CUSTOMER_SUPPLIED_LOCATION are typically provided via a + DeliveryVehicle's + ``last_location.supplemental_location_sensor``. + FLEET_ENGINE_LOCATION (6): + A location calculated by Fleet Engine based + on the signals available to it. Output only. + This value will be rejected if it is received in + a request. + FUSED_LOCATION_PROVIDER (100): + Android's Fused Location Provider. + CORE_LOCATION (200): + The location provider on Apple operating + systems. + """ + UNKNOWN_SENSOR = 0 + GPS = 1 + NETWORK = 2 + PASSIVE = 3 + ROAD_SNAPPED_LOCATION_PROVIDER = 4 + CUSTOMER_SUPPLIED_LOCATION = 5 + FLEET_ENGINE_LOCATION = 6 + FUSED_LOCATION_PROVIDER = 100 + CORE_LOCATION = 200 + + +class DeliveryVehicleNavigationStatus(proto.Enum): + r"""The vehicle's navigation status. + + Values: + UNKNOWN_NAVIGATION_STATUS (0): + Unspecified navigation status. + NO_GUIDANCE (1): + The Driver app's navigation is in ``FREE_NAV`` mode. + ENROUTE_TO_DESTINATION (2): + Turn-by-turn navigation is available and the Driver app + navigation has entered ``GUIDED_NAV`` mode. + OFF_ROUTE (3): + The vehicle has gone off the suggested route. + ARRIVED_AT_DESTINATION (4): + The vehicle is within approximately 50m of + the destination. + """ + UNKNOWN_NAVIGATION_STATUS = 0 + NO_GUIDANCE = 1 + ENROUTE_TO_DESTINATION = 2 + OFF_ROUTE = 3 + ARRIVED_AT_DESTINATION = 4 + + +class DeliveryVehicleAttribute(proto.Message): + r"""Describes a vehicle attribute as a key-value pair. The + "key:value" string length cannot exceed 256 characters. + + 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: + key (str): + The attribute's key. + value (str): + The attribute's value. + string_value (str): + String typed attribute value. + + Note: This is identical to the ``value`` field which will + eventually be deprecated. For create or update methods, + either field can be used, but it's strongly recommended to + use ``string_value``. If both ``string_value`` and ``value`` + are set, they must be identical or an error will be thrown. + Both fields are populated in responses. + + This field is a member of `oneof`_ ``delivery_vehicle_attribute_value``. + bool_value (bool): + Boolean typed attribute value. + + This field is a member of `oneof`_ ``delivery_vehicle_attribute_value``. + number_value (float): + Double typed attribute value. + + This field is a member of `oneof`_ ``delivery_vehicle_attribute_value``. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + string_value: str = proto.Field( + proto.STRING, + number=3, + oneof='delivery_vehicle_attribute_value', + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=4, + oneof='delivery_vehicle_attribute_value', + ) + number_value: float = proto.Field( + proto.DOUBLE, + number=5, + oneof='delivery_vehicle_attribute_value', + ) + + +class DeliveryVehicleLocation(proto.Message): + r"""The location, speed, and heading of a vehicle at a point in + time. + + Attributes: + location (google.type.latlng_pb2.LatLng): + The location of the vehicle. When it is sent to Fleet + Engine, the vehicle's location is a GPS location. When you + receive it in a response, the vehicle's location can be + either a GPS location, a supplemental location, or some + other estimated location. The source is specified in + ``location_sensor``. + horizontal_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Deprecated: Use ``latlng_accuracy`` instead. + latlng_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``location`` in meters as a radius. + heading (google.protobuf.wrappers_pb2.Int32Value): + Direction the vehicle is moving in degrees. 0 represents + North. The valid range is [0,360). + bearing_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Deprecated: Use ``heading_accuracy`` instead. + heading_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``heading`` in degrees. + altitude (google.protobuf.wrappers_pb2.DoubleValue): + Altitude in meters above WGS84. + vertical_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Deprecated: Use ``altitude_accuracy`` instead. + altitude_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``altitude`` in meters. + speed_kmph (google.protobuf.wrappers_pb2.Int32Value): + Speed of the vehicle in kilometers per hour. Deprecated: Use + ``speed`` instead. + speed (google.protobuf.wrappers_pb2.DoubleValue): + Speed of the vehicle in meters/second + speed_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``speed`` in meters/second. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when ``location`` was reported by the sensor + according to the sensor's clock. + server_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the server + received the location information. + location_sensor (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocationSensor): + Provider of location data (for example, ``GPS``). + is_road_snapped (google.protobuf.wrappers_pb2.BoolValue): + Whether ``location`` is snapped to a road. + is_gps_sensor_enabled (google.protobuf.wrappers_pb2.BoolValue): + Input only. Indicates whether the GPS sensor + is enabled on the mobile device. + time_since_update (google.protobuf.wrappers_pb2.Int32Value): + Input only. Time (in seconds) since this + location was first sent to the server. This will + be zero for the first update. If the time is + unknown (for example, when the app restarts), + this value resets to zero. + num_stale_updates (google.protobuf.wrappers_pb2.Int32Value): + Input only. Deprecated: Other signals are now + used to determine if a location is stale. + raw_location (google.type.latlng_pb2.LatLng): + Raw vehicle location (unprocessed by + road-snapper). + raw_location_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp associated with the raw location. + raw_location_sensor (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocationSensor): + Source of the raw location. Defaults to ``GPS``. + raw_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``raw_location`` as a radius, in meters. + supplemental_location (google.type.latlng_pb2.LatLng): + Supplemental location provided by the + integrating app. + supplemental_location_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp associated with the supplemental + location. + supplemental_location_sensor (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocationSensor): + Source of the supplemental location. Defaults to + ``CUSTOMER_SUPPLIED_LOCATION``. + supplemental_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``supplemental_location`` as a radius, in + meters. + road_snapped (bool): + Deprecated: Use ``is_road_snapped`` instead. + """ + + location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + horizontal_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=8, + message=wrappers_pb2.DoubleValue, + ) + latlng_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=22, + message=wrappers_pb2.DoubleValue, + ) + heading: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + bearing_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=10, + message=wrappers_pb2.DoubleValue, + ) + heading_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=23, + message=wrappers_pb2.DoubleValue, + ) + altitude: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.DoubleValue, + ) + vertical_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=9, + message=wrappers_pb2.DoubleValue, + ) + altitude_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=24, + message=wrappers_pb2.DoubleValue, + ) + speed_kmph: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int32Value, + ) + speed: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.DoubleValue, + ) + speed_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.DoubleValue, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + server_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=13, + message=timestamp_pb2.Timestamp, + ) + location_sensor: 'DeliveryVehicleLocationSensor' = proto.Field( + proto.ENUM, + number=11, + enum='DeliveryVehicleLocationSensor', + ) + is_road_snapped: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=27, + message=wrappers_pb2.BoolValue, + ) + is_gps_sensor_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=12, + message=wrappers_pb2.BoolValue, + ) + time_since_update: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=14, + message=wrappers_pb2.Int32Value, + ) + num_stale_updates: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=15, + message=wrappers_pb2.Int32Value, + ) + raw_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=16, + message=latlng_pb2.LatLng, + ) + raw_location_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=17, + message=timestamp_pb2.Timestamp, + ) + raw_location_sensor: 'DeliveryVehicleLocationSensor' = proto.Field( + proto.ENUM, + number=28, + enum='DeliveryVehicleLocationSensor', + ) + raw_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=25, + message=wrappers_pb2.DoubleValue, + ) + supplemental_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=18, + message=latlng_pb2.LatLng, + ) + supplemental_location_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + supplemental_location_sensor: 'DeliveryVehicleLocationSensor' = proto.Field( + proto.ENUM, + number=20, + enum='DeliveryVehicleLocationSensor', + ) + supplemental_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=21, + message=wrappers_pb2.DoubleValue, + ) + road_snapped: bool = proto.Field( + proto.BOOL, + number=26, + ) + + +class TimeWindow(proto.Message): + r"""A time range. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The start time of the time window + (inclusive). + end_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The end time of the time window + (inclusive). + """ + + 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, + ) + + +class TaskAttribute(proto.Message): + r"""Describes a task attribute as a key-value pair. The + "key:value" string length cannot exceed 256 characters. + + 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: + key (str): + The attribute's key. Keys may not contain the + colon character (:). + string_value (str): + String typed attribute value. + + This field is a member of `oneof`_ ``task_attribute_value``. + bool_value (bool): + Boolean typed attribute value. + + This field is a member of `oneof`_ ``task_attribute_value``. + number_value (float): + Double typed attribute value. + + This field is a member of `oneof`_ ``task_attribute_value``. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + string_value: str = proto.Field( + proto.STRING, + number=2, + oneof='task_attribute_value', + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=3, + oneof='task_attribute_value', + ) + number_value: float = proto.Field( + proto.DOUBLE, + number=4, + oneof='task_attribute_value', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py new file mode 100644 index 000000000000..e32df11b607b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py @@ -0,0 +1,603 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.fleetengine_delivery_v1.types import delivery_vehicles as mfd_delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import header as mfd_header +from google.maps.fleetengine_delivery_v1.types import tasks as mfd_tasks +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.delivery.v1', + manifest={ + 'CreateDeliveryVehicleRequest', + 'GetDeliveryVehicleRequest', + 'ListDeliveryVehiclesRequest', + 'ListDeliveryVehiclesResponse', + 'UpdateDeliveryVehicleRequest', + 'BatchCreateTasksRequest', + 'BatchCreateTasksResponse', + 'CreateTaskRequest', + 'GetTaskRequest', + 'UpdateTaskRequest', + 'ListTasksRequest', + 'ListTasksResponse', + 'GetTaskTrackingInfoRequest', + }, +) + + +class CreateDeliveryVehicleRequest(proto.Message): + r"""The ``CreateDeliveryVehicle`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request + header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Google Cloud Project ID. For + example, ``sample-cloud-project``. + delivery_vehicle_id (str): + Required. The Delivery Vehicle ID must be unique and subject + to the following restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): + Required. The ``DeliveryVehicle`` entity to create. When + creating a new delivery vehicle, you may set the following + optional fields: + + - type + - last_location + - attributes + + Note: The DeliveryVehicle's ``name`` field is ignored. All + other DeliveryVehicle fields must not be set; otherwise, an + error is returned. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + delivery_vehicle_id: str = proto.Field( + proto.STRING, + number=4, + ) + delivery_vehicle: mfd_delivery_vehicles.DeliveryVehicle = proto.Field( + proto.MESSAGE, + number=5, + message=mfd_delivery_vehicles.DeliveryVehicle, + ) + + +class GetDeliveryVehicleRequest(proto.Message): + r"""The ``GetDeliveryVehicle`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request + header. + name (str): + Required. Must be in the format + ``providers/{provider}/deliveryVehicles/{delivery_vehicle}``. + The ``provider`` must be the Google Cloud Project ID. For + example, ``sample-cloud-project``. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDeliveryVehiclesRequest(proto.Message): + r"""The ``ListDeliveryVehicles`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request + header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The ``provider`` must be the Google Cloud Project ID. For + example, ``sample-cloud-project``. + page_size (int): + Optional. The maximum number of vehicles to + return. The service may return fewer than this + number. If you don't specify this number, then + the server determines the number of results to + return. + page_token (str): + Optional. A page token, received from a previous + ``ListDeliveryVehicles`` call. You must provide this in + order to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListDeliveryVehicles`` must match the call that provided + the page token. + filter (str): + Optional. A filter query to apply when listing delivery + vehicles. See http://aip.dev/160 for examples of the filter + syntax. If you don't specify a value, or if you specify an + empty string for the filter, then all delivery vehicles are + returned. + + Note that the only queries supported for + ``ListDeliveryVehicles`` are on vehicle attributes (for + example, ``attributes. = `` or + ``attributes. = AND attributes. = ``). + Also, all attributes are stored as strings, so the only + supported comparisons against attributes are string + comparisons. In order to compare against number or boolean + values, the values must be explicitly quoted to be treated + as strings (for example, ``attributes. = "10"`` or + ``attributes. = "true"``). + + The maximum number of restrictions allowed in a filter query + is 50. A restriction is a part of the query of the form + ``attribute. ``, for example + ``attributes.foo = bar`` is 1 restriction. + viewport (google.geo.type.types.Viewport): + Optional. A filter that limits the vehicles + returned to those whose last known location was + in the rectangular area defined by the viewport. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + filter: str = proto.Field( + proto.STRING, + number=6, + ) + viewport: ggt_viewport.Viewport = proto.Field( + proto.MESSAGE, + number=7, + message=ggt_viewport.Viewport, + ) + + +class ListDeliveryVehiclesResponse(proto.Message): + r"""The ``ListDeliveryVehicles`` response message. + + Attributes: + delivery_vehicles (MutableSequence[google.maps.fleetengine_delivery_v1.types.DeliveryVehicle]): + The set of delivery vehicles that meet the + requested filtering criteria. When no filter is + specified, the request returns all delivery + vehicles. A successful response can also be + empty. An empty response indicates that no + delivery vehicles were found meeting the + requested filter criteria. + next_page_token (str): + You can pass this token in the + ``ListDeliveryVehiclesRequest`` to continue to list results. + When all of the results are returned, this field won't be in + the response, or it will be an empty string. + total_size (int): + The total number of delivery vehicles that + match the request criteria, across all pages. + """ + + @property + def raw_page(self): + return self + + delivery_vehicles: MutableSequence[mfd_delivery_vehicles.DeliveryVehicle] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=mfd_delivery_vehicles.DeliveryVehicle, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT64, + number=3, + ) + + +class UpdateDeliveryVehicleRequest(proto.Message): + r"""The ``UpdateDeliveryVehicle`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request + header. + delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): + Required. The ``DeliveryVehicle`` entity update to apply. + Note: You cannot update the name of the ``DeliveryVehicle``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask that indicates which + ``DeliveryVehicle`` fields to update. Note that the + update_mask must contain at least one field. + + This is a comma-separated list of fully qualified names of + fields. Example: ``"remaining_vehicle_journey_segments"``. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + delivery_vehicle: mfd_delivery_vehicles.DeliveryVehicle = proto.Field( + proto.MESSAGE, + number=3, + message=mfd_delivery_vehicles.DeliveryVehicle, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class BatchCreateTasksRequest(proto.Message): + r"""The ``BatchCreateTask`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request header. Note: If + you set this field, then the header field in the + ``CreateTaskRequest`` messages must either be empty, or it + must match this field. + parent (str): + Required. The parent resource shared by all tasks. This + value must be in the format ``providers/{provider}``. The + ``provider`` must be the Google Cloud Project ID. For + example, ``sample-cloud-project``. The parent field in the + ``CreateTaskRequest`` messages must either be empty, or it + must match this field. + requests (MutableSequence[google.maps.fleetengine_delivery_v1.types.CreateTaskRequest]): + Required. The request message that specifies + the resources to create. Note: You can create a + maximum of 500 tasks in a batch. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + requests: MutableSequence['CreateTaskRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='CreateTaskRequest', + ) + + +class BatchCreateTasksResponse(proto.Message): + r"""The ``BatchCreateTask`` response message. + + Attributes: + tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.Task]): + The created Tasks. + """ + + tasks: MutableSequence[mfd_tasks.Task] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=mfd_tasks.Task, + ) + + +class CreateTaskRequest(proto.Message): + r"""The ``CreateTask`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request + header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The ``provider`` must be the Google Cloud Project ID. For + example, ``sample-cloud-project``. + task_id (str): + Required. The Task ID must be unique, but it should be not a + shipment tracking ID. To store a shipment tracking ID, use + the ``tracking_id`` field. Note that multiple tasks can have + the same ``tracking_id``. Task IDs are subject to the + following restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + task (google.maps.fleetengine_delivery_v1.types.Task): + Required. The Task entity to create. When creating a Task, + the following fields are required: + + - ``type`` + - ``state`` (must be set to ``OPEN``) + - ``tracking_id`` (must not be set for ``UNAVAILABLE`` or + ``SCHEDULED_STOP`` tasks, but required for all other task + types) + - ``planned_location`` (optional for ``UNAVAILABLE`` tasks) + - ``task_duration`` + + Note: The Task's ``name`` field is ignored. All other Task + fields must not be set; otherwise, an error is returned. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + task_id: str = proto.Field( + proto.STRING, + number=5, + ) + task: mfd_tasks.Task = proto.Field( + proto.MESSAGE, + number=4, + message=mfd_tasks.Task, + ) + + +class GetTaskRequest(proto.Message): + r"""The ``GetTask`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request + header. + name (str): + Required. Must be in the format + ``providers/{provider}/tasks/{task}``. The ``provider`` must + be the Google Cloud Project ID. For example, + ``sample-cloud-project``. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateTaskRequest(proto.Message): + r"""The ``UpdateTask`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request + header. + task (google.maps.fleetengine_delivery_v1.types.Task): + Required. The Task associated with the update. The following + fields are maintained by Fleet Engine. Do not update them + using ``Task.update``. + + - ``last_location``. + - ``last_location_snappable``. + - ``name``. + - ``remaining_vehicle_journey_segments``. + - ``task_outcome_location_source``. + + Note: You cannot change the value of ``task_outcome`` once + you set it. + + If the Task has been assigned to a delivery vehicle, then + don't set the Task state to CLOSED using ``Task.update``. + Instead, remove the ``VehicleStop`` that contains the Task + from the delivery vehicle, which automatically sets the Task + state to CLOSED. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field mask that indicates which Task fields to + update. Note: The ``update_mask`` must contain at least one + field. + + This is a comma-separated list of fully qualified names of + fields. Example: + ``"task_outcome,task_outcome_time,task_outcome_location"``. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + task: mfd_tasks.Task = proto.Field( + proto.MESSAGE, + number=3, + message=mfd_tasks.Task, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class ListTasksRequest(proto.Message): + r"""The ``ListTasks`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request + header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The ``provider`` must be the Google Cloud Project ID. For + example, ``sample-cloud-project``. + page_size (int): + Optional. The maximum number of Tasks to + return. The service may return fewer than this + value. If you don't specify this value, then the + server determines the number of results to + return. + page_token (str): + Optional. A page token received from a previous + ``ListTasks`` call. You can provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListTasks`` must match the call that provided the page + token. + filter (str): + Optional. A filter query to apply when listing Tasks. See + http://aip.dev/160 for examples of filter syntax. If you + don't specify a value, or if you filter on an empty string, + then all Tasks are returned. For information about the Task + properties that you can filter on, see `List + tasks `__. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + filter: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListTasksResponse(proto.Message): + r"""The ``ListTasks`` response that contains the set of Tasks that meet + the filter criteria in the ``ListTasksRequest``. + + Attributes: + tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.Task]): + The set of Tasks that meet the requested + filtering criteria. When no filter is specified, + the request returns all tasks. A successful + response can also be empty. An empty response + indicates that no Tasks were found meeting the + requested filter criteria. + next_page_token (str): + Pass this token in the ``ListTasksRequest`` to continue to + list results. If all results have been returned, then this + field is either an empty string, or it doesn't appear in the + response. + total_size (int): + The total number of Tasks that match the + request criteria, across all pages. + """ + + @property + def raw_page(self): + return self + + tasks: MutableSequence[mfd_tasks.Task] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=mfd_tasks.Task, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT64, + number=3, + ) + + +class GetTaskTrackingInfoRequest(proto.Message): + r"""The ``GetTaskTrackingInfoRequest`` request message. + + Attributes: + header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): + Optional. The standard Delivery API request + header. + name (str): + Required. Must be in the format + ``providers/{provider}/taskTrackingInfo/{tracking_id}``. The + ``provider`` must be the Google Cloud Project ID, and the + ``tracking_id`` must be the tracking ID associated with the + task. An example name can be + ``providers/sample-cloud-project/taskTrackingInfo/sample-tracking-id``. + """ + + header: mfd_header.DeliveryRequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mfd_header.DeliveryRequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py new file mode 100644 index 000000000000..2ded1f83bf92 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py @@ -0,0 +1,414 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.fleetengine_delivery_v1.types import common +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.delivery.v1', + manifest={ + 'DeliveryVehicle', + 'LocationInfo', + 'VehicleJourneySegment', + 'VehicleStop', + }, +) + + +class DeliveryVehicle(proto.Message): + r"""The ``DeliveryVehicle`` message. A delivery vehicle transports + shipments from a depot to a delivery location, and from a pickup + location to the depot. In some cases, delivery vehicles also + transport shipments directly from the pickup location to the + delivery location. + + Note: gRPC and REST APIs use different field naming conventions. For + example, the ``DeliveryVehicle.current_route_segment`` field in the + gRPC API and the ``DeliveryVehicle.currentRouteSegment`` field in + the REST API refer to the same field. + + Attributes: + name (str): + The unique name of this Delivery Vehicle. The format is + ``providers/{provider}/deliveryVehicles/{vehicle}``. + last_location (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocation): + The last reported location of the Delivery + Vehicle. + navigation_status (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleNavigationStatus): + The Delivery Vehicle's navigation status. + current_route_segment (bytes): + The encoded polyline specifying the route that the + navigation recommends taking to the next waypoint. Your + driver app updates this when a stop is reached or passed, + and when the navigation reroutes. These ``LatLng``\ s are + returned in + ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0].path`` + (gRPC) or + ``Task.journeySharingInfo.remainingVehicleJourneySegments[0].path`` + (REST) for all active Tasks assigned to the Vehicle. + + There are a few cases where this field might not be used to + populate + ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0].path`` + (gRPC) or + ``Task.journeySharingInfo.remainingVehicleJourneySegments[0].path`` + (REST): + + - The endpoint of the ``current_route_segment`` does not + match + ``DeliveryVehicle.remaining_vehicle_journey_segments[0].stop`` + (gRPC) or + ``DeliveryVehicle.remainingVehicleJourneySegments[0].stop`` + (REST). + + - The driver app has not updated its location recently, so + the last updated value for this field might be stale. + + - The driver app has recently updated its location, but the + ``current_route_segment`` is stale, and points to a + previous vehicle stop. + + In these cases, Fleet Engine populates this field with a + route from the most recently passed VehicleStop to the + upcoming VehicleStop to ensure that the consumer of this + field has the best available information on the current path + of the Delivery Vehicle. + current_route_segment_end_point (google.type.latlng_pb2.LatLng): + The location where the ``current_route_segment`` ends. This + is not currently populated by the driver app, but you can + supply it on ``UpdateDeliveryVehicle`` calls. It is either + the ``LatLng`` from the upcoming vehicle stop, or the last + ``LatLng`` of the ``current_route_segment``. Fleet Engine + will then do its best to interpolate to an actual + ``VehicleStop``. + + This field is ignored in ``UpdateDeliveryVehicle`` calls if + the ``current_route_segment`` field is empty. + remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The remaining driving distance for the + ``current_route_segment``. The Driver app typically provides + this field, but there are some circumstances in which Fleet + Engine will override the value sent by the app. For more + information, see + [DeliveryVehicle.current_route_segment][maps.fleetengine.delivery.v1.DeliveryVehicle.current_route_segment]. + This field is returned in + ``Task.remaining_vehicle_journey_segments[0].driving_distance_meters`` + (gRPC) or + ``Task.remainingVehicleJourneySegments[0].drivingDistanceMeters`` + (REST) for all active ``Task``\ s assigned to the Delivery + Vehicle. + + Fleet Engine ignores this field in + ``UpdateDeliveryVehicleRequest`` if the + ``current_route_segment`` field is empty. + remaining_duration (google.protobuf.duration_pb2.Duration): + The remaining driving time for the + ``current_route_segment``. The Driver app typically provides + this field, but there are some circumstances in which Fleet + Engine will override the value sent by the app. For more + information, see + [DeliveryVehicle.current_route_segment][maps.fleetengine.delivery.v1.DeliveryVehicle.current_route_segment]. + This field is returned in + ``Task.remaining_vehicle_journey_segments[0].driving_duration`` + (gRPC) or + ``Task.remainingVehicleJourneySegments[0].drivingDuration`` + (REST) for all active tasks assigned to the Delivery + Vehicle. + + Fleet Engine ignores this field in + ``UpdateDeliveryVehicleRequest`` if the + ``current_route_segment`` field is empty. + remaining_vehicle_journey_segments (MutableSequence[google.maps.fleetengine_delivery_v1.types.VehicleJourneySegment]): + The journey segments assigned to this Delivery Vehicle, + starting from the Vehicle's most recently reported location. + This field won't be populated in the response of + ``ListDeliveryVehicles``. + attributes (MutableSequence[google.maps.fleetengine_delivery_v1.types.DeliveryVehicleAttribute]): + A list of custom Delivery Vehicle attributes. + A Delivery Vehicle can have at most 100 + attributes, and each attribute must have a + unique key. + type_ (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle.DeliveryVehicleType): + The type of this delivery vehicle. If unset, this will + default to ``AUTO``. + """ + class DeliveryVehicleType(proto.Enum): + r"""The type of delivery vehicle. + + Values: + DELIVERY_VEHICLE_TYPE_UNSPECIFIED (0): + The value is unused. + AUTO (1): + An automobile. + TWO_WHEELER (2): + A motorcycle, moped, or other two-wheeled + vehicle + BICYCLE (3): + Human-powered transport. + PEDESTRIAN (4): + A human transporter, typically walking or + running, traveling along pedestrian pathways. + """ + DELIVERY_VEHICLE_TYPE_UNSPECIFIED = 0 + AUTO = 1 + TWO_WHEELER = 2 + BICYCLE = 3 + PEDESTRIAN = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + last_location: common.DeliveryVehicleLocation = proto.Field( + proto.MESSAGE, + number=2, + message=common.DeliveryVehicleLocation, + ) + navigation_status: common.DeliveryVehicleNavigationStatus = proto.Field( + proto.ENUM, + number=3, + enum=common.DeliveryVehicleNavigationStatus, + ) + current_route_segment: bytes = proto.Field( + proto.BYTES, + number=4, + ) + current_route_segment_end_point: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=5, + message=latlng_pb2.LatLng, + ) + remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.Int32Value, + ) + remaining_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + remaining_vehicle_journey_segments: MutableSequence['VehicleJourneySegment'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='VehicleJourneySegment', + ) + attributes: MutableSequence[common.DeliveryVehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=common.DeliveryVehicleAttribute, + ) + type_: DeliveryVehicleType = proto.Field( + proto.ENUM, + number=10, + enum=DeliveryVehicleType, + ) + + +class LocationInfo(proto.Message): + r"""A location with any additional identifiers. + + Attributes: + point (google.type.latlng_pb2.LatLng): + The location's coordinates. + """ + + point: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + + +class VehicleJourneySegment(proto.Message): + r"""Represents a Vehicle’s travel segment - from its previous + stop to the current stop. If it is the first active stop, then + it is from the Vehicle’s current location to this stop. + + Attributes: + stop (google.maps.fleetengine_delivery_v1.types.VehicleStop): + Specifies the stop location, along with the ``Task``\ s + associated with the stop. Some fields of the VehicleStop + might not be present if this journey segment is part of + ``JourneySharingInfo``. + driving_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + Output only. The travel distance from the previous stop to + this stop. If the current stop is the first stop in the list + of journey segments, then the starting point is the + vehicle's location recorded at the time that this stop was + added to the list. This field might not be present if this + journey segment is part of ``JourneySharingInfo``. + driving_duration (google.protobuf.duration_pb2.Duration): + Output only. The travel time from the previous stop to this + stop. If the current stop is the first stop in the list of + journey segments, then the starting point is the Vehicle's + location recorded at the time that this stop was added to + the list. + + If this field is defined in the path + ``Task.remaining_vehicle_journey_segments[0].driving_duration`` + (gRPC) or + ``Task.remainingVehicleJourneySegments[0].drivingDuration`` + (REST), then it may be populated with the value from + ``DeliveryVehicle.remaining_duration`` (gRPC) or + ``DeliveryVehicle.remainingDuration`` (REST). This provides + the remaining driving duration from the driver app's latest + known location rather than the driving time from the + previous stop. + path (MutableSequence[google.type.latlng_pb2.LatLng]): + Output only. The path from the previous stop to this stop. + If the current stop is the first stop in the list of journey + segments, then this is the path from the vehicle's current + location to this stop at the time that the stop was added to + the list. This field might not be present if this journey + segment is part of ``JourneySharingInfo``. + + If this field is defined in the path + ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0].path`` + (gRPC) or + ``Task.journeySharingInfo.remainingVehicleJourneySegments[0].path`` + (REST), then it may be populated with the ``LatLng``\ s + decoded from ``DeliveryVehicle.current_route_segment`` + (gRPC) or ``DeliveryVehicle.currentRouteSegment`` (REST). + This provides the driving path from the driver app's latest + known location rather than the path from the previous stop. + """ + + stop: 'VehicleStop' = proto.Field( + proto.MESSAGE, + number=1, + message='VehicleStop', + ) + driving_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + driving_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + path: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=latlng_pb2.LatLng, + ) + + +class VehicleStop(proto.Message): + r"""Describes a point where a Vehicle stops to perform one or more + ``Task``\ s. + + Attributes: + planned_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): + Required. The location of the stop. Note that the locations + in the ``Task``\ s might not exactly match this location, + but will be within a short distance of it. This field won't + be populated in the response of a ``GetTask`` call. + tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.VehicleStop.TaskInfo]): + The list of ``Task``\ s to be performed at this stop. This + field won't be populated in the response of a ``GetTask`` + call. + state (google.maps.fleetengine_delivery_v1.types.VehicleStop.State): + The state of the ``VehicleStop``. This field won't be + populated in the response of a ``GetTask`` call. + """ + class State(proto.Enum): + r"""The current state of a ``VehicleStop``. + + Values: + STATE_UNSPECIFIED (0): + Unknown. + NEW (1): + Created, but not actively routing. + ENROUTE (2): + Assigned and actively routing. + ARRIVED (3): + Arrived at stop. Assumes that when the + Vehicle is routing to the next stop, that all + previous stops have been completed. + """ + STATE_UNSPECIFIED = 0 + NEW = 1 + ENROUTE = 2 + ARRIVED = 3 + + class TaskInfo(proto.Message): + r"""Additional information about the Task performed at this stop. + + Attributes: + task_id (str): + The Task ID. This field won't be populated in the response + of a ``GetTask`` call. Task IDs are subject to the following + restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + task_duration (google.protobuf.duration_pb2.Duration): + Output only. The time required to perform the + Task. + target_time_window (google.maps.fleetengine_delivery_v1.types.TimeWindow): + Output only. The time window during which the task should be + completed. This is only set in the response to + ``GetDeliveryVehicle``. + """ + + task_id: str = proto.Field( + proto.STRING, + number=1, + ) + task_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + target_time_window: common.TimeWindow = proto.Field( + proto.MESSAGE, + number=3, + message=common.TimeWindow, + ) + + planned_location: 'LocationInfo' = proto.Field( + proto.MESSAGE, + number=1, + message='LocationInfo', + ) + tasks: MutableSequence[TaskInfo] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=TaskInfo, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.py new file mode 100644 index 000000000000..4764c19a73c6 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.delivery.v1', + manifest={ + 'DeliveryRequestHeader', + }, +) + + +class DeliveryRequestHeader(proto.Message): + r"""A RequestHeader contains fields common to all Delivery RPC + requests. + + Attributes: + language_code (str): + The BCP-47 language code, such as en-US or sr-Latn. For more + information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + If none is specified, the response may be in any language, + with a preference for English if such a name exists. Field + value example: ``en-US``. + region_code (str): + Required. CLDR region code of the region where the request + originates. Field value example: ``US``. + sdk_version (str): + Version of the calling SDK, if applicable. The version + format is "major.minor.patch", example: ``1.1.2``. + os_version (str): + Version of the operating system on which the calling SDK is + running. Field value examples: ``4.4.1``, ``12.1``. + device_model (str): + Model of the device on which the calling SDK is running. + Field value examples: ``iPhone12,1``, ``SM-G920F``. + sdk_type (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader.SdkType): + The type of SDK sending the request. + maps_sdk_version (str): + Version of the MapSDK which the calling SDK depends on, if + applicable. The version format is "major.minor.patch", + example: ``5.2.1``. + nav_sdk_version (str): + Version of the NavSDK which the calling SDK depends on, if + applicable. The version format is "major.minor.patch", + example: ``2.1.0``. + platform (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader.Platform): + Platform of the calling SDK. + manufacturer (str): + Manufacturer of the Android device from the calling SDK, + only applicable for the Android SDKs. Field value example: + ``Samsung``. + android_api_level (int): + Android API level of the calling SDK, only applicable for + the Android SDKs. Field value example: ``23``. + trace_id (str): + Optional ID that can be provided for logging + purposes in order to identify the request. + """ + class SdkType(proto.Enum): + r"""Possible types of SDK. + + Values: + SDK_TYPE_UNSPECIFIED (0): + The default value. This value is used if the ``sdk_type`` is + omitted. + CONSUMER (1): + The calling SDK is Consumer. + DRIVER (2): + The calling SDK is Driver. + JAVASCRIPT (3): + The calling SDK is JavaScript. + """ + SDK_TYPE_UNSPECIFIED = 0 + CONSUMER = 1 + DRIVER = 2 + JAVASCRIPT = 3 + + class Platform(proto.Enum): + r"""The platform of the calling SDK. + + Values: + PLATFORM_UNSPECIFIED (0): + The default value. This value is used if the + platform is omitted. + ANDROID (1): + The request is coming from Android. + IOS (2): + The request is coming from iOS. + WEB (3): + The request is coming from the web. + """ + PLATFORM_UNSPECIFIED = 0 + ANDROID = 1 + IOS = 2 + WEB = 3 + + language_code: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + sdk_version: str = proto.Field( + proto.STRING, + number=3, + ) + os_version: str = proto.Field( + proto.STRING, + number=4, + ) + device_model: str = proto.Field( + proto.STRING, + number=5, + ) + sdk_type: SdkType = proto.Field( + proto.ENUM, + number=6, + enum=SdkType, + ) + maps_sdk_version: str = proto.Field( + proto.STRING, + number=7, + ) + nav_sdk_version: str = proto.Field( + proto.STRING, + number=8, + ) + platform: Platform = proto.Field( + proto.ENUM, + number=9, + enum=Platform, + ) + manufacturer: str = proto.Field( + proto.STRING, + number=10, + ) + android_api_level: int = proto.Field( + proto.INT32, + number=11, + ) + trace_id: str = proto.Field( + proto.STRING, + number=12, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py new file mode 100644 index 000000000000..8ad90dd9b068 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.fleetengine_delivery_v1.types import common +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import tasks +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.delivery.v1', + manifest={ + 'TaskTrackingInfo', + }, +) + + +class TaskTrackingInfo(proto.Message): + r"""The ``TaskTrackingInfo`` message. The message contains task tracking + information which will be used for display. If a tracking ID is + associated with multiple Tasks, Fleet Engine uses a heuristic to + decide which Task's TaskTrackingInfo to select. + + Attributes: + name (str): + Must be in the format + ``providers/{provider}/taskTrackingInfo/{tracking}``, where + ``tracking`` represents the tracking ID. + tracking_id (str): + Immutable. The tracking ID of a Task. + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + vehicle_location (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocation): + The vehicle's last location. + route_polyline_points (MutableSequence[google.type.latlng_pb2.LatLng]): + A list of points which when connected forms a + polyline of the vehicle's expected route to the + location of this task. + remaining_stop_count (google.protobuf.wrappers_pb2.Int32Value): + Indicates the number of stops the vehicle + remaining until the task stop is reached, + including the task stop. For example, if the + vehicle's next stop is the task stop, the value + will be 1. + remaining_driving_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The total remaining distance in meters to the + ``VehicleStop`` of interest. + estimated_arrival_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp that indicates the estimated + arrival time to the stop location. + estimated_task_completion_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp that indicates the estimated + completion time of a Task. + state (google.maps.fleetengine_delivery_v1.types.Task.State): + The current execution state of the Task. + task_outcome (google.maps.fleetengine_delivery_v1.types.Task.TaskOutcome): + The outcome of attempting to execute a Task. + task_outcome_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp that indicates when the Task's + outcome was set by the provider. + planned_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): + Immutable. The location where the Task will + be completed. + target_time_window (google.maps.fleetengine_delivery_v1.types.TimeWindow): + The time window during which the task should + be completed. + attributes (MutableSequence[google.maps.fleetengine_delivery_v1.types.TaskAttribute]): + The custom attributes set on the task. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + tracking_id: str = proto.Field( + proto.STRING, + number=2, + ) + vehicle_location: common.DeliveryVehicleLocation = proto.Field( + proto.MESSAGE, + number=3, + message=common.DeliveryVehicleLocation, + ) + route_polyline_points: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=latlng_pb2.LatLng, + ) + remaining_stop_count: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.Int32Value, + ) + remaining_driving_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.Int32Value, + ) + estimated_arrival_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + estimated_task_completion_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + state: tasks.Task.State = proto.Field( + proto.ENUM, + number=11, + enum=tasks.Task.State, + ) + task_outcome: tasks.Task.TaskOutcome = proto.Field( + proto.ENUM, + number=9, + enum=tasks.Task.TaskOutcome, + ) + task_outcome_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + planned_location: delivery_vehicles.LocationInfo = proto.Field( + proto.MESSAGE, + number=10, + message=delivery_vehicles.LocationInfo, + ) + target_time_window: common.TimeWindow = proto.Field( + proto.MESSAGE, + number=13, + message=common.TimeWindow, + ) + attributes: MutableSequence[common.TaskAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=common.TaskAttribute, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py new file mode 100644 index 000000000000..ecb26f920108 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.fleetengine_delivery_v1.types import common +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.delivery.v1', + manifest={ + 'Task', + 'TaskTrackingViewConfig', + }, +) + + +class Task(proto.Message): + r"""A Task in the Delivery API represents a single action to track. In + general, there is a distinction between shipment-related Tasks and + break Tasks. A shipment can have multiple Tasks associated with it. + For example, there could be one Task for the pickup, and one for the + drop-off or transfer. Also, different Tasks for a given shipment can + be handled by different vehicles. For example, one vehicle could + handle the pickup, driving the shipment to the hub, while another + vehicle drives the same shipment from the hub to the drop-off + location. + + Note: gRPC and REST APIs use different field naming conventions. For + example, the ``Task.journey_sharing_info`` field in the gRPC API and + the ``Task.journeySharingInfo`` field in the REST API refer to the + same field. + + Attributes: + name (str): + Must be in the format ``providers/{provider}/tasks/{task}``. + type_ (google.maps.fleetengine_delivery_v1.types.Task.Type): + Required. Immutable. Defines the type of the + Task. For example, a break or shipment. + state (google.maps.fleetengine_delivery_v1.types.Task.State): + Required. The current execution state of the + Task. + task_outcome (google.maps.fleetengine_delivery_v1.types.Task.TaskOutcome): + The outcome of the Task. + task_outcome_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp that indicates when the ``Task``'s outcome was + set by the provider. + task_outcome_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): + The location where the ``Task``'s outcome was set. This + value is updated as part of ``UpdateTask``. If this value + isn't explicitly updated by the provider, then Fleet Engine + populates it by default with the last known vehicle location + (the *raw* location). + task_outcome_location_source (google.maps.fleetengine_delivery_v1.types.Task.TaskOutcomeLocationSource): + Indicates where the value of the ``task_outcome_location`` + came from. + tracking_id (str): + Immutable. This field facilitates the storing of an ID so + you can avoid using a complicated mapping. You cannot set + ``tracking_id`` for Tasks of type ``UNAVAILABLE`` and + ``SCHEDULED_STOP``. These IDs are subject to the following + restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + delivery_vehicle_id (str): + Output only. The ID of the vehicle that is executing this + Task. Delivery Vehicle IDs are subject to the following + restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + planned_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): + Immutable. The location where the Task will be completed. + Optional for ``UNAVAILABLE`` Tasks, but required for all + other Tasks. + task_duration (google.protobuf.duration_pb2.Duration): + Required. Immutable. The time needed to + execute a Task at this location. + target_time_window (google.maps.fleetengine_delivery_v1.types.TimeWindow): + The time window during which the task should + be completed. + journey_sharing_info (google.maps.fleetengine_delivery_v1.types.Task.JourneySharingInfo): + Output only. Journey sharing-specific fields. Not populated + when state is ``CLOSED``. + task_tracking_view_config (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig): + The configuration for task tracking that + specifies which data elements are visible to the + end users under what circumstances. + attributes (MutableSequence[google.maps.fleetengine_delivery_v1.types.TaskAttribute]): + A list of custom Task attributes. Each + attribute must have a unique key. + """ + class Type(proto.Enum): + r"""The type of Task. + + Values: + TYPE_UNSPECIFIED (0): + Default, the Task type is unknown. + PICKUP (1): + A pickup Task is the action taken for picking up a shipment + from a customer. Depot or feeder vehicle pickups should use + the ``SCHEDULED_STOP`` type. + DELIVERY (2): + A delivery Task is the action taken for delivering a + shipment to an end customer. Depot or feeder vehicle + dropoffs should use the ``SCHEDULED_STOP`` type. + SCHEDULED_STOP (3): + A scheduled stop Task is used for planning + purposes. For example, it could represent + picking up or dropping off shipments from feeder + vehicles or depots. It shouldn't be used for any + shipments that are picked up or dropped off from + an end customer. + UNAVAILABLE (4): + A Task that means the Vehicle is not + available for service. For example, this can + happen when the driver takes a break, or when + the vehicle is being refueled. + """ + TYPE_UNSPECIFIED = 0 + PICKUP = 1 + DELIVERY = 2 + SCHEDULED_STOP = 3 + UNAVAILABLE = 4 + + class State(proto.Enum): + r"""The state of a Task. This indicates the Tasks's progress. + + Values: + STATE_UNSPECIFIED (0): + Default. Used for an unspecified or + unrecognized Task state. + OPEN (1): + Either the Task has not yet been assigned to a delivery + vehicle, or the delivery vehicle has not yet passed the + ``Task``'s assigned vehicle stop. + CLOSED (2): + When the vehicle passes the vehicle stop for + this Task. + """ + STATE_UNSPECIFIED = 0 + OPEN = 1 + CLOSED = 2 + + class TaskOutcome(proto.Enum): + r"""The outcome of attempting to execute a Task. When ``TaskState`` is + closed, ``TaskOutcome`` indicates whether it was completed + successfully. + + Values: + TASK_OUTCOME_UNSPECIFIED (0): + The Task outcome before its value is set. + SUCCEEDED (1): + The Task completed successfully. + FAILED (2): + Either the Task couldn't be completed, or it + was cancelled. + """ + TASK_OUTCOME_UNSPECIFIED = 0 + SUCCEEDED = 1 + FAILED = 2 + + class TaskOutcomeLocationSource(proto.Enum): + r"""The identity of the source that populated the + ``task_outcome_location``. + + Values: + TASK_OUTCOME_LOCATION_SOURCE_UNSPECIFIED (0): + The task outcome before it is set. + PROVIDER (2): + The provider-specified the ``task_outcome_location``. + LAST_VEHICLE_LOCATION (3): + The provider didn't specify the ``task_outcome_location``, + so Fleet Engine used the last known vehicle location. + """ + TASK_OUTCOME_LOCATION_SOURCE_UNSPECIFIED = 0 + PROVIDER = 2 + LAST_VEHICLE_LOCATION = 3 + + class JourneySharingInfo(proto.Message): + r"""Journey sharing specific fields. + + Attributes: + remaining_vehicle_journey_segments (MutableSequence[google.maps.fleetengine_delivery_v1.types.VehicleJourneySegment]): + Tracking information for the stops that the assigned vehicle + will make before it completes this Task. Note that this list + can contain stops from other tasks. + + The first segment, + ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0]`` + (gRPC) or + ``Task.journeySharingInfo.remainingVehicleJourneySegments[0]`` + (REST), contains route information from the driver's last + known location to the upcoming ``VehicleStop``. Current + route information usually comes from the driver app, except + for some cases noted in the documentation for + [DeliveryVehicle.current_route_segment][maps.fleetengine.delivery.v1.DeliveryVehicle.current_route_segment]. + The other segments in + ``Task.journey_sharing_info.remaining_vehicle_journey_segments`` + (gRPC) or + ``Task.journeySharingInfo.remainingVehicleJourneySegments`` + (REST) are populated by Fleet Engine. They provide route + information between the remaining ``VehicleStops``. + last_location (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocation): + Indicates the vehicle's last reported + location of the assigned vehicle. + last_location_snappable (bool): + Indicates whether the vehicle's lastLocation can be snapped + to the ``current_route_segment``. This value is False if + either ``last_location`` or ``current_route_segment`` don't + exist. This value is computed by Fleet Engine. Updates from + clients are ignored. + """ + + remaining_vehicle_journey_segments: MutableSequence[delivery_vehicles.VehicleJourneySegment] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=delivery_vehicles.VehicleJourneySegment, + ) + last_location: common.DeliveryVehicleLocation = proto.Field( + proto.MESSAGE, + number=2, + message=common.DeliveryVehicleLocation, + ) + last_location_snappable: bool = proto.Field( + proto.BOOL, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + task_outcome: TaskOutcome = proto.Field( + proto.ENUM, + number=9, + enum=TaskOutcome, + ) + task_outcome_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + task_outcome_location: delivery_vehicles.LocationInfo = proto.Field( + proto.MESSAGE, + number=11, + message=delivery_vehicles.LocationInfo, + ) + task_outcome_location_source: TaskOutcomeLocationSource = proto.Field( + proto.ENUM, + number=12, + enum=TaskOutcomeLocationSource, + ) + tracking_id: str = proto.Field( + proto.STRING, + number=4, + ) + delivery_vehicle_id: str = proto.Field( + proto.STRING, + number=5, + ) + planned_location: delivery_vehicles.LocationInfo = proto.Field( + proto.MESSAGE, + number=6, + message=delivery_vehicles.LocationInfo, + ) + task_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + target_time_window: common.TimeWindow = proto.Field( + proto.MESSAGE, + number=14, + message=common.TimeWindow, + ) + journey_sharing_info: JourneySharingInfo = proto.Field( + proto.MESSAGE, + number=8, + message=JourneySharingInfo, + ) + task_tracking_view_config: 'TaskTrackingViewConfig' = proto.Field( + proto.MESSAGE, + number=13, + message='TaskTrackingViewConfig', + ) + attributes: MutableSequence[common.TaskAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=15, + message=common.TaskAttribute, + ) + + +class TaskTrackingViewConfig(proto.Message): + r"""The configuration message that defines when a data element of + a Task should be visible to the end users. + + Attributes: + route_polyline_points_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): + The field that specifies when route polyline + points can be visible. If this field is not + specified, the project level default visibility + configuration for this data will be used. + estimated_arrival_time_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): + The field that specifies when estimated + arrival time can be visible. If this field is + not specified, the project level default + visibility configuration for this data will be + used. + estimated_task_completion_time_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): + The field that specifies when estimated task + completion time can be visible. If this field is + not specified, the project level default + visibility configuration for this data will be + used. + remaining_driving_distance_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): + The field that specifies when remaining + driving distance can be visible. If this field + is not specified, the project level default + visibility configuration for this data will be + used. + remaining_stop_count_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): + The field that specifies when remaining stop + count can be visible. If this field is not + specified, the project level default visibility + configuration for this data will be used. + vehicle_location_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): + The field that specifies when vehicle + location can be visible. If this field is not + specified, the project level default visibility + configuration for this data will be used. + """ + + class VisibilityOption(proto.Message): + r"""The option message that defines when a data element should be + visible to the end users. + + 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: + remaining_stop_count_threshold (int): + This data element is visible to the end users if the + remaining stop count <= remaining_stop_count_threshold. + + This field is a member of `oneof`_ ``visibility_option``. + duration_until_estimated_arrival_time_threshold (google.protobuf.duration_pb2.Duration): + This data element is visible to the end users if the ETA to + the stop <= duration_until_estimated_arrival_time_threshold. + + This field is a member of `oneof`_ ``visibility_option``. + remaining_driving_distance_meters_threshold (int): + This data element is visible to the end users if the + remaining driving distance in meters <= + remaining_driving_distance_meters_threshold. + + This field is a member of `oneof`_ ``visibility_option``. + always (bool): + If set to true, this data element is always + visible to the end users with no thresholds. + This field cannot be set to false. + + This field is a member of `oneof`_ ``visibility_option``. + never (bool): + If set to true, this data element is always + hidden from the end users with no thresholds. + This field cannot be set to false. + + This field is a member of `oneof`_ ``visibility_option``. + """ + + remaining_stop_count_threshold: int = proto.Field( + proto.INT32, + number=1, + oneof='visibility_option', + ) + duration_until_estimated_arrival_time_threshold: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + oneof='visibility_option', + message=duration_pb2.Duration, + ) + remaining_driving_distance_meters_threshold: int = proto.Field( + proto.INT32, + number=3, + oneof='visibility_option', + ) + always: bool = proto.Field( + proto.BOOL, + number=4, + oneof='visibility_option', + ) + never: bool = proto.Field( + proto.BOOL, + number=5, + oneof='visibility_option', + ) + + route_polyline_points_visibility: VisibilityOption = proto.Field( + proto.MESSAGE, + number=1, + message=VisibilityOption, + ) + estimated_arrival_time_visibility: VisibilityOption = proto.Field( + proto.MESSAGE, + number=2, + message=VisibilityOption, + ) + estimated_task_completion_time_visibility: VisibilityOption = proto.Field( + proto.MESSAGE, + number=3, + message=VisibilityOption, + ) + remaining_driving_distance_visibility: VisibilityOption = proto.Field( + proto.MESSAGE, + number=4, + message=VisibilityOption, + ) + remaining_stop_count_visibility: VisibilityOption = proto.Field( + proto.MESSAGE, + number=5, + message=VisibilityOption, + ) + vehicle_location_visibility: VisibilityOption = proto.Field( + proto.MESSAGE, + number=6, + message=VisibilityOption, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/maps-fleetengine-delivery-v1-py.tar.gz b/owl-bot-staging/google-maps-fleetengine-delivery/v1/maps-fleetengine-delivery-v1-py.tar.gz new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini b/owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/noxfile.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/noxfile.py new file mode 100644 index 000000000000..c0bf4d81c131 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery' + +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/fleetengine_delivery_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/fleetengine_delivery_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-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py new file mode 100644 index 000000000000..04dfa5f0bb70 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateTasks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_BatchCreateTasks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_batch_create_tasks(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + requests = fleetengine_delivery_v1.CreateTaskRequest() + requests.parent = "parent_value" + requests.task_id = "task_id_value" + requests.task.type_ = "UNAVAILABLE" + requests.task.state = "CLOSED" + + request = fleetengine_delivery_v1.BatchCreateTasksRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_tasks(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_BatchCreateTasks_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py new file mode 100644 index 000000000000..e22a2a94aeb1 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateTasks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_BatchCreateTasks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_batch_create_tasks(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + requests = fleetengine_delivery_v1.CreateTaskRequest() + requests.parent = "parent_value" + requests.task_id = "task_id_value" + requests.task.type_ = "UNAVAILABLE" + requests.task.state = "CLOSED" + + request = fleetengine_delivery_v1.BatchCreateTasksRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_tasks(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_BatchCreateTasks_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py new file mode 100644 index 000000000000..0c37cfba37dd --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_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 CreateDeliveryVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_create_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( + parent="parent_value", + delivery_vehicle_id="delivery_vehicle_id_value", + ) + + # Make the request + response = await client.create_delivery_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py new file mode 100644 index 000000000000..2db42c6068e4 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_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 CreateDeliveryVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_create_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( + parent="parent_value", + delivery_vehicle_id="delivery_vehicle_id_value", + ) + + # Make the request + response = client.create_delivery_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py new file mode 100644 index 000000000000..057d6ba4de47 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_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 CreateTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_CreateTask_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_create_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + task = fleetengine_delivery_v1.Task() + task.type_ = "UNAVAILABLE" + task.state = "CLOSED" + + request = fleetengine_delivery_v1.CreateTaskRequest( + parent="parent_value", + task_id="task_id_value", + task=task, + ) + + # Make the request + response = await client.create_task(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_CreateTask_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py new file mode 100644 index 000000000000..ab663bc61458 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_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 CreateTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_CreateTask_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_create_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + task = fleetengine_delivery_v1.Task() + task.type_ = "UNAVAILABLE" + task.state = "CLOSED" + + request = fleetengine_delivery_v1.CreateTaskRequest( + parent="parent_value", + task_id="task_id_value", + task=task, + ) + + # Make the request + response = client.create_task(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_CreateTask_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py new file mode 100644 index 000000000000..7ec99a4b6b6b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_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 GetDeliveryVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_get_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_delivery_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py new file mode 100644 index 000000000000..13994becb4b5 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_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 GetDeliveryVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_get_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.get_delivery_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_async.py new file mode 100644 index 000000000000..11afdf35a194 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_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 GetTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_GetTask_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_get_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetTaskRequest( + name="name_value", + ) + + # Make the request + response = await client.get_task(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_GetTask_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_sync.py new file mode 100644 index 000000000000..47f7f5d20c3b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_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 GetTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_GetTask_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_get_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetTaskRequest( + name="name_value", + ) + + # Make the request + response = client.get_task(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_GetTask_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py new file mode 100644 index 000000000000..e8f168c07e55 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_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 GetTaskTrackingInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_get_task_tracking_info(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( + name="name_value", + ) + + # Make the request + response = await client.get_task_tracking_info(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py new file mode 100644 index 000000000000..aac42ad23bd4 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_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 GetTaskTrackingInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_get_task_tracking_info(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( + name="name_value", + ) + + # Make the request + response = client.get_task_tracking_info(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py new file mode 100644 index 000000000000..92cd353762c2 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_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 ListDeliveryVehicles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_list_delivery_vehicles(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_delivery_vehicles(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py new file mode 100644 index 000000000000..eb7f3d5332fa --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_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 ListDeliveryVehicles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_list_delivery_vehicles(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_delivery_vehicles(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_async.py new file mode 100644 index 000000000000..5a75c67090bb --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_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 ListTasks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_ListTasks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_list_tasks(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.ListTasksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tasks(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END fleetengine_v1_generated_DeliveryService_ListTasks_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_sync.py new file mode 100644 index 000000000000..5fa38d62c1fb --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_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 ListTasks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_ListTasks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_list_tasks(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.ListTasksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tasks(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END fleetengine_v1_generated_DeliveryService_ListTasks_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py new file mode 100644 index 000000000000..48cb75ccb089 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_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 UpdateDeliveryVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_update_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( + ) + + # Make the request + response = await client.update_delivery_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py new file mode 100644 index 000000000000..b79b67bf7ab0 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_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 UpdateDeliveryVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_update_delivery_vehicle(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( + ) + + # Make the request + response = client.update_delivery_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_async.py new file mode 100644 index 000000000000..e5b4c9099c2f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_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 UpdateTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_UpdateTask_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +async def sample_update_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() + + # Initialize request argument(s) + task = fleetengine_delivery_v1.Task() + task.type_ = "UNAVAILABLE" + task.state = "CLOSED" + + request = fleetengine_delivery_v1.UpdateTaskRequest( + task=task, + ) + + # Make the request + response = await client.update_task(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_UpdateTask_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_sync.py new file mode 100644 index 000000000000..cdb247237fa2 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_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 UpdateTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine-delivery + + +# [START fleetengine_v1_generated_DeliveryService_UpdateTask_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_delivery_v1 + + +def sample_update_task(): + # Create a client + client = fleetengine_delivery_v1.DeliveryServiceClient() + + # Initialize request argument(s) + task = fleetengine_delivery_v1.Task() + task.type_ = "UNAVAILABLE" + task.state = "CLOSED" + + request = fleetengine_delivery_v1.UpdateTaskRequest( + task=task, + ) + + # Make the request + response = client.update_task(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_DeliveryService_UpdateTask_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json new file mode 100644 index 000000000000..884ac226d0e4 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json @@ -0,0 +1,1665 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "maps.fleetengine.delivery.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-fleetengine-delivery", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.batch_create_tasks", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.BatchCreateTasks", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "BatchCreateTasks" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse", + "shortName": "batch_create_tasks" + }, + "description": "Sample for BatchCreateTasks", + "file": "fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_BatchCreateTasks_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.batch_create_tasks", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.BatchCreateTasks", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "BatchCreateTasks" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse", + "shortName": "batch_create_tasks" + }, + "description": "Sample for BatchCreateTasks", + "file": "fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_BatchCreateTasks_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.create_delivery_vehicle", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateDeliveryVehicle", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "CreateDeliveryVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "delivery_vehicle", + "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" + }, + { + "name": "delivery_vehicle_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", + "shortName": "create_delivery_vehicle" + }, + "description": "Sample for CreateDeliveryVehicle", + "file": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.create_delivery_vehicle", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateDeliveryVehicle", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "CreateDeliveryVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "delivery_vehicle", + "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" + }, + { + "name": "delivery_vehicle_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", + "shortName": "create_delivery_vehicle" + }, + "description": "Sample for CreateDeliveryVehicle", + "file": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.create_task", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateTask", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "CreateTask" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.CreateTaskRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "task", + "type": "google.maps.fleetengine_delivery_v1.types.Task" + }, + { + "name": "task_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.Task", + "shortName": "create_task" + }, + "description": "Sample for CreateTask", + "file": "fleetengine_v1_generated_delivery_service_create_task_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_CreateTask_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": "fleetengine_v1_generated_delivery_service_create_task_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.create_task", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateTask", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "CreateTask" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.CreateTaskRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "task", + "type": "google.maps.fleetengine_delivery_v1.types.Task" + }, + { + "name": "task_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.Task", + "shortName": "create_task" + }, + "description": "Sample for CreateTask", + "file": "fleetengine_v1_generated_delivery_service_create_task_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_CreateTask_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": "fleetengine_v1_generated_delivery_service_create_task_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.get_delivery_vehicle", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetDeliveryVehicle", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "GetDeliveryVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", + "shortName": "get_delivery_vehicle" + }, + "description": "Sample for GetDeliveryVehicle", + "file": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.get_delivery_vehicle", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetDeliveryVehicle", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "GetDeliveryVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", + "shortName": "get_delivery_vehicle" + }, + "description": "Sample for GetDeliveryVehicle", + "file": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.get_task_tracking_info", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTaskTrackingInfo", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "GetTaskTrackingInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo", + "shortName": "get_task_tracking_info" + }, + "description": "Sample for GetTaskTrackingInfo", + "file": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_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": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.get_task_tracking_info", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTaskTrackingInfo", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "GetTaskTrackingInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo", + "shortName": "get_task_tracking_info" + }, + "description": "Sample for GetTaskTrackingInfo", + "file": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_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": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.get_task", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTask", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "GetTask" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.GetTaskRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.Task", + "shortName": "get_task" + }, + "description": "Sample for GetTask", + "file": "fleetengine_v1_generated_delivery_service_get_task_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_GetTask_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": "fleetengine_v1_generated_delivery_service_get_task_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.get_task", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTask", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "GetTask" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.GetTaskRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.Task", + "shortName": "get_task" + }, + "description": "Sample for GetTask", + "file": "fleetengine_v1_generated_delivery_service_get_task_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_GetTask_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": "fleetengine_v1_generated_delivery_service_get_task_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.list_delivery_vehicles", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListDeliveryVehicles", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "ListDeliveryVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesAsyncPager", + "shortName": "list_delivery_vehicles" + }, + "description": "Sample for ListDeliveryVehicles", + "file": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_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": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.list_delivery_vehicles", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListDeliveryVehicles", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "ListDeliveryVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesPager", + "shortName": "list_delivery_vehicles" + }, + "description": "Sample for ListDeliveryVehicles", + "file": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_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": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.list_tasks", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListTasks", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "ListTasks" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.ListTasksRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksAsyncPager", + "shortName": "list_tasks" + }, + "description": "Sample for ListTasks", + "file": "fleetengine_v1_generated_delivery_service_list_tasks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_ListTasks_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": "fleetengine_v1_generated_delivery_service_list_tasks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.list_tasks", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListTasks", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "ListTasks" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.ListTasksRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksPager", + "shortName": "list_tasks" + }, + "description": "Sample for ListTasks", + "file": "fleetengine_v1_generated_delivery_service_list_tasks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_ListTasks_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": "fleetengine_v1_generated_delivery_service_list_tasks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.update_delivery_vehicle", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateDeliveryVehicle", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "UpdateDeliveryVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest" + }, + { + "name": "delivery_vehicle", + "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" + }, + { + "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, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", + "shortName": "update_delivery_vehicle" + }, + "description": "Sample for UpdateDeliveryVehicle", + "file": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.update_delivery_vehicle", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateDeliveryVehicle", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "UpdateDeliveryVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest" + }, + { + "name": "delivery_vehicle", + "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" + }, + { + "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, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", + "shortName": "update_delivery_vehicle" + }, + "description": "Sample for UpdateDeliveryVehicle", + "file": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", + "shortName": "DeliveryServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.update_task", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateTask", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "UpdateTask" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest" + }, + { + "name": "task", + "type": "google.maps.fleetengine_delivery_v1.types.Task" + }, + { + "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, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.Task", + "shortName": "update_task" + }, + "description": "Sample for UpdateTask", + "file": "fleetengine_v1_generated_delivery_service_update_task_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateTask_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": "fleetengine_v1_generated_delivery_service_update_task_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", + "shortName": "DeliveryServiceClient" + }, + "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.update_task", + "method": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateTask", + "service": { + "fullName": "maps.fleetengine.delivery.v1.DeliveryService", + "shortName": "DeliveryService" + }, + "shortName": "UpdateTask" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest" + }, + { + "name": "task", + "type": "google.maps.fleetengine_delivery_v1.types.Task" + }, + { + "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, str]" + } + ], + "resultType": "google.maps.fleetengine_delivery_v1.types.Task", + "shortName": "update_task" + }, + "description": "Sample for UpdateTask", + "file": "fleetengine_v1_generated_delivery_service_update_task_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateTask_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": "fleetengine_v1_generated_delivery_service_update_task_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py new file mode 100644 index 000000000000..8dc89e72edee --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py @@ -0,0 +1,185 @@ +#! /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 fleetengine_deliveryCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_tasks': ('parent', 'requests', 'header', ), + 'create_delivery_vehicle': ('parent', 'delivery_vehicle_id', 'delivery_vehicle', 'header', ), + 'create_task': ('parent', 'task_id', 'task', 'header', ), + 'get_delivery_vehicle': ('name', 'header', ), + 'get_task': ('name', 'header', ), + 'get_task_tracking_info': ('name', 'header', ), + 'list_delivery_vehicles': ('parent', 'header', 'page_size', 'page_token', 'filter', 'viewport', ), + 'list_tasks': ('parent', 'header', 'page_size', 'page_token', 'filter', ), + 'update_delivery_vehicle': ('delivery_vehicle', 'update_mask', 'header', ), + 'update_task': ('task', 'update_mask', 'header', ), + } + + 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=fleetengine_deliveryCallTransformer(), +): + """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 fleetengine_delivery 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-fleetengine-delivery/v1/setup.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/setup.py new file mode 100644 index 000000000000..7fb3e991da0e --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery' + + +description = "Google Maps Fleetengine Delivery API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/fleetengine_delivery/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-fleetengine-delivery" + +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-fleetengine-delivery/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..277853c664a0 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/tests/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_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-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py new file mode 100644 index 000000000000..d3dae258b7ff --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py @@ -0,0 +1,9124 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.fleetengine_delivery_v1.services.delivery_service import DeliveryServiceAsyncClient +from google.maps.fleetengine_delivery_v1.services.delivery_service import DeliveryServiceClient +from google.maps.fleetengine_delivery_v1.services.delivery_service import pagers +from google.maps.fleetengine_delivery_v1.services.delivery_service import transports +from google.maps.fleetengine_delivery_v1.types import common +from google.maps.fleetengine_delivery_v1.types import delivery_api +from google.maps.fleetengine_delivery_v1.types import delivery_vehicles +from google.maps.fleetengine_delivery_v1.types import header +from google.maps.fleetengine_delivery_v1.types import task_tracking_info +from google.maps.fleetengine_delivery_v1.types import tasks +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_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 DeliveryServiceClient._get_default_mtls_endpoint(None) is None + assert DeliveryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DeliveryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DeliveryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DeliveryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DeliveryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert DeliveryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert DeliveryServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert DeliveryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + DeliveryServiceClient._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 DeliveryServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert DeliveryServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert DeliveryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + DeliveryServiceClient._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 DeliveryServiceClient._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 DeliveryServiceClient._get_client_cert_source(None, False) is None + assert DeliveryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert DeliveryServiceClient._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 DeliveryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert DeliveryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) +@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = DeliveryServiceClient._DEFAULT_UNIVERSE + default_endpoint = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert DeliveryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert DeliveryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT + assert DeliveryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert DeliveryServiceClient._get_api_endpoint(None, None, default_universe, "always") == DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT + assert DeliveryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT + assert DeliveryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert DeliveryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + DeliveryServiceClient._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 DeliveryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert DeliveryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert DeliveryServiceClient._get_universe_domain(None, None) == DeliveryServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + DeliveryServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc"), + (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DeliveryServiceClient, "grpc"), + (DeliveryServiceAsyncClient, "grpc_asyncio"), + (DeliveryServiceClient, "rest"), +]) +def test_delivery_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 == ( + 'fleetengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://fleetengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DeliveryServiceGrpcTransport, "grpc"), + (transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DeliveryServiceRestTransport, "rest"), +]) +def test_delivery_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", [ + (DeliveryServiceClient, "grpc"), + (DeliveryServiceAsyncClient, "grpc_asyncio"), + (DeliveryServiceClient, "rest"), +]) +def test_delivery_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 == ( + 'fleetengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://fleetengine.googleapis.com' + ) + + +def test_delivery_service_client_get_transport_class(): + transport = DeliveryServiceClient.get_transport_class() + available_transports = [ + transports.DeliveryServiceGrpcTransport, + transports.DeliveryServiceRestTransport, + ] + assert transport in available_transports + + transport = DeliveryServiceClient.get_transport_class("grpc") + assert transport == transports.DeliveryServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc"), + (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest"), +]) +@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) +@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) +def test_delivery_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(DeliveryServiceClient, '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(DeliveryServiceClient, '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", [ + (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", "true"), + (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", "false"), + (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest", "true"), + (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) +@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_delivery_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", [ + DeliveryServiceClient, DeliveryServiceAsyncClient +]) +@mock.patch.object(DeliveryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeliveryServiceClient)) +@mock.patch.object(DeliveryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeliveryServiceAsyncClient)) +def test_delivery_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", [ + DeliveryServiceClient, DeliveryServiceAsyncClient +]) +@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) +@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) +def test_delivery_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = DeliveryServiceClient._DEFAULT_UNIVERSE + default_endpoint = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = DeliveryServiceClient._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", [ + (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc"), + (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest"), +]) +def test_delivery_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", [ + (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", grpc_helpers), + (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest", None), +]) +def test_delivery_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_delivery_service_client_client_options_from_dict(): + with mock.patch('google.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DeliveryServiceClient( + 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", [ + (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", grpc_helpers), + (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_delivery_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( + "fleetengine.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="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.CreateDeliveryVehicleRequest, + dict, +]) +def test_create_delivery_vehicle(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + ) + response = client.create_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.CreateDeliveryVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == 'name_value' + assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + assert response.current_route_segment == b'current_route_segment_blob' + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +def test_create_delivery_vehicle_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.CreateDeliveryVehicleRequest( + parent='parent_value', + delivery_vehicle_id='delivery_vehicle_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_delivery_vehicle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_delivery_vehicle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.CreateDeliveryVehicleRequest( + parent='parent_value', + delivery_vehicle_id='delivery_vehicle_id_value', + ) + +def test_create_delivery_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_delivery_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_delivery_vehicle] = mock_rpc + request = {} + client.create_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_delivery_vehicle(request) + + # Establish that a new wrapper 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_delivery_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_delivery_vehicle in client._client._transport._wrapped_methods + + # 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_delivery_vehicle] = mock_rpc + + request = {} + await client.create_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_delivery_vehicle(request) + + # Establish that a new wrapper 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_delivery_vehicle_async(transport: str = 'grpc_asyncio', request_type=delivery_api.CreateDeliveryVehicleRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + )) + response = await client.create_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.CreateDeliveryVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == 'name_value' + assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + assert response.current_route_segment == b'current_route_segment_blob' + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +@pytest.mark.asyncio +async def test_create_delivery_vehicle_async_from_dict(): + await test_create_delivery_vehicle_async(request_type=dict) + + +def test_create_delivery_vehicle_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_vehicles.DeliveryVehicle() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_delivery_vehicle( + parent='parent_value', + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), + delivery_vehicle_id='delivery_vehicle_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].delivery_vehicle + mock_val = delivery_vehicles.DeliveryVehicle(name='name_value') + assert arg == mock_val + arg = args[0].delivery_vehicle_id + mock_val = 'delivery_vehicle_id_value' + assert arg == mock_val + + +def test_create_delivery_vehicle_flattened_error(): + client = DeliveryServiceClient( + credentials=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_delivery_vehicle( + delivery_api.CreateDeliveryVehicleRequest(), + parent='parent_value', + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), + delivery_vehicle_id='delivery_vehicle_id_value', + ) + +@pytest.mark.asyncio +async def test_create_delivery_vehicle_flattened_async(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_vehicles.DeliveryVehicle() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_delivery_vehicle( + parent='parent_value', + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), + delivery_vehicle_id='delivery_vehicle_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].delivery_vehicle + mock_val = delivery_vehicles.DeliveryVehicle(name='name_value') + assert arg == mock_val + arg = args[0].delivery_vehicle_id + mock_val = 'delivery_vehicle_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_delivery_vehicle_flattened_error_async(): + client = DeliveryServiceAsyncClient( + credentials=async_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_delivery_vehicle( + delivery_api.CreateDeliveryVehicleRequest(), + parent='parent_value', + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), + delivery_vehicle_id='delivery_vehicle_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.GetDeliveryVehicleRequest, + dict, +]) +def test_get_delivery_vehicle(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + ) + response = client.get_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.GetDeliveryVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == 'name_value' + assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + assert response.current_route_segment == b'current_route_segment_blob' + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +def test_get_delivery_vehicle_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.GetDeliveryVehicleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_delivery_vehicle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_delivery_vehicle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.GetDeliveryVehicleRequest( + name='name_value', + ) + +def test_get_delivery_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_delivery_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_delivery_vehicle] = mock_rpc + request = {} + client.get_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_delivery_vehicle(request) + + # Establish that a new wrapper 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_delivery_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_delivery_vehicle in client._client._transport._wrapped_methods + + # 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_delivery_vehicle] = mock_rpc + + request = {} + await client.get_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_delivery_vehicle(request) + + # Establish that a new wrapper 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_delivery_vehicle_async(transport: str = 'grpc_asyncio', request_type=delivery_api.GetDeliveryVehicleRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + )) + response = await client.get_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.GetDeliveryVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == 'name_value' + assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + assert response.current_route_segment == b'current_route_segment_blob' + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +@pytest.mark.asyncio +async def test_get_delivery_vehicle_async_from_dict(): + await test_get_delivery_vehicle_async(request_type=dict) + + +def test_get_delivery_vehicle_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_vehicles.DeliveryVehicle() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_delivery_vehicle( + 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_delivery_vehicle_flattened_error(): + client = DeliveryServiceClient( + credentials=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_delivery_vehicle( + delivery_api.GetDeliveryVehicleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_delivery_vehicle_flattened_async(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_vehicles.DeliveryVehicle() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_delivery_vehicle( + 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_delivery_vehicle_flattened_error_async(): + client = DeliveryServiceAsyncClient( + credentials=async_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_delivery_vehicle( + delivery_api.GetDeliveryVehicleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.UpdateDeliveryVehicleRequest, + dict, +]) +def test_update_delivery_vehicle(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + ) + response = client.update_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.UpdateDeliveryVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == 'name_value' + assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + assert response.current_route_segment == b'current_route_segment_blob' + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +def test_update_delivery_vehicle_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.UpdateDeliveryVehicleRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_delivery_vehicle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_delivery_vehicle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.UpdateDeliveryVehicleRequest( + ) + +def test_update_delivery_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_delivery_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_delivery_vehicle] = mock_rpc + request = {} + client.update_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_delivery_vehicle(request) + + # Establish that a new wrapper 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_delivery_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_delivery_vehicle in client._client._transport._wrapped_methods + + # 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_delivery_vehicle] = mock_rpc + + request = {} + await client.update_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_delivery_vehicle(request) + + # Establish that a new wrapper 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_delivery_vehicle_async(transport: str = 'grpc_asyncio', request_type=delivery_api.UpdateDeliveryVehicleRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + )) + response = await client.update_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.UpdateDeliveryVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == 'name_value' + assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + assert response.current_route_segment == b'current_route_segment_blob' + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +@pytest.mark.asyncio +async def test_update_delivery_vehicle_async_from_dict(): + await test_update_delivery_vehicle_async(request_type=dict) + + +def test_update_delivery_vehicle_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_vehicles.DeliveryVehicle() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_delivery_vehicle( + delivery_vehicle=delivery_vehicles.DeliveryVehicle(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].delivery_vehicle + mock_val = delivery_vehicles.DeliveryVehicle(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_delivery_vehicle_flattened_error(): + client = DeliveryServiceClient( + credentials=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_delivery_vehicle( + delivery_api.UpdateDeliveryVehicleRequest(), + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_delivery_vehicle_flattened_async(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_vehicles.DeliveryVehicle() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_delivery_vehicle( + delivery_vehicle=delivery_vehicles.DeliveryVehicle(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].delivery_vehicle + mock_val = delivery_vehicles.DeliveryVehicle(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_delivery_vehicle_flattened_error_async(): + client = DeliveryServiceAsyncClient( + credentials=async_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_delivery_vehicle( + delivery_api.UpdateDeliveryVehicleRequest(), + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.BatchCreateTasksRequest, + dict, +]) +def test_batch_create_tasks(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_api.BatchCreateTasksResponse( + ) + response = client.batch_create_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.BatchCreateTasksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_api.BatchCreateTasksResponse) + + +def test_batch_create_tasks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.BatchCreateTasksRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_tasks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_tasks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.BatchCreateTasksRequest( + parent='parent_value', + ) + +def test_batch_create_tasks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_tasks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_tasks] = mock_rpc + request = {} + client.batch_create_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_tasks(request) + + # Establish that a new wrapper 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_tasks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_tasks in client._client._transport._wrapped_methods + + # 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_tasks] = mock_rpc + + request = {} + await client.batch_create_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_create_tasks(request) + + # Establish that a new wrapper 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_tasks_async(transport: str = 'grpc_asyncio', request_type=delivery_api.BatchCreateTasksRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.BatchCreateTasksResponse( + )) + response = await client.batch_create_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.BatchCreateTasksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_api.BatchCreateTasksResponse) + + +@pytest.mark.asyncio +async def test_batch_create_tasks_async_from_dict(): + await test_batch_create_tasks_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.CreateTaskRequest, + dict, +]) +def test_create_task(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + ) + response = client.create_task(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.CreateTaskRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tasks.Task) + assert response.name == 'name_value' + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER + assert response.tracking_id == 'tracking_id_value' + assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' + + +def test_create_task_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.CreateTaskRequest( + parent='parent_value', + task_id='task_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_task), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_task(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.CreateTaskRequest( + parent='parent_value', + task_id='task_id_value', + ) + +def test_create_task_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_task] = mock_rpc + request = {} + client.create_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_task(request) + + # Establish that a new wrapper 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_task_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_task in client._client._transport._wrapped_methods + + # 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_task] = mock_rpc + + request = {} + await client.create_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_task(request) + + # Establish that a new wrapper 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_task_async(transport: str = 'grpc_asyncio', request_type=delivery_api.CreateTaskRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + )) + response = await client.create_task(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.CreateTaskRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tasks.Task) + assert response.name == 'name_value' + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER + assert response.tracking_id == 'tracking_id_value' + assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' + + +@pytest.mark.asyncio +async def test_create_task_async_from_dict(): + await test_create_task_async(request_type=dict) + + +def test_create_task_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tasks.Task() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_task( + parent='parent_value', + task=tasks.Task(name='name_value'), + task_id='task_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].task + mock_val = tasks.Task(name='name_value') + assert arg == mock_val + arg = args[0].task_id + mock_val = 'task_id_value' + assert arg == mock_val + + +def test_create_task_flattened_error(): + client = DeliveryServiceClient( + credentials=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_task( + delivery_api.CreateTaskRequest(), + parent='parent_value', + task=tasks.Task(name='name_value'), + task_id='task_id_value', + ) + +@pytest.mark.asyncio +async def test_create_task_flattened_async(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tasks.Task() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_task( + parent='parent_value', + task=tasks.Task(name='name_value'), + task_id='task_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].task + mock_val = tasks.Task(name='name_value') + assert arg == mock_val + arg = args[0].task_id + mock_val = 'task_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_task_flattened_error_async(): + client = DeliveryServiceAsyncClient( + credentials=async_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_task( + delivery_api.CreateTaskRequest(), + parent='parent_value', + task=tasks.Task(name='name_value'), + task_id='task_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.GetTaskRequest, + dict, +]) +def test_get_task(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + ) + response = client.get_task(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.GetTaskRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tasks.Task) + assert response.name == 'name_value' + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER + assert response.tracking_id == 'tracking_id_value' + assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' + + +def test_get_task_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.GetTaskRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_task), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_task(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.GetTaskRequest( + name='name_value', + ) + +def test_get_task_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_task] = mock_rpc + request = {} + client.get_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_task(request) + + # Establish that a new wrapper 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_task_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_task in client._client._transport._wrapped_methods + + # 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_task] = mock_rpc + + request = {} + await client.get_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_task(request) + + # Establish that a new wrapper 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_task_async(transport: str = 'grpc_asyncio', request_type=delivery_api.GetTaskRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + )) + response = await client.get_task(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.GetTaskRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tasks.Task) + assert response.name == 'name_value' + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER + assert response.tracking_id == 'tracking_id_value' + assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' + + +@pytest.mark.asyncio +async def test_get_task_async_from_dict(): + await test_get_task_async(request_type=dict) + + +def test_get_task_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tasks.Task() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_task( + 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_task_flattened_error(): + client = DeliveryServiceClient( + credentials=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_task( + delivery_api.GetTaskRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_task_flattened_async(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tasks.Task() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_task( + 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_task_flattened_error_async(): + client = DeliveryServiceAsyncClient( + credentials=async_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_task( + delivery_api.GetTaskRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.UpdateTaskRequest, + dict, +]) +def test_update_task(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + ) + response = client.update_task(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.UpdateTaskRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tasks.Task) + assert response.name == 'name_value' + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER + assert response.tracking_id == 'tracking_id_value' + assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' + + +def test_update_task_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.UpdateTaskRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_task), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_task(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.UpdateTaskRequest( + ) + +def test_update_task_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_task] = mock_rpc + request = {} + client.update_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_task(request) + + # Establish that a new wrapper 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_task_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_task in client._client._transport._wrapped_methods + + # 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_task] = mock_rpc + + request = {} + await client.update_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_task(request) + + # Establish that a new wrapper 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_task_async(transport: str = 'grpc_asyncio', request_type=delivery_api.UpdateTaskRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + )) + response = await client.update_task(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.UpdateTaskRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tasks.Task) + assert response.name == 'name_value' + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER + assert response.tracking_id == 'tracking_id_value' + assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' + + +@pytest.mark.asyncio +async def test_update_task_async_from_dict(): + await test_update_task_async(request_type=dict) + + +def test_update_task_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tasks.Task() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_task( + task=tasks.Task(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].task + mock_val = tasks.Task(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_task_flattened_error(): + client = DeliveryServiceClient( + credentials=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_task( + delivery_api.UpdateTaskRequest(), + task=tasks.Task(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_task_flattened_async(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tasks.Task() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_task( + task=tasks.Task(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].task + mock_val = tasks.Task(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_task_flattened_error_async(): + client = DeliveryServiceAsyncClient( + credentials=async_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_task( + delivery_api.UpdateTaskRequest(), + task=tasks.Task(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.ListTasksRequest, + dict, +]) +def test_list_tasks(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_api.ListTasksResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.ListTasksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTasksPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_tasks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.ListTasksRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_tasks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.ListTasksRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_tasks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_tasks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_tasks] = mock_rpc + request = {} + client.list_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tasks(request) + + # Establish that a new wrapper 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_tasks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_tasks in client._client._transport._wrapped_methods + + # 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_tasks] = mock_rpc + + request = {} + await client.list_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_tasks(request) + + # Establish that a new wrapper 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_tasks_async(transport: str = 'grpc_asyncio', request_type=delivery_api.ListTasksRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.ListTasksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTasksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_tasks_async_from_dict(): + await test_list_tasks_async(request_type=dict) + + +def test_list_tasks_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_api.ListTasksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tasks( + 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_tasks_flattened_error(): + client = DeliveryServiceClient( + credentials=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_tasks( + delivery_api.ListTasksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_tasks_flattened_async(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_api.ListTasksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tasks( + 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_tasks_flattened_error_async(): + client = DeliveryServiceAsyncClient( + credentials=async_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_tasks( + delivery_api.ListTasksRequest(), + parent='parent_value', + ) + + +def test_list_tasks_pager(transport_name: str = "grpc"): + client = DeliveryServiceClient( + 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_tasks), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + tasks.Task(), + ], + next_page_token='abc', + ), + delivery_api.ListTasksResponse( + tasks=[], + next_page_token='def', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + ], + next_page_token='ghi', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_tasks(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, tasks.Task) + for i in results) +def test_list_tasks_pages(transport_name: str = "grpc"): + client = DeliveryServiceClient( + 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_tasks), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + tasks.Task(), + ], + next_page_token='abc', + ), + delivery_api.ListTasksResponse( + tasks=[], + next_page_token='def', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + ], + next_page_token='ghi', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tasks(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_tasks_async_pager(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + tasks.Task(), + ], + next_page_token='abc', + ), + delivery_api.ListTasksResponse( + tasks=[], + next_page_token='def', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + ], + next_page_token='ghi', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tasks(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, tasks.Task) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_tasks_async_pages(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + tasks.Task(), + ], + next_page_token='abc', + ), + delivery_api.ListTasksResponse( + tasks=[], + next_page_token='def', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + ], + next_page_token='ghi', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + ], + ), + 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_tasks(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", [ + delivery_api.GetTaskTrackingInfoRequest, + dict, +]) +def test_get_task_tracking_info(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_task_tracking_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = task_tracking_info.TaskTrackingInfo( + name='name_value', + tracking_id='tracking_id_value', + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + ) + response = client.get_task_tracking_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.GetTaskTrackingInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, task_tracking_info.TaskTrackingInfo) + assert response.name == 'name_value' + assert response.tracking_id == 'tracking_id_value' + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + + +def test_get_task_tracking_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 = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.GetTaskTrackingInfoRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_task_tracking_info), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_task_tracking_info(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.GetTaskTrackingInfoRequest( + name='name_value', + ) + +def test_get_task_tracking_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 = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_task_tracking_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_task_tracking_info] = mock_rpc + request = {} + client.get_task_tracking_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_task_tracking_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_task_tracking_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 = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_task_tracking_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_task_tracking_info] = mock_rpc + + request = {} + await client.get_task_tracking_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_task_tracking_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_task_tracking_info_async(transport: str = 'grpc_asyncio', request_type=delivery_api.GetTaskTrackingInfoRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_task_tracking_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo( + name='name_value', + tracking_id='tracking_id_value', + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + )) + response = await client.get_task_tracking_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.GetTaskTrackingInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, task_tracking_info.TaskTrackingInfo) + assert response.name == 'name_value' + assert response.tracking_id == 'tracking_id_value' + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + + +@pytest.mark.asyncio +async def test_get_task_tracking_info_async_from_dict(): + await test_get_task_tracking_info_async(request_type=dict) + + +def test_get_task_tracking_info_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_task_tracking_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = task_tracking_info.TaskTrackingInfo() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_task_tracking_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_task_tracking_info_flattened_error(): + client = DeliveryServiceClient( + credentials=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_task_tracking_info( + delivery_api.GetTaskTrackingInfoRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_task_tracking_info_flattened_async(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_task_tracking_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = task_tracking_info.TaskTrackingInfo() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_task_tracking_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_task_tracking_info_flattened_error_async(): + client = DeliveryServiceAsyncClient( + credentials=async_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_task_tracking_info( + delivery_api.GetTaskTrackingInfoRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.ListDeliveryVehiclesRequest, + dict, +]) +def test_list_delivery_vehicles(request_type, transport: str = 'grpc'): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_delivery_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_api.ListDeliveryVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_delivery_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.ListDeliveryVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeliveryVehiclesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_delivery_vehicles_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.ListDeliveryVehiclesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_delivery_vehicles(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.ListDeliveryVehiclesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_delivery_vehicles_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_delivery_vehicles in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_delivery_vehicles] = mock_rpc + request = {} + client.list_delivery_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_delivery_vehicles(request) + + # Establish that a new wrapper 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_delivery_vehicles_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_delivery_vehicles in client._client._transport._wrapped_methods + + # 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_delivery_vehicles] = mock_rpc + + request = {} + await client.list_delivery_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_delivery_vehicles(request) + + # Establish that a new wrapper 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_delivery_vehicles_async(transport: str = 'grpc_asyncio', request_type=delivery_api.ListDeliveryVehiclesRequest): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_delivery_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_delivery_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = delivery_api.ListDeliveryVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeliveryVehiclesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_delivery_vehicles_async_from_dict(): + await test_list_delivery_vehicles_async(request_type=dict) + + +def test_list_delivery_vehicles_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_api.ListDeliveryVehiclesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_delivery_vehicles( + 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_delivery_vehicles_flattened_error(): + client = DeliveryServiceClient( + credentials=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_delivery_vehicles( + delivery_api.ListDeliveryVehiclesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_delivery_vehicles_flattened_async(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_api.ListDeliveryVehiclesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_delivery_vehicles( + 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_delivery_vehicles_flattened_error_async(): + client = DeliveryServiceAsyncClient( + credentials=async_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_delivery_vehicles( + delivery_api.ListDeliveryVehiclesRequest(), + parent='parent_value', + ) + + +def test_list_delivery_vehicles_pager(transport_name: str = "grpc"): + client = DeliveryServiceClient( + 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_delivery_vehicles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='abc', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[], + next_page_token='def', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='ghi', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_delivery_vehicles(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, delivery_vehicles.DeliveryVehicle) + for i in results) +def test_list_delivery_vehicles_pages(transport_name: str = "grpc"): + client = DeliveryServiceClient( + 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_delivery_vehicles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='abc', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[], + next_page_token='def', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='ghi', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + ), + RuntimeError, + ) + pages = list(client.list_delivery_vehicles(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_delivery_vehicles_async_pager(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='abc', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[], + next_page_token='def', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='ghi', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_delivery_vehicles(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, delivery_vehicles.DeliveryVehicle) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_delivery_vehicles_async_pages(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='abc', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[], + next_page_token='def', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='ghi', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + ), + 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_delivery_vehicles(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_delivery_vehicle_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_delivery_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_delivery_vehicle] = mock_rpc + + request = {} + client.create_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_delivery_vehicle(request) + + # Establish 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_delivery_vehicle_rest_required_fields(request_type=delivery_api.CreateDeliveryVehicleRequest): + transport_class = transports.DeliveryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["delivery_vehicle_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 "deliveryVehicleId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_delivery_vehicle._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "deliveryVehicleId" in jsonified_request + assert jsonified_request["deliveryVehicleId"] == request_init["delivery_vehicle_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["deliveryVehicleId"] = 'delivery_vehicle_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_delivery_vehicle._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("delivery_vehicle_id", "header", )) + 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 "deliveryVehicleId" in jsonified_request + assert jsonified_request["deliveryVehicleId"] == 'delivery_vehicle_id_value' + + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = delivery_vehicles.DeliveryVehicle() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_delivery_vehicle(request) + + expected_params = [ + ( + "deliveryVehicleId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_delivery_vehicle_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_delivery_vehicle._get_unset_required_fields({}) + assert set(unset_fields) == (set(("deliveryVehicleId", "header", )) & set(("parent", "deliveryVehicleId", "deliveryVehicle", ))) + + +def test_create_delivery_vehicle_rest_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = delivery_vehicles.DeliveryVehicle() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'providers/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), + delivery_vehicle_id='delivery_vehicle_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 = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_delivery_vehicle(**mock_args) + + # Establish that the underlying call 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=providers/*}/deliveryVehicles" % client.transport._host, args[1]) + + +def test_create_delivery_vehicle_rest_flattened_error(transport: str = 'rest'): + client = DeliveryServiceClient( + credentials=ga_credentials.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_delivery_vehicle( + delivery_api.CreateDeliveryVehicleRequest(), + parent='parent_value', + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), + delivery_vehicle_id='delivery_vehicle_id_value', + ) + + +def test_get_delivery_vehicle_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_delivery_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_delivery_vehicle] = mock_rpc + + request = {} + client.get_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_delivery_vehicle(request) + + # Establish 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_delivery_vehicle_rest_required_fields(request_type=delivery_api.GetDeliveryVehicleRequest): + transport_class = transports.DeliveryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_delivery_vehicle._get_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_delivery_vehicle._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("header", )) + jsonified_request.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 = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = delivery_vehicles.DeliveryVehicle() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_delivery_vehicle(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_delivery_vehicle_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_delivery_vehicle._get_unset_required_fields({}) + assert set(unset_fields) == (set(("header", )) & set(("name", ))) + + +def test_get_delivery_vehicle_rest_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = delivery_vehicles.DeliveryVehicle() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'providers/sample1/deliveryVehicles/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 = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_delivery_vehicle(**mock_args) + + # Establish that the underlying call 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=providers/*/deliveryVehicles/*}" % client.transport._host, args[1]) + + +def test_get_delivery_vehicle_rest_flattened_error(transport: str = 'rest'): + client = DeliveryServiceClient( + credentials=ga_credentials.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_delivery_vehicle( + delivery_api.GetDeliveryVehicleRequest(), + name='name_value', + ) + + +def test_update_delivery_vehicle_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_delivery_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_delivery_vehicle] = mock_rpc + + request = {} + client.update_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_delivery_vehicle(request) + + # Establish 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_delivery_vehicle_rest_required_fields(request_type=delivery_api.UpdateDeliveryVehicleRequest): + transport_class = transports.DeliveryServiceRestTransport + + 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_delivery_vehicle._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_delivery_vehicle._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("header", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = delivery_vehicles.DeliveryVehicle() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_delivery_vehicle(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_delivery_vehicle_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_delivery_vehicle._get_unset_required_fields({}) + assert set(unset_fields) == (set(("header", "updateMask", )) & set(("deliveryVehicle", "updateMask", ))) + + +def test_update_delivery_vehicle_rest_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = delivery_vehicles.DeliveryVehicle() + + # get arguments that satisfy an http rule for this method + sample_request = {'delivery_vehicle': {'name': 'providers/sample1/deliveryVehicles/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + delivery_vehicle=delivery_vehicles.DeliveryVehicle(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 = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_delivery_vehicle(**mock_args) + + # Establish that the underlying call 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/{delivery_vehicle.name=providers/*/deliveryVehicles/*}" % client.transport._host, args[1]) + + +def test_update_delivery_vehicle_rest_flattened_error(transport: str = 'rest'): + client = DeliveryServiceClient( + credentials=ga_credentials.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_delivery_vehicle( + delivery_api.UpdateDeliveryVehicleRequest(), + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_batch_create_tasks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_tasks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_tasks] = mock_rpc + + request = {} + client.batch_create_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_tasks(request) + + # Establish 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_tasks_rest_required_fields(request_type=delivery_api.BatchCreateTasksRequest): + transport_class = transports.DeliveryServiceRestTransport + + 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_tasks._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_tasks._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 = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = delivery_api.BatchCreateTasksResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = delivery_api.BatchCreateTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_create_tasks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_tasks_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_tasks._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) + + +def test_create_task_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_task] = mock_rpc + + request = {} + client.create_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_task(request) + + # Establish 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_task_rest_required_fields(request_type=delivery_api.CreateTaskRequest): + transport_class = transports.DeliveryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["task_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 "taskId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_task._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "taskId" in jsonified_request + assert jsonified_request["taskId"] == request_init["task_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["taskId"] = 'task_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_task._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("header", "task_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 "taskId" in jsonified_request + assert jsonified_request["taskId"] == 'task_id_value' + + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tasks.Task() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = tasks.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_task(request) + + expected_params = [ + ( + "taskId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_task_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_task._get_unset_required_fields({}) + assert set(unset_fields) == (set(("header", "taskId", )) & set(("parent", "taskId", "task", ))) + + +def test_create_task_rest_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tasks.Task() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'providers/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + task=tasks.Task(name='name_value'), + task_id='task_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 = tasks.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_task(**mock_args) + + # Establish that the underlying call 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=providers/*}/tasks" % client.transport._host, args[1]) + + +def test_create_task_rest_flattened_error(transport: str = 'rest'): + client = DeliveryServiceClient( + credentials=ga_credentials.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_task( + delivery_api.CreateTaskRequest(), + parent='parent_value', + task=tasks.Task(name='name_value'), + task_id='task_id_value', + ) + + +def test_get_task_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_task] = mock_rpc + + request = {} + client.get_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_task(request) + + # Establish 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_task_rest_required_fields(request_type=delivery_api.GetTaskRequest): + transport_class = transports.DeliveryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_task._get_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_task._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("header", )) + jsonified_request.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 = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tasks.Task() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = tasks.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_task(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_task_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_task._get_unset_required_fields({}) + assert set(unset_fields) == (set(("header", )) & set(("name", ))) + + +def test_get_task_rest_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tasks.Task() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'providers/sample1/tasks/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 = tasks.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_task(**mock_args) + + # Establish that the underlying call 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=providers/*/tasks/*}" % client.transport._host, args[1]) + + +def test_get_task_rest_flattened_error(transport: str = 'rest'): + client = DeliveryServiceClient( + credentials=ga_credentials.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_task( + delivery_api.GetTaskRequest(), + name='name_value', + ) + + +def test_update_task_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_task] = mock_rpc + + request = {} + client.update_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_task(request) + + # Establish 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_task_rest_required_fields(request_type=delivery_api.UpdateTaskRequest): + transport_class = transports.DeliveryServiceRestTransport + + 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_task._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_task._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("header", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tasks.Task() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = tasks.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_task(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_task_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_task._get_unset_required_fields({}) + assert set(unset_fields) == (set(("header", "updateMask", )) & set(("task", "updateMask", ))) + + +def test_update_task_rest_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tasks.Task() + + # get arguments that satisfy an http rule for this method + sample_request = {'task': {'name': 'providers/sample1/tasks/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + task=tasks.Task(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 = tasks.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_task(**mock_args) + + # Establish that the underlying call 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/{task.name=providers/*/tasks/*}" % client.transport._host, args[1]) + + +def test_update_task_rest_flattened_error(transport: str = 'rest'): + client = DeliveryServiceClient( + credentials=ga_credentials.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_task( + delivery_api.UpdateTaskRequest(), + task=tasks.Task(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_tasks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_tasks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_tasks] = mock_rpc + + request = {} + client.list_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tasks(request) + + # Establish 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_tasks_rest_required_fields(request_type=delivery_api.ListTasksRequest): + transport_class = transports.DeliveryServiceRestTransport + + 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_tasks._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_tasks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "header", "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 = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = delivery_api.ListTasksResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = delivery_api.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_tasks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_tasks_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_tasks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "header", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_tasks_rest_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = delivery_api.ListTasksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'providers/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 = delivery_api.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_tasks(**mock_args) + + # Establish that the underlying call 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=providers/*}/tasks" % client.transport._host, args[1]) + + +def test_list_tasks_rest_flattened_error(transport: str = 'rest'): + client = DeliveryServiceClient( + credentials=ga_credentials.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_tasks( + delivery_api.ListTasksRequest(), + parent='parent_value', + ) + + +def test_list_tasks_rest_pager(transport: str = 'rest'): + client = DeliveryServiceClient( + 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 = ( + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + tasks.Task(), + ], + next_page_token='abc', + ), + delivery_api.ListTasksResponse( + tasks=[], + next_page_token='def', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + ], + next_page_token='ghi', + ), + delivery_api.ListTasksResponse( + tasks=[ + tasks.Task(), + tasks.Task(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(delivery_api.ListTasksResponse.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': 'providers/sample1'} + + pager = client.list_tasks(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tasks.Task) + for i in results) + + pages = list(client.list_tasks(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_task_tracking_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 = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_task_tracking_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_task_tracking_info] = mock_rpc + + request = {} + client.get_task_tracking_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_task_tracking_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_task_tracking_info_rest_required_fields(request_type=delivery_api.GetTaskTrackingInfoRequest): + transport_class = transports.DeliveryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_task_tracking_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_task_tracking_info._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("header", )) + jsonified_request.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 = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = task_tracking_info.TaskTrackingInfo() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = task_tracking_info.TaskTrackingInfo.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_task_tracking_info(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_task_tracking_info_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_task_tracking_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(("header", )) & set(("name", ))) + + +def test_get_task_tracking_info_rest_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = task_tracking_info.TaskTrackingInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'providers/sample1/taskTrackingInfo/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 = task_tracking_info.TaskTrackingInfo.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_task_tracking_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/v1/{name=providers/*/taskTrackingInfo/*}" % client.transport._host, args[1]) + + +def test_get_task_tracking_info_rest_flattened_error(transport: str = 'rest'): + client = DeliveryServiceClient( + credentials=ga_credentials.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_task_tracking_info( + delivery_api.GetTaskTrackingInfoRequest(), + name='name_value', + ) + + +def test_list_delivery_vehicles_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_delivery_vehicles in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_delivery_vehicles] = mock_rpc + + request = {} + client.list_delivery_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_delivery_vehicles(request) + + # Establish 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_delivery_vehicles_rest_required_fields(request_type=delivery_api.ListDeliveryVehiclesRequest): + transport_class = transports.DeliveryServiceRestTransport + + 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_delivery_vehicles._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_delivery_vehicles._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "header", "page_size", "page_token", "viewport", )) + 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 = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = delivery_api.ListDeliveryVehiclesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = delivery_api.ListDeliveryVehiclesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_delivery_vehicles(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_delivery_vehicles_rest_unset_required_fields(): + transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_delivery_vehicles._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "header", "pageSize", "pageToken", "viewport", )) & set(("parent", ))) + + +def test_list_delivery_vehicles_rest_flattened(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = delivery_api.ListDeliveryVehiclesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'providers/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 = delivery_api.ListDeliveryVehiclesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_delivery_vehicles(**mock_args) + + # Establish that the underlying call 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=providers/*}/deliveryVehicles" % client.transport._host, args[1]) + + +def test_list_delivery_vehicles_rest_flattened_error(transport: str = 'rest'): + client = DeliveryServiceClient( + credentials=ga_credentials.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_delivery_vehicles( + delivery_api.ListDeliveryVehiclesRequest(), + parent='parent_value', + ) + + +def test_list_delivery_vehicles_rest_pager(transport: str = 'rest'): + client = DeliveryServiceClient( + 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 = ( + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='abc', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[], + next_page_token='def', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token='ghi', + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(delivery_api.ListDeliveryVehiclesResponse.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': 'providers/sample1'} + + pager = client.list_delivery_vehicles(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, delivery_vehicles.DeliveryVehicle) + for i in results) + + pages = list(client.list_delivery_vehicles(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.DeliveryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DeliveryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeliveryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DeliveryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DeliveryServiceClient( + 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 = DeliveryServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DeliveryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeliveryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeliveryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DeliveryServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeliveryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DeliveryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DeliveryServiceGrpcTransport, + transports.DeliveryServiceGrpcAsyncIOTransport, + transports.DeliveryServiceRestTransport, +]) +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 = DeliveryServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = DeliveryServiceClient( + 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_delivery_vehicle_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_delivery_vehicle), + '__call__') as call: + call.return_value = delivery_vehicles.DeliveryVehicle() + client.create_delivery_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.CreateDeliveryVehicleRequest() + + assert args[0] == request_msg + + +# This 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_delivery_vehicle_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_delivery_vehicle), + '__call__') as call: + call.return_value = delivery_vehicles.DeliveryVehicle() + client.get_delivery_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.GetDeliveryVehicleRequest() + + assert args[0] == request_msg + + +# This 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_delivery_vehicle_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_delivery_vehicle), + '__call__') as call: + call.return_value = delivery_vehicles.DeliveryVehicle() + client.update_delivery_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.UpdateDeliveryVehicleRequest() + + assert args[0] == request_msg + + +# This 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_tasks_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_tasks), + '__call__') as call: + call.return_value = delivery_api.BatchCreateTasksResponse() + client.batch_create_tasks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.BatchCreateTasksRequest() + + assert args[0] == request_msg + + +# This 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_task_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_task), + '__call__') as call: + call.return_value = tasks.Task() + client.create_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.CreateTaskRequest() + + assert args[0] == request_msg + + +# This 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_task_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task), + '__call__') as call: + call.return_value = tasks.Task() + client.get_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.GetTaskRequest() + + assert args[0] == request_msg + + +# This 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_task_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_task), + '__call__') as call: + call.return_value = tasks.Task() + client.update_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.UpdateTaskRequest() + + assert args[0] == request_msg + + +# This 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_tasks_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__') as call: + call.return_value = delivery_api.ListTasksResponse() + client.list_tasks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.ListTasksRequest() + + assert args[0] == request_msg + + +# This 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_task_tracking_info_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task_tracking_info), + '__call__') as call: + call.return_value = task_tracking_info.TaskTrackingInfo() + client.get_task_tracking_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.GetTaskTrackingInfoRequest() + + assert args[0] == request_msg + + +# This 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_delivery_vehicles_empty_call_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__') as call: + call.return_value = delivery_api.ListDeliveryVehiclesResponse() + client.list_delivery_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.ListDeliveryVehiclesRequest() + + assert args[0] == request_msg + + +def test_create_delivery_vehicle_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_delivery_vehicle), + '__call__') as call: + call.return_value = delivery_vehicles.DeliveryVehicle() + client.create_delivery_vehicle(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.CreateDeliveryVehicleRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_delivery_vehicle_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_delivery_vehicle), + '__call__') as call: + call.return_value = delivery_vehicles.DeliveryVehicle() + client.get_delivery_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.GetDeliveryVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_delivery_vehicle_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_delivery_vehicle), + '__call__') as call: + call.return_value = delivery_vehicles.DeliveryVehicle() + client.update_delivery_vehicle(request={"delivery_vehicle": {"name": "providers/sample1"}}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.UpdateDeliveryVehicleRequest(**{"delivery_vehicle": {"name": "providers/sample1"}}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_batch_create_tasks_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_tasks), + '__call__') as call: + call.return_value = delivery_api.BatchCreateTasksResponse() + client.batch_create_tasks(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.BatchCreateTasksRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_create_task_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_task), + '__call__') as call: + call.return_value = tasks.Task() + client.create_task(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.CreateTaskRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_task_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task), + '__call__') as call: + call.return_value = tasks.Task() + client.get_task(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.GetTaskRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_task_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_task), + '__call__') as call: + call.return_value = tasks.Task() + client.update_task(request={"task": {"name": "providers/sample1"}}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.UpdateTaskRequest(**{"task": {"name": "providers/sample1"}}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_list_tasks_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__') as call: + call.return_value = delivery_api.ListTasksResponse() + client.list_tasks(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.ListTasksRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_task_tracking_info_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task_tracking_info), + '__call__') as call: + call.return_value = task_tracking_info.TaskTrackingInfo() + client.get_task_tracking_info(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.GetTaskTrackingInfoRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_list_delivery_vehicles_routing_parameters_request_1_grpc(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__') as call: + call.return_value = delivery_api.ListDeliveryVehiclesResponse() + client.list_delivery_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.ListDeliveryVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_kind_grpc_asyncio(): + transport = DeliveryServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + 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_delivery_vehicle_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + )) + await client.create_delivery_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.CreateDeliveryVehicleRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_delivery_vehicle_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + )) + await client.get_delivery_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.GetDeliveryVehicleRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_delivery_vehicle_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + )) + await client.update_delivery_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.UpdateDeliveryVehicleRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_tasks_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.BatchCreateTasksResponse( + )) + await client.batch_create_tasks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.BatchCreateTasksRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_task_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + )) + await client.create_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.CreateTaskRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_task_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + )) + await client.get_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.GetTaskRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_task_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + )) + await client.update_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.UpdateTaskRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_tasks_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_tasks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.ListTasksRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_task_tracking_info_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task_tracking_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo( + name='name_value', + tracking_id='tracking_id_value', + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + )) + await client.get_task_tracking_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.GetTaskTrackingInfoRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_delivery_vehicles_empty_call_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_delivery_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.ListDeliveryVehiclesRequest() + + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_create_delivery_vehicle_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + )) + await client.create_delivery_vehicle(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.CreateDeliveryVehicleRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_get_delivery_vehicle_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + )) + await client.get_delivery_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.GetDeliveryVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_update_delivery_vehicle_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_delivery_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + )) + await client.update_delivery_vehicle(request={"delivery_vehicle": {"name": "providers/sample1"}}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.UpdateDeliveryVehicleRequest(**{"delivery_vehicle": {"name": "providers/sample1"}}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_batch_create_tasks_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.BatchCreateTasksResponse( + )) + await client.batch_create_tasks(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.BatchCreateTasksRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_create_task_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + )) + await client.create_task(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.CreateTaskRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_get_task_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + )) + await client.get_task(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.GetTaskRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_update_task_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_task), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + )) + await client.update_task(request={"task": {"name": "providers/sample1"}}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.UpdateTaskRequest(**{"task": {"name": "providers/sample1"}}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_list_tasks_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_tasks(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.ListTasksRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_get_task_tracking_info_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task_tracking_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo( + name='name_value', + tracking_id='tracking_id_value', + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + )) + await client.get_task_tracking_info(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.GetTaskTrackingInfoRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_list_delivery_vehicles_routing_parameters_request_1_grpc_asyncio(): + client = DeliveryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_delivery_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.ListDeliveryVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_kind_rest(): + transport = DeliveryServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_delivery_vehicle_rest_bad_request(request_type=delivery_api.CreateDeliveryVehicleRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/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 + client.create_delivery_vehicle(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.CreateDeliveryVehicleRequest, + dict, +]) +def test_create_delivery_vehicle_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/sample1'} + request_init["delivery_vehicle"] = {'name': 'name_value', 'last_location': {'location': {'latitude': 0.86, 'longitude': 0.971}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {'value': 541}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {'seconds': 751, 'nanos': 543}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'navigation_status': 1, 'current_route_segment': b'current_route_segment_blob', 'current_route_segment_end_point': {}, 'remaining_distance_meters': {}, 'remaining_duration': {'seconds': 751, 'nanos': 543}, 'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {'point': {}}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {'start_time': {}, 'end_time': {}}}], 'state': 1}, 'driving_distance_meters': {}, 'driving_duration': {}, 'path': {}}], 'attributes': [{'key': 'key_value', 'value': 'value_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}], '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 = delivery_api.CreateDeliveryVehicleRequest.meta.fields["delivery_vehicle"] + + 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["delivery_vehicle"].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["delivery_vehicle"][field])): + del request_init["delivery_vehicle"][field][i][subfield] + else: + del request_init["delivery_vehicle"][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 = delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_delivery_vehicle(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == 'name_value' + assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + assert response.current_route_segment == b'current_route_segment_blob' + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_delivery_vehicle_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_create_delivery_vehicle") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_create_delivery_vehicle") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.CreateDeliveryVehicleRequest.pb(delivery_api.CreateDeliveryVehicleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = delivery_vehicles.DeliveryVehicle.to_json(delivery_vehicles.DeliveryVehicle()) + req.return_value.content = return_value + + request = delivery_api.CreateDeliveryVehicleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = delivery_vehicles.DeliveryVehicle() + + client.create_delivery_vehicle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_delivery_vehicle_rest_bad_request(request_type=delivery_api.GetDeliveryVehicleRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'providers/sample1/deliveryVehicles/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 + client.get_delivery_vehicle(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.GetDeliveryVehicleRequest, + dict, +]) +def test_get_delivery_vehicle_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'providers/sample1/deliveryVehicles/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 = delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_delivery_vehicle(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == 'name_value' + assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + assert response.current_route_segment == b'current_route_segment_blob' + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_delivery_vehicle_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_get_delivery_vehicle") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_get_delivery_vehicle") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.GetDeliveryVehicleRequest.pb(delivery_api.GetDeliveryVehicleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = delivery_vehicles.DeliveryVehicle.to_json(delivery_vehicles.DeliveryVehicle()) + req.return_value.content = return_value + + request = delivery_api.GetDeliveryVehicleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = delivery_vehicles.DeliveryVehicle() + + client.get_delivery_vehicle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_delivery_vehicle_rest_bad_request(request_type=delivery_api.UpdateDeliveryVehicleRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'delivery_vehicle': {'name': 'providers/sample1/deliveryVehicles/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 + client.update_delivery_vehicle(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.UpdateDeliveryVehicleRequest, + dict, +]) +def test_update_delivery_vehicle_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'delivery_vehicle': {'name': 'providers/sample1/deliveryVehicles/sample2'}} + request_init["delivery_vehicle"] = {'name': 'providers/sample1/deliveryVehicles/sample2', 'last_location': {'location': {'latitude': 0.86, 'longitude': 0.971}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {'value': 541}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {'seconds': 751, 'nanos': 543}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'navigation_status': 1, 'current_route_segment': b'current_route_segment_blob', 'current_route_segment_end_point': {}, 'remaining_distance_meters': {}, 'remaining_duration': {'seconds': 751, 'nanos': 543}, 'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {'point': {}}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {'start_time': {}, 'end_time': {}}}], 'state': 1}, 'driving_distance_meters': {}, 'driving_duration': {}, 'path': {}}], 'attributes': [{'key': 'key_value', 'value': 'value_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}], '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 = delivery_api.UpdateDeliveryVehicleRequest.meta.fields["delivery_vehicle"] + + 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["delivery_vehicle"].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["delivery_vehicle"][field])): + del request_init["delivery_vehicle"][field][i][subfield] + else: + del request_init["delivery_vehicle"][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 = delivery_vehicles.DeliveryVehicle( + name='name_value', + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b'current_route_segment_blob', + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_delivery_vehicle(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == 'name_value' + assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + assert response.current_route_segment == b'current_route_segment_blob' + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_delivery_vehicle_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_update_delivery_vehicle") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_update_delivery_vehicle") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.UpdateDeliveryVehicleRequest.pb(delivery_api.UpdateDeliveryVehicleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = delivery_vehicles.DeliveryVehicle.to_json(delivery_vehicles.DeliveryVehicle()) + req.return_value.content = return_value + + request = delivery_api.UpdateDeliveryVehicleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = delivery_vehicles.DeliveryVehicle() + + client.update_delivery_vehicle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_tasks_rest_bad_request(request_type=delivery_api.BatchCreateTasksRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/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 + client.batch_create_tasks(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.BatchCreateTasksRequest, + dict, +]) +def test_batch_create_tasks_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/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 = delivery_api.BatchCreateTasksResponse( + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = delivery_api.BatchCreateTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_create_tasks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_api.BatchCreateTasksResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_tasks_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_batch_create_tasks") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_batch_create_tasks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.BatchCreateTasksRequest.pb(delivery_api.BatchCreateTasksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = delivery_api.BatchCreateTasksResponse.to_json(delivery_api.BatchCreateTasksResponse()) + req.return_value.content = return_value + + request = delivery_api.BatchCreateTasksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = delivery_api.BatchCreateTasksResponse() + + client.batch_create_tasks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_task_rest_bad_request(request_type=delivery_api.CreateTaskRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/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 + client.create_task(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.CreateTaskRequest, + dict, +]) +def test_create_task_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/sample1'} + request_init["task"] = {'name': 'name_value', 'type_': 1, 'state': 1, 'task_outcome': 1, 'task_outcome_time': {'seconds': 751, 'nanos': 543}, 'task_outcome_location': {'point': {'latitude': 0.86, 'longitude': 0.971}}, 'task_outcome_location_source': 2, 'tracking_id': 'tracking_id_value', 'delivery_vehicle_id': 'delivery_vehicle_id_value', 'planned_location': {}, 'task_duration': {'seconds': 751, 'nanos': 543}, 'target_time_window': {'start_time': {}, 'end_time': {}}, 'journey_sharing_info': {'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {}}], 'state': 1}, 'driving_distance_meters': {'value': 541}, 'driving_duration': {}, 'path': {}}], 'last_location': {'location': {}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'last_location_snappable': True}, 'task_tracking_view_config': {'route_polyline_points_visibility': {'remaining_stop_count_threshold': 3219, 'duration_until_estimated_arrival_time_threshold': {}, 'remaining_driving_distance_meters_threshold': 4561, 'always': True, 'never': True}, 'estimated_arrival_time_visibility': {}, 'estimated_task_completion_time_visibility': {}, 'remaining_driving_distance_visibility': {}, 'remaining_stop_count_visibility': {}, 'vehicle_location_visibility': {}}, 'attributes': [{'key': 'key_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}]} + # 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 = delivery_api.CreateTaskRequest.meta.fields["task"] + + 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["task"].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["task"][field])): + del request_init["task"][field][i][subfield] + else: + del request_init["task"][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 = tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tasks.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_task(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tasks.Task) + assert response.name == 'name_value' + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER + assert response.tracking_id == 'tracking_id_value' + assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_task_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_create_task") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_create_task") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.CreateTaskRequest.pb(delivery_api.CreateTaskRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tasks.Task.to_json(tasks.Task()) + req.return_value.content = return_value + + request = delivery_api.CreateTaskRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tasks.Task() + + client.create_task(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_task_rest_bad_request(request_type=delivery_api.GetTaskRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'providers/sample1/tasks/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 + client.get_task(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.GetTaskRequest, + dict, +]) +def test_get_task_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'providers/sample1/tasks/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 = tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tasks.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_task(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tasks.Task) + assert response.name == 'name_value' + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER + assert response.tracking_id == 'tracking_id_value' + assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_task_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_get_task") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_get_task") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.GetTaskRequest.pb(delivery_api.GetTaskRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tasks.Task.to_json(tasks.Task()) + req.return_value.content = return_value + + request = delivery_api.GetTaskRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tasks.Task() + + client.get_task(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_task_rest_bad_request(request_type=delivery_api.UpdateTaskRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'task': {'name': 'providers/sample1/tasks/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 + client.update_task(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.UpdateTaskRequest, + dict, +]) +def test_update_task_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'task': {'name': 'providers/sample1/tasks/sample2'}} + request_init["task"] = {'name': 'providers/sample1/tasks/sample2', 'type_': 1, 'state': 1, 'task_outcome': 1, 'task_outcome_time': {'seconds': 751, 'nanos': 543}, 'task_outcome_location': {'point': {'latitude': 0.86, 'longitude': 0.971}}, 'task_outcome_location_source': 2, 'tracking_id': 'tracking_id_value', 'delivery_vehicle_id': 'delivery_vehicle_id_value', 'planned_location': {}, 'task_duration': {'seconds': 751, 'nanos': 543}, 'target_time_window': {'start_time': {}, 'end_time': {}}, 'journey_sharing_info': {'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {}}], 'state': 1}, 'driving_distance_meters': {'value': 541}, 'driving_duration': {}, 'path': {}}], 'last_location': {'location': {}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'last_location_snappable': True}, 'task_tracking_view_config': {'route_polyline_points_visibility': {'remaining_stop_count_threshold': 3219, 'duration_until_estimated_arrival_time_threshold': {}, 'remaining_driving_distance_meters_threshold': 4561, 'always': True, 'never': True}, 'estimated_arrival_time_visibility': {}, 'estimated_task_completion_time_visibility': {}, 'remaining_driving_distance_visibility': {}, 'remaining_stop_count_visibility': {}, 'vehicle_location_visibility': {}}, 'attributes': [{'key': 'key_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}]} + # 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 = delivery_api.UpdateTaskRequest.meta.fields["task"] + + 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["task"].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["task"][field])): + del request_init["task"][field][i][subfield] + else: + del request_init["task"][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 = tasks.Task( + name='name_value', + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id='tracking_id_value', + delivery_vehicle_id='delivery_vehicle_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tasks.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_task(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tasks.Task) + assert response.name == 'name_value' + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER + assert response.tracking_id == 'tracking_id_value' + assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_task_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_update_task") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_update_task") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.UpdateTaskRequest.pb(delivery_api.UpdateTaskRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tasks.Task.to_json(tasks.Task()) + req.return_value.content = return_value + + request = delivery_api.UpdateTaskRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tasks.Task() + + client.update_task(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tasks_rest_bad_request(request_type=delivery_api.ListTasksRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/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 + client.list_tasks(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.ListTasksRequest, + dict, +]) +def test_list_tasks_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/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 = delivery_api.ListTasksResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = delivery_api.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_tasks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTasksPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tasks_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_list_tasks") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_list_tasks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.ListTasksRequest.pb(delivery_api.ListTasksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = delivery_api.ListTasksResponse.to_json(delivery_api.ListTasksResponse()) + req.return_value.content = return_value + + request = delivery_api.ListTasksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = delivery_api.ListTasksResponse() + + client.list_tasks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_task_tracking_info_rest_bad_request(request_type=delivery_api.GetTaskTrackingInfoRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'providers/sample1/taskTrackingInfo/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 + client.get_task_tracking_info(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.GetTaskTrackingInfoRequest, + dict, +]) +def test_get_task_tracking_info_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'providers/sample1/taskTrackingInfo/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 = task_tracking_info.TaskTrackingInfo( + name='name_value', + tracking_id='tracking_id_value', + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = task_tracking_info.TaskTrackingInfo.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_task_tracking_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, task_tracking_info.TaskTrackingInfo) + assert response.name == 'name_value' + assert response.tracking_id == 'tracking_id_value' + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_task_tracking_info_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_get_task_tracking_info") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_get_task_tracking_info") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.GetTaskTrackingInfoRequest.pb(delivery_api.GetTaskTrackingInfoRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = task_tracking_info.TaskTrackingInfo.to_json(task_tracking_info.TaskTrackingInfo()) + req.return_value.content = return_value + + request = delivery_api.GetTaskTrackingInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = task_tracking_info.TaskTrackingInfo() + + client.get_task_tracking_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_delivery_vehicles_rest_bad_request(request_type=delivery_api.ListDeliveryVehiclesRequest): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/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 + client.list_delivery_vehicles(request) + + +@pytest.mark.parametrize("request_type", [ + delivery_api.ListDeliveryVehiclesRequest, + dict, +]) +def test_list_delivery_vehicles_rest_call_success(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'providers/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 = delivery_api.ListDeliveryVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = delivery_api.ListDeliveryVehiclesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_delivery_vehicles(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeliveryVehiclesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_delivery_vehicles_rest_interceptors(null_interceptor): + transport = transports.DeliveryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), + ) + client = DeliveryServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_list_delivery_vehicles") as post, \ + mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_list_delivery_vehicles") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = delivery_api.ListDeliveryVehiclesRequest.pb(delivery_api.ListDeliveryVehiclesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = delivery_api.ListDeliveryVehiclesResponse.to_json(delivery_api.ListDeliveryVehiclesResponse()) + req.return_value.content = return_value + + request = delivery_api.ListDeliveryVehiclesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = delivery_api.ListDeliveryVehiclesResponse() + + client.list_delivery_vehicles(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = DeliveryServiceClient( + 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_delivery_vehicle_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_delivery_vehicle), + '__call__') as call: + client.create_delivery_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.CreateDeliveryVehicleRequest() + + assert args[0] == request_msg + + +# This 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_delivery_vehicle_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_delivery_vehicle), + '__call__') as call: + client.get_delivery_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.GetDeliveryVehicleRequest() + + assert args[0] == request_msg + + +# This 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_delivery_vehicle_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_delivery_vehicle), + '__call__') as call: + client.update_delivery_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.UpdateDeliveryVehicleRequest() + + assert args[0] == request_msg + + +# This 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_tasks_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_tasks), + '__call__') as call: + client.batch_create_tasks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.BatchCreateTasksRequest() + + assert args[0] == request_msg + + +# This 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_task_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_task), + '__call__') as call: + client.create_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.CreateTaskRequest() + + assert args[0] == request_msg + + +# This 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_task_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task), + '__call__') as call: + client.get_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.GetTaskRequest() + + assert args[0] == request_msg + + +# This 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_task_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_task), + '__call__') as call: + client.update_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.UpdateTaskRequest() + + assert args[0] == request_msg + + +# This 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_tasks_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__') as call: + client.list_tasks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.ListTasksRequest() + + assert args[0] == request_msg + + +# This 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_task_tracking_info_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task_tracking_info), + '__call__') as call: + client.get_task_tracking_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.GetTaskTrackingInfoRequest() + + assert args[0] == request_msg + + +# This 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_delivery_vehicles_empty_call_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__') as call: + client.list_delivery_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = delivery_api.ListDeliveryVehiclesRequest() + + assert args[0] == request_msg + + +def test_create_delivery_vehicle_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_delivery_vehicle), + '__call__') as call: + client.create_delivery_vehicle(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.CreateDeliveryVehicleRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_delivery_vehicle_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_delivery_vehicle), + '__call__') as call: + client.get_delivery_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.GetDeliveryVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_delivery_vehicle_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_delivery_vehicle), + '__call__') as call: + client.update_delivery_vehicle(request={"delivery_vehicle": {"name": "providers/sample1"}}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.UpdateDeliveryVehicleRequest(**{"delivery_vehicle": {"name": "providers/sample1"}}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_batch_create_tasks_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_tasks), + '__call__') as call: + client.batch_create_tasks(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.BatchCreateTasksRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_create_task_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_task), + '__call__') as call: + client.create_task(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.CreateTaskRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_task_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task), + '__call__') as call: + client.get_task(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.GetTaskRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_task_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_task), + '__call__') as call: + client.update_task(request={"task": {"name": "providers/sample1"}}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.UpdateTaskRequest(**{"task": {"name": "providers/sample1"}}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_list_tasks_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tasks), + '__call__') as call: + client.list_tasks(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.ListTasksRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_task_tracking_info_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_task_tracking_info), + '__call__') as call: + client.get_task_tracking_info(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.GetTaskTrackingInfoRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_list_delivery_vehicles_routing_parameters_request_1_rest(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + '__call__') as call: + client.list_delivery_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = delivery_api.ListDeliveryVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DeliveryServiceGrpcTransport, + ) + +def test_delivery_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DeliveryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_delivery_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DeliveryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_delivery_vehicle', + 'get_delivery_vehicle', + 'update_delivery_vehicle', + 'batch_create_tasks', + 'create_task', + 'get_task', + 'update_task', + 'list_tasks', + 'get_task_tracking_info', + 'list_delivery_vehicles', + ) + 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_delivery_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.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DeliveryServiceTransport( + 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_delivery_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.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DeliveryServiceTransport() + adc.assert_called_once() + + +def test_delivery_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) + DeliveryServiceClient() + 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.DeliveryServiceGrpcTransport, + transports.DeliveryServiceGrpcAsyncIOTransport, + ], +) +def test_delivery_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/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DeliveryServiceGrpcTransport, + transports.DeliveryServiceGrpcAsyncIOTransport, + transports.DeliveryServiceRestTransport, + ], +) +def test_delivery_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.DeliveryServiceGrpcTransport, grpc_helpers), + (transports.DeliveryServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_delivery_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( + "fleetengine.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="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DeliveryServiceGrpcTransport, transports.DeliveryServiceGrpcAsyncIOTransport]) +def test_delivery_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_delivery_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.DeliveryServiceRestTransport ( + 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_delivery_service_host_no_port(transport_name): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://fleetengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_delivery_service_host_with_port(transport_name): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://fleetengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_delivery_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DeliveryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DeliveryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_delivery_vehicle._session + session2 = client2.transport.create_delivery_vehicle._session + assert session1 != session2 + session1 = client1.transport.get_delivery_vehicle._session + session2 = client2.transport.get_delivery_vehicle._session + assert session1 != session2 + session1 = client1.transport.update_delivery_vehicle._session + session2 = client2.transport.update_delivery_vehicle._session + assert session1 != session2 + session1 = client1.transport.batch_create_tasks._session + session2 = client2.transport.batch_create_tasks._session + assert session1 != session2 + session1 = client1.transport.create_task._session + session2 = client2.transport.create_task._session + assert session1 != session2 + session1 = client1.transport.get_task._session + session2 = client2.transport.get_task._session + assert session1 != session2 + session1 = client1.transport.update_task._session + session2 = client2.transport.update_task._session + assert session1 != session2 + session1 = client1.transport.list_tasks._session + session2 = client2.transport.list_tasks._session + assert session1 != session2 + session1 = client1.transport.get_task_tracking_info._session + session2 = client2.transport.get_task_tracking_info._session + assert session1 != session2 + session1 = client1.transport.list_delivery_vehicles._session + session2 = client2.transport.list_delivery_vehicles._session + assert session1 != session2 +def test_delivery_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DeliveryServiceGrpcTransport( + 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_delivery_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DeliveryServiceGrpcAsyncIOTransport( + 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.DeliveryServiceGrpcTransport, transports.DeliveryServiceGrpcAsyncIOTransport]) +def test_delivery_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.DeliveryServiceGrpcTransport, transports.DeliveryServiceGrpcAsyncIOTransport]) +def test_delivery_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_delivery_vehicle_path(): + provider = "squid" + vehicle = "clam" + expected = "providers/{provider}/deliveryVehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) + actual = DeliveryServiceClient.delivery_vehicle_path(provider, vehicle) + assert expected == actual + + +def test_parse_delivery_vehicle_path(): + expected = { + "provider": "whelk", + "vehicle": "octopus", + } + path = DeliveryServiceClient.delivery_vehicle_path(**expected) + + # Check that the path construction is reversible. + actual = DeliveryServiceClient.parse_delivery_vehicle_path(path) + assert expected == actual + +def test_task_path(): + provider = "oyster" + task = "nudibranch" + expected = "providers/{provider}/tasks/{task}".format(provider=provider, task=task, ) + actual = DeliveryServiceClient.task_path(provider, task) + assert expected == actual + + +def test_parse_task_path(): + expected = { + "provider": "cuttlefish", + "task": "mussel", + } + path = DeliveryServiceClient.task_path(**expected) + + # Check that the path construction is reversible. + actual = DeliveryServiceClient.parse_task_path(path) + assert expected == actual + +def test_task_tracking_info_path(): + provider = "winkle" + tracking = "nautilus" + expected = "providers/{provider}/taskTrackingInfo/{tracking}".format(provider=provider, tracking=tracking, ) + actual = DeliveryServiceClient.task_tracking_info_path(provider, tracking) + assert expected == actual + + +def test_parse_task_tracking_info_path(): + expected = { + "provider": "scallop", + "tracking": "abalone", + } + path = DeliveryServiceClient.task_tracking_info_path(**expected) + + # Check that the path construction is reversible. + actual = DeliveryServiceClient.parse_task_tracking_info_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DeliveryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DeliveryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DeliveryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = DeliveryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DeliveryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DeliveryServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DeliveryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DeliveryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DeliveryServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = DeliveryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DeliveryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DeliveryServiceClient.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 = DeliveryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DeliveryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DeliveryServiceClient.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.DeliveryServiceTransport, '_prep_wrapped_messages') as prep: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DeliveryServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DeliveryServiceClient.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 = DeliveryServiceClient( + 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 = DeliveryServiceAsyncClient( + 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 = DeliveryServiceClient( + 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 = DeliveryServiceClient( + 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", [ + (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport), + (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport), +]) +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-fleetengine/v1/.coveragerc b/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc new file mode 100644 index 000000000000..2611031f9d9f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/fleetengine/__init__.py + google/maps/fleetengine/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-fleetengine/v1/.flake8 b/owl-bot-staging/google-maps-fleetengine/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/MANIFEST.in b/owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in new file mode 100644 index 000000000000..3dcb3007a4fb --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/fleetengine *.py +recursive-include google/maps/fleetengine_v1 *.py diff --git a/owl-bot-staging/google-maps-fleetengine/v1/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/README.rst new file mode 100644 index 000000000000..b9bd958ce86c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Fleetengine 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 Fleetengine 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-fleetengine/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py b/owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py new file mode 100644 index 000000000000..de2c2c6df868 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine 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-fleetengine" +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-fleetengine-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-fleetengine.tex", + u"google-maps-fleetengine 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-fleetengine", + u"Google Maps Fleetengine 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-fleetengine", + u"google-maps-fleetengine Documentation", + author, + "google-maps-fleetengine", + "GAPIC library for Google Maps Fleetengine 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-fleetengine/v1/docs/fleetengine_v1/services_.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst new file mode 100644 index 000000000000..a23a0eb62775 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst @@ -0,0 +1,7 @@ +Services for Google Maps Fleetengine v1 API +=========================================== +.. toctree:: + :maxdepth: 2 + + trip_service + vehicle_service diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst new file mode 100644 index 000000000000..9cb42aff9bcf --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst @@ -0,0 +1,10 @@ +TripService +----------------------------- + +.. automodule:: google.maps.fleetengine_v1.services.trip_service + :members: + :inherited-members: + +.. automodule:: google.maps.fleetengine_v1.services.trip_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst new file mode 100644 index 000000000000..2e980bba2916 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Fleetengine v1 API +======================================== + +.. automodule:: google.maps.fleetengine_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst new file mode 100644 index 000000000000..e1bfe924fcca --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst @@ -0,0 +1,10 @@ +VehicleService +-------------------------------- + +.. automodule:: google.maps.fleetengine_v1.services.vehicle_service + :members: + :inherited-members: + +.. automodule:: google.maps.fleetengine_v1.services.vehicle_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst new file mode 100644 index 000000000000..2b0090bf63a3 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + fleetengine_v1/services_ + fleetengine_v1/types_ diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py new file mode 100644 index 000000000000..474efa60eda8 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.fleetengine import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.fleetengine_v1.services.trip_service.client import TripServiceClient +from google.maps.fleetengine_v1.services.trip_service.async_client import TripServiceAsyncClient +from google.maps.fleetengine_v1.services.vehicle_service.client import VehicleServiceClient +from google.maps.fleetengine_v1.services.vehicle_service.async_client import VehicleServiceAsyncClient + +from google.maps.fleetengine_v1.types.fleetengine import TerminalLocation +from google.maps.fleetengine_v1.types.fleetengine import TerminalPointId +from google.maps.fleetengine_v1.types.fleetengine import TripWaypoint +from google.maps.fleetengine_v1.types.fleetengine import VehicleAttribute +from google.maps.fleetengine_v1.types.fleetengine import VehicleLocation +from google.maps.fleetengine_v1.types.fleetengine import LocationSensor +from google.maps.fleetengine_v1.types.fleetengine import NavigationStatus +from google.maps.fleetengine_v1.types.fleetengine import PolylineFormatType +from google.maps.fleetengine_v1.types.fleetengine import TripType +from google.maps.fleetengine_v1.types.fleetengine import WaypointType +from google.maps.fleetengine_v1.types.header import RequestHeader +from google.maps.fleetengine_v1.types.traffic import ConsumableTrafficPolyline +from google.maps.fleetengine_v1.types.traffic import SpeedReadingInterval +from google.maps.fleetengine_v1.types.trip_api import CreateTripRequest +from google.maps.fleetengine_v1.types.trip_api import GetTripRequest +from google.maps.fleetengine_v1.types.trip_api import ReportBillableTripRequest +from google.maps.fleetengine_v1.types.trip_api import SearchTripsRequest +from google.maps.fleetengine_v1.types.trip_api import SearchTripsResponse +from google.maps.fleetengine_v1.types.trip_api import UpdateTripRequest +from google.maps.fleetengine_v1.types.trips import StopLocation +from google.maps.fleetengine_v1.types.trips import Trip +from google.maps.fleetengine_v1.types.trips import BillingPlatformIdentifier +from google.maps.fleetengine_v1.types.trips import TripStatus +from google.maps.fleetengine_v1.types.trips import TripView +from google.maps.fleetengine_v1.types.vehicle_api import CreateVehicleRequest +from google.maps.fleetengine_v1.types.vehicle_api import GetVehicleRequest +from google.maps.fleetengine_v1.types.vehicle_api import ListVehiclesRequest +from google.maps.fleetengine_v1.types.vehicle_api import ListVehiclesResponse +from google.maps.fleetengine_v1.types.vehicle_api import SearchVehiclesRequest +from google.maps.fleetengine_v1.types.vehicle_api import SearchVehiclesResponse +from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleAttributesRequest +from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleAttributesResponse +from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleRequest +from google.maps.fleetengine_v1.types.vehicle_api import VehicleAttributeList +from google.maps.fleetengine_v1.types.vehicle_api import VehicleMatch +from google.maps.fleetengine_v1.types.vehicle_api import Waypoint +from google.maps.fleetengine_v1.types.vehicles import BatteryInfo +from google.maps.fleetengine_v1.types.vehicles import DeviceSettings +from google.maps.fleetengine_v1.types.vehicles import LicensePlate +from google.maps.fleetengine_v1.types.vehicles import TrafficPolylineData +from google.maps.fleetengine_v1.types.vehicles import Vehicle +from google.maps.fleetengine_v1.types.vehicles import VisualTrafficReportPolylineRendering +from google.maps.fleetengine_v1.types.vehicles import BatteryStatus +from google.maps.fleetengine_v1.types.vehicles import LocationPowerSaveMode +from google.maps.fleetengine_v1.types.vehicles import PowerSource +from google.maps.fleetengine_v1.types.vehicles import VehicleState + +__all__ = ('TripServiceClient', + 'TripServiceAsyncClient', + 'VehicleServiceClient', + 'VehicleServiceAsyncClient', + 'TerminalLocation', + 'TerminalPointId', + 'TripWaypoint', + 'VehicleAttribute', + 'VehicleLocation', + 'LocationSensor', + 'NavigationStatus', + 'PolylineFormatType', + 'TripType', + 'WaypointType', + 'RequestHeader', + 'ConsumableTrafficPolyline', + 'SpeedReadingInterval', + 'CreateTripRequest', + 'GetTripRequest', + 'ReportBillableTripRequest', + 'SearchTripsRequest', + 'SearchTripsResponse', + 'UpdateTripRequest', + 'StopLocation', + 'Trip', + 'BillingPlatformIdentifier', + 'TripStatus', + 'TripView', + 'CreateVehicleRequest', + 'GetVehicleRequest', + 'ListVehiclesRequest', + 'ListVehiclesResponse', + 'SearchVehiclesRequest', + 'SearchVehiclesResponse', + 'UpdateVehicleAttributesRequest', + 'UpdateVehicleAttributesResponse', + 'UpdateVehicleRequest', + 'VehicleAttributeList', + 'VehicleMatch', + 'Waypoint', + 'BatteryInfo', + 'DeviceSettings', + 'LicensePlate', + 'TrafficPolylineData', + 'Vehicle', + 'VisualTrafficReportPolylineRendering', + 'BatteryStatus', + 'LocationPowerSaveMode', + 'PowerSource', + 'VehicleState', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/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-fleetengine/v1/google/maps/fleetengine/py.typed b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed new file mode 100644 index 000000000000..47d8e9910cb6 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-fleetengine package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py new file mode 100644 index 000000000000..74f5cd53382b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.fleetengine_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.trip_service import TripServiceClient +from .services.trip_service import TripServiceAsyncClient +from .services.vehicle_service import VehicleServiceClient +from .services.vehicle_service import VehicleServiceAsyncClient + +from .types.fleetengine import TerminalLocation +from .types.fleetengine import TerminalPointId +from .types.fleetengine import TripWaypoint +from .types.fleetengine import VehicleAttribute +from .types.fleetengine import VehicleLocation +from .types.fleetengine import LocationSensor +from .types.fleetengine import NavigationStatus +from .types.fleetengine import PolylineFormatType +from .types.fleetengine import TripType +from .types.fleetengine import WaypointType +from .types.header import RequestHeader +from .types.traffic import ConsumableTrafficPolyline +from .types.traffic import SpeedReadingInterval +from .types.trip_api import CreateTripRequest +from .types.trip_api import GetTripRequest +from .types.trip_api import ReportBillableTripRequest +from .types.trip_api import SearchTripsRequest +from .types.trip_api import SearchTripsResponse +from .types.trip_api import UpdateTripRequest +from .types.trips import StopLocation +from .types.trips import Trip +from .types.trips import BillingPlatformIdentifier +from .types.trips import TripStatus +from .types.trips import TripView +from .types.vehicle_api import CreateVehicleRequest +from .types.vehicle_api import GetVehicleRequest +from .types.vehicle_api import ListVehiclesRequest +from .types.vehicle_api import ListVehiclesResponse +from .types.vehicle_api import SearchVehiclesRequest +from .types.vehicle_api import SearchVehiclesResponse +from .types.vehicle_api import UpdateVehicleAttributesRequest +from .types.vehicle_api import UpdateVehicleAttributesResponse +from .types.vehicle_api import UpdateVehicleRequest +from .types.vehicle_api import VehicleAttributeList +from .types.vehicle_api import VehicleMatch +from .types.vehicle_api import Waypoint +from .types.vehicles import BatteryInfo +from .types.vehicles import DeviceSettings +from .types.vehicles import LicensePlate +from .types.vehicles import TrafficPolylineData +from .types.vehicles import Vehicle +from .types.vehicles import VisualTrafficReportPolylineRendering +from .types.vehicles import BatteryStatus +from .types.vehicles import LocationPowerSaveMode +from .types.vehicles import PowerSource +from .types.vehicles import VehicleState + +__all__ = ( + 'TripServiceAsyncClient', + 'VehicleServiceAsyncClient', +'BatteryInfo', +'BatteryStatus', +'BillingPlatformIdentifier', +'ConsumableTrafficPolyline', +'CreateTripRequest', +'CreateVehicleRequest', +'DeviceSettings', +'GetTripRequest', +'GetVehicleRequest', +'LicensePlate', +'ListVehiclesRequest', +'ListVehiclesResponse', +'LocationPowerSaveMode', +'LocationSensor', +'NavigationStatus', +'PolylineFormatType', +'PowerSource', +'ReportBillableTripRequest', +'RequestHeader', +'SearchTripsRequest', +'SearchTripsResponse', +'SearchVehiclesRequest', +'SearchVehiclesResponse', +'SpeedReadingInterval', +'StopLocation', +'TerminalLocation', +'TerminalPointId', +'TrafficPolylineData', +'Trip', +'TripServiceClient', +'TripStatus', +'TripType', +'TripView', +'TripWaypoint', +'UpdateTripRequest', +'UpdateVehicleAttributesRequest', +'UpdateVehicleAttributesResponse', +'UpdateVehicleRequest', +'Vehicle', +'VehicleAttribute', +'VehicleAttributeList', +'VehicleLocation', +'VehicleMatch', +'VehicleServiceClient', +'VehicleState', +'VisualTrafficReportPolylineRendering', +'Waypoint', +'WaypointType', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json new file mode 100644 index 000000000000..1a6ac8f7d116 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json @@ -0,0 +1,147 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.fleetengine_v1", + "protoPackage": "maps.fleetengine.v1", + "schema": "1.0", + "services": { + "TripService": { + "clients": { + "grpc": { + "libraryClient": "TripServiceClient", + "rpcs": { + "CreateTrip": { + "methods": [ + "create_trip" + ] + }, + "GetTrip": { + "methods": [ + "get_trip" + ] + }, + "ReportBillableTrip": { + "methods": [ + "report_billable_trip" + ] + }, + "SearchTrips": { + "methods": [ + "search_trips" + ] + }, + "UpdateTrip": { + "methods": [ + "update_trip" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TripServiceAsyncClient", + "rpcs": { + "CreateTrip": { + "methods": [ + "create_trip" + ] + }, + "GetTrip": { + "methods": [ + "get_trip" + ] + }, + "ReportBillableTrip": { + "methods": [ + "report_billable_trip" + ] + }, + "SearchTrips": { + "methods": [ + "search_trips" + ] + }, + "UpdateTrip": { + "methods": [ + "update_trip" + ] + } + } + } + } + }, + "VehicleService": { + "clients": { + "grpc": { + "libraryClient": "VehicleServiceClient", + "rpcs": { + "CreateVehicle": { + "methods": [ + "create_vehicle" + ] + }, + "GetVehicle": { + "methods": [ + "get_vehicle" + ] + }, + "ListVehicles": { + "methods": [ + "list_vehicles" + ] + }, + "SearchVehicles": { + "methods": [ + "search_vehicles" + ] + }, + "UpdateVehicle": { + "methods": [ + "update_vehicle" + ] + }, + "UpdateVehicleAttributes": { + "methods": [ + "update_vehicle_attributes" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VehicleServiceAsyncClient", + "rpcs": { + "CreateVehicle": { + "methods": [ + "create_vehicle" + ] + }, + "GetVehicle": { + "methods": [ + "get_vehicle" + ] + }, + "ListVehicles": { + "methods": [ + "list_vehicles" + ] + }, + "SearchVehicles": { + "methods": [ + "search_vehicles" + ] + }, + "UpdateVehicle": { + "methods": [ + "update_vehicle" + ] + }, + "UpdateVehicleAttributes": { + "methods": [ + "update_vehicle_attributes" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_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-fleetengine/v1/google/maps/fleetengine_v1/py.typed b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed new file mode 100644 index 000000000000..47d8e9910cb6 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-fleetengine package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py new file mode 100644 index 000000000000..268b90139486 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_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 TripServiceClient +from .async_client import TripServiceAsyncClient + +__all__ = ( + 'TripServiceClient', + 'TripServiceAsyncClient', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py new file mode 100644 index 000000000000..f32fa72743e2 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py @@ -0,0 +1,675 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.maps.fleetengine_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.fleetengine_v1.services.trip_service import pagers +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import traffic +from google.maps.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +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.type import latlng_pb2 # type: ignore +from .transports.base import TripServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TripServiceGrpcAsyncIOTransport +from .client import TripServiceClient + + +class TripServiceAsyncClient: + """Trip management service.""" + + _client: TripServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = TripServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TripServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = TripServiceClient._DEFAULT_UNIVERSE + + trip_path = staticmethod(TripServiceClient.trip_path) + parse_trip_path = staticmethod(TripServiceClient.parse_trip_path) + common_billing_account_path = staticmethod(TripServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TripServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TripServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(TripServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(TripServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(TripServiceClient.parse_common_organization_path) + common_project_path = staticmethod(TripServiceClient.common_project_path) + parse_common_project_path = staticmethod(TripServiceClient.parse_common_project_path) + common_location_path = staticmethod(TripServiceClient.common_location_path) + parse_common_location_path = staticmethod(TripServiceClient.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: + TripServiceAsyncClient: The constructed client. + """ + return TripServiceClient.from_service_account_info.__func__(TripServiceAsyncClient, 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: + TripServiceAsyncClient: The constructed client. + """ + return TripServiceClient.from_service_account_file.__func__(TripServiceAsyncClient, 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 TripServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TripServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TripServiceTransport: 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 = TripServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, TripServiceTransport, Callable[..., TripServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the trip 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,TripServiceTransport,Callable[..., TripServiceTransport]]]): + 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 TripServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = TripServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_trip(self, + request: Optional[Union[trip_api.CreateTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Creates a trip in the Fleet Engine and returns the + new trip. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_create_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateTripRequest( + parent="parent_value", + trip_id="trip_id_value", + ) + + # Make the request + response = await client.create_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.CreateTripRequest, dict]]): + The request object. CreateTrip 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.CreateTripRequest): + request = trip_api.CreateTripRequest(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_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_trip(self, + request: Optional[Union[trip_api.GetTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Get information about a single trip. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_get_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetTripRequest( + name="name_value", + ) + + # Make the request + response = await client.get_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.GetTripRequest, dict]]): + The request object. GetTrip 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.GetTripRequest): + request = trip_api.GetTripRequest(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_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def report_billable_trip(self, + request: Optional[Union[trip_api.ReportBillableTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Report billable trip usage. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_report_billable_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.ReportBillableTripRequest( + name="name_value", + country_code="country_code_value", + ) + + # Make the request + await client.report_billable_trip(request=request) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.ReportBillableTripRequest, dict]]): + The request object. ReportBillableTrip 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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, trip_api.ReportBillableTripRequest): + request = trip_api.ReportBillableTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.report_billable_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def search_trips(self, + request: Optional[Union[trip_api.SearchTripsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchTripsAsyncPager: + r"""Get all the trips for a specific vehicle. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_search_trips(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchTripsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.search_trips(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.SearchTripsRequest, dict]]): + The request object. SearchTrips 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsAsyncPager: + SearchTrips response message. + + 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, trip_api.SearchTripsRequest): + request = trip_api.SearchTripsRequest(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_trips] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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.SearchTripsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_trip(self, + request: Optional[Union[trip_api.UpdateTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Updates trip data. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_update_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateTripRequest( + name="name_value", + ) + + # Make the request + response = await client.update_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.UpdateTripRequest, dict]]): + The request object. UpdateTrip 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.UpdateTripRequest): + request = trip_api.UpdateTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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) -> "TripServiceAsyncClient": + 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__ = ( + "TripServiceAsyncClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py new file mode 100644 index 000000000000..f419a120f8ca --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py @@ -0,0 +1,1030 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.maps.fleetengine_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 + +from google.maps.fleetengine_v1.services.trip_service import pagers +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import traffic +from google.maps.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +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.type import latlng_pb2 # type: ignore +from .transports.base import TripServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TripServiceGrpcTransport +from .transports.grpc_asyncio import TripServiceGrpcAsyncIOTransport + + +class TripServiceClientMeta(type): + """Metaclass for the TripService 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[TripServiceTransport]] + _transport_registry["grpc"] = TripServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TripServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[TripServiceTransport]: + """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 TripServiceClient(metaclass=TripServiceClientMeta): + """Trip management service.""" + + @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 = "fleetengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: + TripServiceClient: 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: + TripServiceClient: 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) -> TripServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TripServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def trip_path(provider: str,trip: str,) -> str: + """Returns a fully-qualified trip string.""" + return "providers/{provider}/trips/{trip}".format(provider=provider, trip=trip, ) + + @staticmethod + def parse_trip_path(path: str) -> Dict[str,str]: + """Parses a trip path into its component segments.""" + m = re.match(r"^providers/(?P.+?)/trips/(?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 = TripServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = TripServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = TripServiceClient._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 = TripServiceClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = TripServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + TripServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, TripServiceTransport, Callable[..., TripServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the trip 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,TripServiceTransport,Callable[..., TripServiceTransport]]]): + 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 TripServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = TripServiceClient._read_environment_variables() + self._client_cert_source = TripServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = TripServiceClient._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 + + 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, TripServiceTransport) + if transport_provided: + # transport is a TripServiceTransport 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(TripServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + TripServiceClient._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[TripServiceTransport], Callable[..., TripServiceTransport]] = ( + TripServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., TripServiceTransport], 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, + ) + + def create_trip(self, + request: Optional[Union[trip_api.CreateTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Creates a trip in the Fleet Engine and returns the + new trip. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_create_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateTripRequest( + parent="parent_value", + trip_id="trip_id_value", + ) + + # Make the request + response = client.create_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.CreateTripRequest, dict]): + The request object. CreateTrip 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.CreateTripRequest): + request = trip_api.CreateTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_trip(self, + request: Optional[Union[trip_api.GetTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Get information about a single trip. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_get_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetTripRequest( + name="name_value", + ) + + # Make the request + response = client.get_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.GetTripRequest, dict]): + The request object. GetTrip 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.GetTripRequest): + request = trip_api.GetTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def report_billable_trip(self, + request: Optional[Union[trip_api.ReportBillableTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Report billable trip usage. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_report_billable_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.ReportBillableTripRequest( + name="name_value", + country_code="country_code_value", + ) + + # Make the request + client.report_billable_trip(request=request) + + Args: + request (Union[google.maps.fleetengine_v1.types.ReportBillableTripRequest, dict]): + The request object. ReportBillableTrip 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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, trip_api.ReportBillableTripRequest): + request = trip_api.ReportBillableTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report_billable_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def search_trips(self, + request: Optional[Union[trip_api.SearchTripsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchTripsPager: + r"""Get all the trips for a specific vehicle. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_search_trips(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchTripsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.search_trips(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.SearchTripsRequest, dict]): + The request object. SearchTrips 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsPager: + SearchTrips response message. + + 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, trip_api.SearchTripsRequest): + request = trip_api.SearchTripsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_trips] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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.SearchTripsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_trip(self, + request: Optional[Union[trip_api.UpdateTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Updates trip data. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_update_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateTripRequest( + name="name_value", + ) + + # Make the request + response = client.update_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.UpdateTripRequest, dict]): + The request object. UpdateTrip 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.UpdateTripRequest): + request = trip_api.UpdateTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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) -> "TripServiceClient": + 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__ = ( + "TripServiceClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py new file mode 100644 index 000000000000..8b5599f99cfa --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips + + +class SearchTripsPager: + """A pager for iterating through ``search_trips`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``trips`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchTrips`` requests and continue to iterate + through the ``trips`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., trip_api.SearchTripsResponse], + request: trip_api.SearchTripsRequest, + response: trip_api.SearchTripsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_v1.types.SearchTripsRequest): + The initial request object. + response (google.maps.fleetengine_v1.types.SearchTripsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = trip_api.SearchTripsRequest(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[trip_api.SearchTripsResponse]: + 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[trips.Trip]: + for page in self.pages: + yield from page.trips + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchTripsAsyncPager: + """A pager for iterating through ``search_trips`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``trips`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchTrips`` requests and continue to iterate + through the ``trips`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` + attributes are available on the 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[trip_api.SearchTripsResponse]], + request: trip_api.SearchTripsRequest, + response: trip_api.SearchTripsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_v1.types.SearchTripsRequest): + The initial request object. + response (google.maps.fleetengine_v1.types.SearchTripsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = trip_api.SearchTripsRequest(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[trip_api.SearchTripsResponse]: + 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[trips.Trip]: + async def async_generator(): + async for page in self.pages: + for response in page.trips: + 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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst new file mode 100644 index 000000000000..97675873407f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TripServiceTransport` is the ABC for all transports. +- public child `TripServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TripServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTripServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TripServiceRestTransport` 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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py new file mode 100644 index 000000000000..89de6013d759 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 TripServiceTransport +from .grpc import TripServiceGrpcTransport +from .grpc_asyncio import TripServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TripServiceTransport]] +_transport_registry['grpc'] = TripServiceGrpcTransport +_transport_registry['grpc_asyncio'] = TripServiceGrpcAsyncIOTransport + +__all__ = ( + 'TripServiceTransport', + 'TripServiceGrpcTransport', + 'TripServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py new file mode 100644 index 000000000000..71595601d903 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.maps.fleetengine_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.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class TripServiceTransport(abc.ABC): + """Abstract transport class for TripService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_trip: gapic_v1.method.wrap_method( + self.create_trip, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_trip: gapic_v1.method.wrap_method( + self.get_trip, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.report_billable_trip: gapic_v1.method.wrap_method( + self.report_billable_trip, + default_timeout=None, + client_info=client_info, + ), + self.search_trips: gapic_v1.method.wrap_method( + self.search_trips, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_trip: gapic_v1.method.wrap_method( + self.update_trip, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.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_trip(self) -> Callable[ + [trip_api.CreateTripRequest], + Union[ + trips.Trip, + Awaitable[trips.Trip] + ]]: + raise NotImplementedError() + + @property + def get_trip(self) -> Callable[ + [trip_api.GetTripRequest], + Union[ + trips.Trip, + Awaitable[trips.Trip] + ]]: + raise NotImplementedError() + + @property + def report_billable_trip(self) -> Callable[ + [trip_api.ReportBillableTripRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def search_trips(self) -> Callable[ + [trip_api.SearchTripsRequest], + Union[ + trip_api.SearchTripsResponse, + Awaitable[trip_api.SearchTripsResponse] + ]]: + raise NotImplementedError() + + @property + def update_trip(self) -> Callable[ + [trip_api.UpdateTripRequest], + Union[ + trips.Trip, + Awaitable[trips.Trip] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'TripServiceTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py new file mode 100644 index 000000000000..0c20dd7934fc --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py @@ -0,0 +1,377 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.maps.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +from google.protobuf import empty_pb2 # type: ignore +from .base import TripServiceTransport, DEFAULT_CLIENT_INFO + + +class TripServiceGrpcTransport(TripServiceTransport): + """gRPC backend transport for TripService. + + Trip management service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'fleetengine.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: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'fleetengine.googleapis.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_trip(self) -> Callable[ + [trip_api.CreateTripRequest], + trips.Trip]: + r"""Return a callable for the create trip method over gRPC. + + Creates a trip in the Fleet Engine and returns the + new trip. + + Returns: + Callable[[~.CreateTripRequest], + ~.Trip]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_trip' not in self._stubs: + self._stubs['create_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/CreateTrip', + request_serializer=trip_api.CreateTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['create_trip'] + + @property + def get_trip(self) -> Callable[ + [trip_api.GetTripRequest], + trips.Trip]: + r"""Return a callable for the get trip method over gRPC. + + Get information about a single trip. + + Returns: + Callable[[~.GetTripRequest], + ~.Trip]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_trip' not in self._stubs: + self._stubs['get_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/GetTrip', + request_serializer=trip_api.GetTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['get_trip'] + + @property + def report_billable_trip(self) -> Callable[ + [trip_api.ReportBillableTripRequest], + empty_pb2.Empty]: + r"""Return a callable for the report billable trip method over gRPC. + + Report billable trip usage. + + Returns: + Callable[[~.ReportBillableTripRequest], + ~.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 'report_billable_trip' not in self._stubs: + self._stubs['report_billable_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/ReportBillableTrip', + request_serializer=trip_api.ReportBillableTripRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['report_billable_trip'] + + @property + def search_trips(self) -> Callable[ + [trip_api.SearchTripsRequest], + trip_api.SearchTripsResponse]: + r"""Return a callable for the search trips method over gRPC. + + Get all the trips for a specific vehicle. + + Returns: + Callable[[~.SearchTripsRequest], + ~.SearchTripsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_trips' not in self._stubs: + self._stubs['search_trips'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/SearchTrips', + request_serializer=trip_api.SearchTripsRequest.serialize, + response_deserializer=trip_api.SearchTripsResponse.deserialize, + ) + return self._stubs['search_trips'] + + @property + def update_trip(self) -> Callable[ + [trip_api.UpdateTripRequest], + trips.Trip]: + r"""Return a callable for the update trip method over gRPC. + + Updates trip data. + + Returns: + Callable[[~.UpdateTripRequest], + ~.Trip]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_trip' not in self._stubs: + self._stubs['update_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/UpdateTrip', + request_serializer=trip_api.UpdateTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['update_trip'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'TripServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..b7b838015e6d --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py @@ -0,0 +1,454 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +from google.protobuf import empty_pb2 # type: ignore +from .base import TripServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import TripServiceGrpcTransport + + +class TripServiceGrpcAsyncIOTransport(TripServiceTransport): + """gRPC AsyncIO backend transport for TripService. + + Trip management service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'fleetengine.googleapis.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 = 'fleetengine.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: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_trip(self) -> Callable[ + [trip_api.CreateTripRequest], + Awaitable[trips.Trip]]: + r"""Return a callable for the create trip method over gRPC. + + Creates a trip in the Fleet Engine and returns the + new trip. + + Returns: + Callable[[~.CreateTripRequest], + Awaitable[~.Trip]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_trip' not in self._stubs: + self._stubs['create_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/CreateTrip', + request_serializer=trip_api.CreateTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['create_trip'] + + @property + def get_trip(self) -> Callable[ + [trip_api.GetTripRequest], + Awaitable[trips.Trip]]: + r"""Return a callable for the get trip method over gRPC. + + Get information about a single trip. + + Returns: + Callable[[~.GetTripRequest], + Awaitable[~.Trip]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_trip' not in self._stubs: + self._stubs['get_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/GetTrip', + request_serializer=trip_api.GetTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['get_trip'] + + @property + def report_billable_trip(self) -> Callable[ + [trip_api.ReportBillableTripRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the report billable trip method over gRPC. + + Report billable trip usage. + + Returns: + Callable[[~.ReportBillableTripRequest], + 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 'report_billable_trip' not in self._stubs: + self._stubs['report_billable_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/ReportBillableTrip', + request_serializer=trip_api.ReportBillableTripRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['report_billable_trip'] + + @property + def search_trips(self) -> Callable[ + [trip_api.SearchTripsRequest], + Awaitable[trip_api.SearchTripsResponse]]: + r"""Return a callable for the search trips method over gRPC. + + Get all the trips for a specific vehicle. + + Returns: + Callable[[~.SearchTripsRequest], + Awaitable[~.SearchTripsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_trips' not in self._stubs: + self._stubs['search_trips'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/SearchTrips', + request_serializer=trip_api.SearchTripsRequest.serialize, + response_deserializer=trip_api.SearchTripsResponse.deserialize, + ) + return self._stubs['search_trips'] + + @property + def update_trip(self) -> Callable[ + [trip_api.UpdateTripRequest], + Awaitable[trips.Trip]]: + r"""Return a callable for the update trip method over gRPC. + + Updates trip data. + + Returns: + Callable[[~.UpdateTripRequest], + Awaitable[~.Trip]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_trip' not in self._stubs: + self._stubs['update_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/UpdateTrip', + request_serializer=trip_api.UpdateTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['update_trip'] + + 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_trip: self._wrap_method( + self.create_trip, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_trip: self._wrap_method( + self.get_trip, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.report_billable_trip: self._wrap_method( + self.report_billable_trip, + default_timeout=None, + client_info=client_info, + ), + self.search_trips: self._wrap_method( + self.search_trips, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_trip: self._wrap_method( + self.update_trip, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'TripServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py new file mode 100644 index 000000000000..fc6cb2c02da7 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_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 VehicleServiceClient +from .async_client import VehicleServiceAsyncClient + +__all__ = ( + 'VehicleServiceClient', + 'VehicleServiceAsyncClient', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py new file mode 100644 index 000000000000..f5dcf834487a --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py @@ -0,0 +1,827 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.maps.fleetengine_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.fleetengine_v1.services.vehicle_service import pagers +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import VehicleServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VehicleServiceGrpcAsyncIOTransport +from .client import VehicleServiceClient + + +class VehicleServiceAsyncClient: + """Vehicle management service.""" + + _client: VehicleServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = VehicleServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = VehicleServiceClient._DEFAULT_UNIVERSE + + vehicle_path = staticmethod(VehicleServiceClient.vehicle_path) + parse_vehicle_path = staticmethod(VehicleServiceClient.parse_vehicle_path) + common_billing_account_path = staticmethod(VehicleServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VehicleServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VehicleServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(VehicleServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(VehicleServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(VehicleServiceClient.parse_common_organization_path) + common_project_path = staticmethod(VehicleServiceClient.common_project_path) + parse_common_project_path = staticmethod(VehicleServiceClient.parse_common_project_path) + common_location_path = staticmethod(VehicleServiceClient.common_location_path) + parse_common_location_path = staticmethod(VehicleServiceClient.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: + VehicleServiceAsyncClient: The constructed client. + """ + return VehicleServiceClient.from_service_account_info.__func__(VehicleServiceAsyncClient, 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: + VehicleServiceAsyncClient: The constructed client. + """ + return VehicleServiceClient.from_service_account_file.__func__(VehicleServiceAsyncClient, 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 VehicleServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> VehicleServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VehicleServiceTransport: 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 = VehicleServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, VehicleServiceTransport, Callable[..., VehicleServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the vehicle 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,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): + 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 VehicleServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = VehicleServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_vehicle(self, + request: Optional[Union[vehicle_api.CreateVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Instantiates a new vehicle associated with an on-demand + rideshare or deliveries provider. Each ``Vehicle`` must have a + unique vehicle ID. + + The following ``Vehicle`` fields are required when creating a + ``Vehicle``: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + The following ``Vehicle`` fields are ignored when creating a + ``Vehicle``: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_create_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateVehicleRequest( + parent="parent_value", + vehicle_id="vehicle_id_value", + ) + + # Make the request + response = await client.create_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.CreateVehicleRequest, dict]]): + The request object. ``CreateVehicle`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.CreateVehicleRequest): + request = vehicle_api.CreateVehicleRequest(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_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_vehicle(self, + request: Optional[Union[vehicle_api.GetVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Returns a vehicle from the Fleet Engine. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_get_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.GetVehicleRequest, dict]]): + The request object. ``GetVehicle`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.GetVehicleRequest): + request = vehicle_api.GetVehicleRequest(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_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_vehicle(self, + request: Optional[Union[vehicle_api.UpdateVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Writes updated vehicle data to the Fleet Engine. + + When updating a ``Vehicle``, the following fields cannot be + updated since they are managed by the server: + + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment_version`` + - ``waypoints_version`` + + The vehicle ``name`` also cannot be updated. + + If the ``attributes`` field is updated, **all** the vehicle's + attributes are replaced with the attributes provided in the + request. If you want to update only some attributes, see the + ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` + field can be updated, but must contain all the waypoints + currently on the vehicle, and no other waypoints. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_update_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.update_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.UpdateVehicleRequest, dict]]): + The request object. \`UpdateVehicle 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.UpdateVehicleRequest): + request = vehicle_api.UpdateVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_vehicle_attributes(self, + request: Optional[Union[vehicle_api.UpdateVehicleAttributesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicle_api.UpdateVehicleAttributesResponse: + r"""Partially updates a vehicle's attributes. Only the attributes + mentioned in the request will be updated, other attributes will + NOT be altered. Note: this is different in ``UpdateVehicle``, + where the whole ``attributes`` field will be replaced by the one + in ``UpdateVehicleRequest``, attributes not in the request would + be removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_update_vehicle_attributes(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + attributes = fleetengine_v1.VehicleAttribute() + attributes.string_value = "string_value_value" + + request = fleetengine_v1.UpdateVehicleAttributesRequest( + name="name_value", + attributes=attributes, + ) + + # Make the request + response = await client.update_vehicle_attributes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest, dict]]): + The request object. ``UpdateVehicleAttributes`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse: + UpdateVehicleAttributes 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, vehicle_api.UpdateVehicleAttributesRequest): + request = vehicle_api.UpdateVehicleAttributesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_vehicle_attributes] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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_vehicles(self, + request: Optional[Union[vehicle_api.ListVehiclesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVehiclesAsyncPager: + r"""Returns a paginated list of vehicles associated with + a provider that match the request options. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_list_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.ListVehiclesRequest( + parent="parent_value", + vehicle_type_categories=['PEDESTRIAN'], + ) + + # Make the request + page_result = client.list_vehicles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.ListVehiclesRequest, dict]]): + The request object. ``ListVehicles`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesAsyncPager: + ListVehicles response message. + + 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, vehicle_api.ListVehiclesRequest): + request = vehicle_api.ListVehiclesRequest(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_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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.ListVehiclesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_vehicles(self, + request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicle_api.SearchVehiclesResponse: + r"""Returns a list of vehicles that match the request + options. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + async def sample_search_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchVehiclesRequest( + parent="parent_value", + pickup_radius_meters=2146, + count=553, + minimum_capacity=1705, + trip_types=['EXCLUSIVE'], + order_by="COST", + ) + + # Make the request + response = await client.search_vehicles(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]]): + The request object. ``SearchVehicles`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.SearchVehiclesResponse: + SearchVehicles 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, vehicle_api.SearchVehiclesRequest): + request = vehicle_api.SearchVehiclesRequest(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_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._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) -> "VehicleServiceAsyncClient": + 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__ = ( + "VehicleServiceAsyncClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py new file mode 100644 index 000000000000..7e670b5a6083 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py @@ -0,0 +1,1182 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.maps.fleetengine_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 + +from google.maps.fleetengine_v1.services.vehicle_service import pagers +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import VehicleServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VehicleServiceGrpcTransport +from .transports.grpc_asyncio import VehicleServiceGrpcAsyncIOTransport + + +class VehicleServiceClientMeta(type): + """Metaclass for the VehicleService 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[VehicleServiceTransport]] + _transport_registry["grpc"] = VehicleServiceGrpcTransport + _transport_registry["grpc_asyncio"] = VehicleServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[VehicleServiceTransport]: + """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 VehicleServiceClient(metaclass=VehicleServiceClientMeta): + """Vehicle management service.""" + + @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 = "fleetengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: + VehicleServiceClient: 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: + VehicleServiceClient: 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) -> VehicleServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VehicleServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def vehicle_path(provider: str,vehicle: str,) -> str: + """Returns a fully-qualified vehicle string.""" + return "providers/{provider}/vehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) + + @staticmethod + def parse_vehicle_path(path: str) -> Dict[str,str]: + """Parses a vehicle path into its component segments.""" + m = re.match(r"^providers/(?P.+?)/vehicles/(?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 = VehicleServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = VehicleServiceClient._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 = VehicleServiceClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = VehicleServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + VehicleServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, VehicleServiceTransport, Callable[..., VehicleServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the vehicle 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,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): + 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 VehicleServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = VehicleServiceClient._read_environment_variables() + self._client_cert_source = VehicleServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = VehicleServiceClient._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 + + 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, VehicleServiceTransport) + if transport_provided: + # transport is a VehicleServiceTransport 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(VehicleServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + VehicleServiceClient._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[VehicleServiceTransport], Callable[..., VehicleServiceTransport]] = ( + VehicleServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., VehicleServiceTransport], 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, + ) + + def create_vehicle(self, + request: Optional[Union[vehicle_api.CreateVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Instantiates a new vehicle associated with an on-demand + rideshare or deliveries provider. Each ``Vehicle`` must have a + unique vehicle ID. + + The following ``Vehicle`` fields are required when creating a + ``Vehicle``: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + The following ``Vehicle`` fields are ignored when creating a + ``Vehicle``: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_create_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateVehicleRequest( + parent="parent_value", + vehicle_id="vehicle_id_value", + ) + + # Make the request + response = client.create_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.CreateVehicleRequest, dict]): + The request object. ``CreateVehicle`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.CreateVehicleRequest): + request = vehicle_api.CreateVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_vehicle(self, + request: Optional[Union[vehicle_api.GetVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Returns a vehicle from the Fleet Engine. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_get_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.get_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.GetVehicleRequest, dict]): + The request object. ``GetVehicle`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.GetVehicleRequest): + request = vehicle_api.GetVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_vehicle(self, + request: Optional[Union[vehicle_api.UpdateVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Writes updated vehicle data to the Fleet Engine. + + When updating a ``Vehicle``, the following fields cannot be + updated since they are managed by the server: + + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment_version`` + - ``waypoints_version`` + + The vehicle ``name`` also cannot be updated. + + If the ``attributes`` field is updated, **all** the vehicle's + attributes are replaced with the attributes provided in the + request. If you want to update only some attributes, see the + ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` + field can be updated, but must contain all the waypoints + currently on the vehicle, and no other waypoints. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_update_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.update_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.UpdateVehicleRequest, dict]): + The request object. \`UpdateVehicle 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.UpdateVehicleRequest): + request = vehicle_api.UpdateVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_vehicle_attributes(self, + request: Optional[Union[vehicle_api.UpdateVehicleAttributesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicle_api.UpdateVehicleAttributesResponse: + r"""Partially updates a vehicle's attributes. Only the attributes + mentioned in the request will be updated, other attributes will + NOT be altered. Note: this is different in ``UpdateVehicle``, + where the whole ``attributes`` field will be replaced by the one + in ``UpdateVehicleRequest``, attributes not in the request would + be removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_update_vehicle_attributes(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + attributes = fleetengine_v1.VehicleAttribute() + attributes.string_value = "string_value_value" + + request = fleetengine_v1.UpdateVehicleAttributesRequest( + name="name_value", + attributes=attributes, + ) + + # Make the request + response = client.update_vehicle_attributes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest, dict]): + The request object. ``UpdateVehicleAttributes`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse: + UpdateVehicleAttributes 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, vehicle_api.UpdateVehicleAttributesRequest): + request = vehicle_api.UpdateVehicleAttributesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_vehicle_attributes] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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_vehicles(self, + request: Optional[Union[vehicle_api.ListVehiclesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVehiclesPager: + r"""Returns a paginated list of vehicles associated with + a provider that match the request options. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_list_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.ListVehiclesRequest( + parent="parent_value", + vehicle_type_categories=['PEDESTRIAN'], + ) + + # Make the request + page_result = client.list_vehicles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.ListVehiclesRequest, dict]): + The request object. ``ListVehicles`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesPager: + ListVehicles response message. + + 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, vehicle_api.ListVehiclesRequest): + request = vehicle_api.ListVehiclesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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.ListVehiclesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_vehicles(self, + request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicle_api.SearchVehiclesResponse: + r"""Returns a list of vehicles that match the request + options. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 fleetengine_v1 + + def sample_search_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchVehiclesRequest( + parent="parent_value", + pickup_radius_meters=2146, + count=553, + minimum_capacity=1705, + trip_types=['EXCLUSIVE'], + order_by="COST", + ) + + # Make the request + response = client.search_vehicles(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]): + The request object. ``SearchVehicles`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.fleetengine_v1.types.SearchVehiclesResponse: + SearchVehicles 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, vehicle_api.SearchVehiclesRequest): + request = vehicle_api.SearchVehiclesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe 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) -> "VehicleServiceClient": + 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__ = ( + "VehicleServiceClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py new file mode 100644 index 000000000000..a37cce62d28f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles + + +class ListVehiclesPager: + """A pager for iterating through ``list_vehicles`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``vehicles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVehicles`` requests and continue to iterate + through the ``vehicles`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., vehicle_api.ListVehiclesResponse], + request: vehicle_api.ListVehiclesRequest, + response: vehicle_api.ListVehiclesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_v1.types.ListVehiclesRequest): + The initial request object. + response (google.maps.fleetengine_v1.types.ListVehiclesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = vehicle_api.ListVehiclesRequest(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[vehicle_api.ListVehiclesResponse]: + 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[vehicles.Vehicle]: + for page in self.pages: + yield from page.vehicles + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVehiclesAsyncPager: + """A pager for iterating through ``list_vehicles`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``vehicles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVehicles`` requests and continue to iterate + through the ``vehicles`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` + attributes are available on the 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[vehicle_api.ListVehiclesResponse]], + request: vehicle_api.ListVehiclesRequest, + response: vehicle_api.ListVehiclesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_v1.types.ListVehiclesRequest): + The initial request object. + response (google.maps.fleetengine_v1.types.ListVehiclesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = vehicle_api.ListVehiclesRequest(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[vehicle_api.ListVehiclesResponse]: + 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[vehicles.Vehicle]: + async def async_generator(): + async for page in self.pages: + for response in page.vehicles: + 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-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst new file mode 100644 index 000000000000..cab31a918dfd --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`VehicleServiceTransport` is the ABC for all transports. +- public child `VehicleServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `VehicleServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseVehicleServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `VehicleServiceRestTransport` 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-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py new file mode 100644 index 000000000000..6c5e9251815c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 VehicleServiceTransport +from .grpc import VehicleServiceGrpcTransport +from .grpc_asyncio import VehicleServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VehicleServiceTransport]] +_transport_registry['grpc'] = VehicleServiceGrpcTransport +_transport_registry['grpc_asyncio'] = VehicleServiceGrpcAsyncIOTransport + +__all__ = ( + 'VehicleServiceTransport', + 'VehicleServiceGrpcTransport', + 'VehicleServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py new file mode 100644 index 000000000000..7f3a046bb15d --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/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 abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.maps.fleetengine_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.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class VehicleServiceTransport(abc.ABC): + """Abstract transport class for VehicleService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_vehicle: gapic_v1.method.wrap_method( + self.create_vehicle, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_vehicle: gapic_v1.method.wrap_method( + self.get_vehicle, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle: gapic_v1.method.wrap_method( + self.update_vehicle, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle_attributes: gapic_v1.method.wrap_method( + self.update_vehicle_attributes, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.list_vehicles: gapic_v1.method.wrap_method( + self.list_vehicles, + default_timeout=None, + client_info=client_info, + ), + self.search_vehicles: gapic_v1.method.wrap_method( + self.search_vehicles, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.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_vehicle(self) -> Callable[ + [vehicle_api.CreateVehicleRequest], + Union[ + vehicles.Vehicle, + Awaitable[vehicles.Vehicle] + ]]: + raise NotImplementedError() + + @property + def get_vehicle(self) -> Callable[ + [vehicle_api.GetVehicleRequest], + Union[ + vehicles.Vehicle, + Awaitable[vehicles.Vehicle] + ]]: + raise NotImplementedError() + + @property + def update_vehicle(self) -> Callable[ + [vehicle_api.UpdateVehicleRequest], + Union[ + vehicles.Vehicle, + Awaitable[vehicles.Vehicle] + ]]: + raise NotImplementedError() + + @property + def update_vehicle_attributes(self) -> Callable[ + [vehicle_api.UpdateVehicleAttributesRequest], + Union[ + vehicle_api.UpdateVehicleAttributesResponse, + Awaitable[vehicle_api.UpdateVehicleAttributesResponse] + ]]: + raise NotImplementedError() + + @property + def list_vehicles(self) -> Callable[ + [vehicle_api.ListVehiclesRequest], + Union[ + vehicle_api.ListVehiclesResponse, + Awaitable[vehicle_api.ListVehiclesResponse] + ]]: + raise NotImplementedError() + + @property + def search_vehicles(self) -> Callable[ + [vehicle_api.SearchVehiclesRequest], + Union[ + vehicle_api.SearchVehiclesResponse, + Awaitable[vehicle_api.SearchVehiclesResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'VehicleServiceTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py new file mode 100644 index 000000000000..827cc20bd1dd --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.maps.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from .base import VehicleServiceTransport, DEFAULT_CLIENT_INFO + + +class VehicleServiceGrpcTransport(VehicleServiceTransport): + """gRPC backend transport for VehicleService. + + Vehicle management service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'fleetengine.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: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'fleetengine.googleapis.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_vehicle(self) -> Callable[ + [vehicle_api.CreateVehicleRequest], + vehicles.Vehicle]: + r"""Return a callable for the create vehicle method over gRPC. + + Instantiates a new vehicle associated with an on-demand + rideshare or deliveries provider. Each ``Vehicle`` must have a + unique vehicle ID. + + The following ``Vehicle`` fields are required when creating a + ``Vehicle``: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + The following ``Vehicle`` fields are ignored when creating a + ``Vehicle``: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + + Returns: + Callable[[~.CreateVehicleRequest], + ~.Vehicle]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicle' not in self._stubs: + self._stubs['create_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/CreateVehicle', + request_serializer=vehicle_api.CreateVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['create_vehicle'] + + @property + def get_vehicle(self) -> Callable[ + [vehicle_api.GetVehicleRequest], + vehicles.Vehicle]: + r"""Return a callable for the get vehicle method over gRPC. + + Returns a vehicle from the Fleet Engine. + + Returns: + Callable[[~.GetVehicleRequest], + ~.Vehicle]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicle' not in self._stubs: + self._stubs['get_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/GetVehicle', + request_serializer=vehicle_api.GetVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['get_vehicle'] + + @property + def update_vehicle(self) -> Callable[ + [vehicle_api.UpdateVehicleRequest], + vehicles.Vehicle]: + r"""Return a callable for the update vehicle method over gRPC. + + Writes updated vehicle data to the Fleet Engine. + + When updating a ``Vehicle``, the following fields cannot be + updated since they are managed by the server: + + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment_version`` + - ``waypoints_version`` + + The vehicle ``name`` also cannot be updated. + + If the ``attributes`` field is updated, **all** the vehicle's + attributes are replaced with the attributes provided in the + request. If you want to update only some attributes, see the + ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` + field can be updated, but must contain all the waypoints + currently on the vehicle, and no other waypoints. + + Returns: + Callable[[~.UpdateVehicleRequest], + ~.Vehicle]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicle' not in self._stubs: + self._stubs['update_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/UpdateVehicle', + request_serializer=vehicle_api.UpdateVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['update_vehicle'] + + @property + def update_vehicle_attributes(self) -> Callable[ + [vehicle_api.UpdateVehicleAttributesRequest], + vehicle_api.UpdateVehicleAttributesResponse]: + r"""Return a callable for the update vehicle attributes method over gRPC. + + Partially updates a vehicle's attributes. Only the attributes + mentioned in the request will be updated, other attributes will + NOT be altered. Note: this is different in ``UpdateVehicle``, + where the whole ``attributes`` field will be replaced by the one + in ``UpdateVehicleRequest``, attributes not in the request would + be removed. + + Returns: + Callable[[~.UpdateVehicleAttributesRequest], + ~.UpdateVehicleAttributesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicle_attributes' not in self._stubs: + self._stubs['update_vehicle_attributes'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/UpdateVehicleAttributes', + request_serializer=vehicle_api.UpdateVehicleAttributesRequest.serialize, + response_deserializer=vehicle_api.UpdateVehicleAttributesResponse.deserialize, + ) + return self._stubs['update_vehicle_attributes'] + + @property + def list_vehicles(self) -> Callable[ + [vehicle_api.ListVehiclesRequest], + vehicle_api.ListVehiclesResponse]: + r"""Return a callable for the list vehicles method over gRPC. + + Returns a paginated list of vehicles associated with + a provider that match the request options. + + Returns: + Callable[[~.ListVehiclesRequest], + ~.ListVehiclesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicles' not in self._stubs: + self._stubs['list_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/ListVehicles', + request_serializer=vehicle_api.ListVehiclesRequest.serialize, + response_deserializer=vehicle_api.ListVehiclesResponse.deserialize, + ) + return self._stubs['list_vehicles'] + + @property + def search_vehicles(self) -> Callable[ + [vehicle_api.SearchVehiclesRequest], + vehicle_api.SearchVehiclesResponse]: + r"""Return a callable for the search vehicles method over gRPC. + + Returns a list of vehicles that match the request + options. + + Returns: + Callable[[~.SearchVehiclesRequest], + ~.SearchVehiclesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicles' not in self._stubs: + self._stubs['search_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/SearchVehicles', + request_serializer=vehicle_api.SearchVehiclesRequest.serialize, + response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, + ) + return self._stubs['search_vehicles'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'VehicleServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..952dd0c816f8 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py @@ -0,0 +1,546 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from .base import VehicleServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import VehicleServiceGrpcTransport + + +class VehicleServiceGrpcAsyncIOTransport(VehicleServiceTransport): + """gRPC AsyncIO backend transport for VehicleService. + + Vehicle management service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'fleetengine.googleapis.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 = 'fleetengine.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: 'fleetengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_vehicle(self) -> Callable[ + [vehicle_api.CreateVehicleRequest], + Awaitable[vehicles.Vehicle]]: + r"""Return a callable for the create vehicle method over gRPC. + + Instantiates a new vehicle associated with an on-demand + rideshare or deliveries provider. Each ``Vehicle`` must have a + unique vehicle ID. + + The following ``Vehicle`` fields are required when creating a + ``Vehicle``: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + The following ``Vehicle`` fields are ignored when creating a + ``Vehicle``: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + + Returns: + Callable[[~.CreateVehicleRequest], + Awaitable[~.Vehicle]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicle' not in self._stubs: + self._stubs['create_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/CreateVehicle', + request_serializer=vehicle_api.CreateVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['create_vehicle'] + + @property + def get_vehicle(self) -> Callable[ + [vehicle_api.GetVehicleRequest], + Awaitable[vehicles.Vehicle]]: + r"""Return a callable for the get vehicle method over gRPC. + + Returns a vehicle from the Fleet Engine. + + Returns: + Callable[[~.GetVehicleRequest], + Awaitable[~.Vehicle]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicle' not in self._stubs: + self._stubs['get_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/GetVehicle', + request_serializer=vehicle_api.GetVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['get_vehicle'] + + @property + def update_vehicle(self) -> Callable[ + [vehicle_api.UpdateVehicleRequest], + Awaitable[vehicles.Vehicle]]: + r"""Return a callable for the update vehicle method over gRPC. + + Writes updated vehicle data to the Fleet Engine. + + When updating a ``Vehicle``, the following fields cannot be + updated since they are managed by the server: + + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment_version`` + - ``waypoints_version`` + + The vehicle ``name`` also cannot be updated. + + If the ``attributes`` field is updated, **all** the vehicle's + attributes are replaced with the attributes provided in the + request. If you want to update only some attributes, see the + ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` + field can be updated, but must contain all the waypoints + currently on the vehicle, and no other waypoints. + + Returns: + Callable[[~.UpdateVehicleRequest], + Awaitable[~.Vehicle]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicle' not in self._stubs: + self._stubs['update_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/UpdateVehicle', + request_serializer=vehicle_api.UpdateVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['update_vehicle'] + + @property + def update_vehicle_attributes(self) -> Callable[ + [vehicle_api.UpdateVehicleAttributesRequest], + Awaitable[vehicle_api.UpdateVehicleAttributesResponse]]: + r"""Return a callable for the update vehicle attributes method over gRPC. + + Partially updates a vehicle's attributes. Only the attributes + mentioned in the request will be updated, other attributes will + NOT be altered. Note: this is different in ``UpdateVehicle``, + where the whole ``attributes`` field will be replaced by the one + in ``UpdateVehicleRequest``, attributes not in the request would + be removed. + + Returns: + Callable[[~.UpdateVehicleAttributesRequest], + Awaitable[~.UpdateVehicleAttributesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicle_attributes' not in self._stubs: + self._stubs['update_vehicle_attributes'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/UpdateVehicleAttributes', + request_serializer=vehicle_api.UpdateVehicleAttributesRequest.serialize, + response_deserializer=vehicle_api.UpdateVehicleAttributesResponse.deserialize, + ) + return self._stubs['update_vehicle_attributes'] + + @property + def list_vehicles(self) -> Callable[ + [vehicle_api.ListVehiclesRequest], + Awaitable[vehicle_api.ListVehiclesResponse]]: + r"""Return a callable for the list vehicles method over gRPC. + + Returns a paginated list of vehicles associated with + a provider that match the request options. + + Returns: + Callable[[~.ListVehiclesRequest], + Awaitable[~.ListVehiclesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicles' not in self._stubs: + self._stubs['list_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/ListVehicles', + request_serializer=vehicle_api.ListVehiclesRequest.serialize, + response_deserializer=vehicle_api.ListVehiclesResponse.deserialize, + ) + return self._stubs['list_vehicles'] + + @property + def search_vehicles(self) -> Callable[ + [vehicle_api.SearchVehiclesRequest], + Awaitable[vehicle_api.SearchVehiclesResponse]]: + r"""Return a callable for the search vehicles method over gRPC. + + Returns a list of vehicles that match the request + options. + + Returns: + Callable[[~.SearchVehiclesRequest], + Awaitable[~.SearchVehiclesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_vehicles' not in self._stubs: + self._stubs['search_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/SearchVehicles', + request_serializer=vehicle_api.SearchVehiclesRequest.serialize, + response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, + ) + return self._stubs['search_vehicles'] + + 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_vehicle: self._wrap_method( + self.create_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_vehicle: self._wrap_method( + self.get_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle: self._wrap_method( + self.update_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle_attributes: self._wrap_method( + self.update_vehicle_attributes, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.list_vehicles: self._wrap_method( + self.list_vehicles, + default_timeout=None, + client_info=client_info, + ), + self.search_vehicles: self._wrap_method( + self.search_vehicles, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'VehicleServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py new file mode 100644 index 000000000000..cba18024bd88 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .fleetengine import ( + TerminalLocation, + TerminalPointId, + TripWaypoint, + VehicleAttribute, + VehicleLocation, + LocationSensor, + NavigationStatus, + PolylineFormatType, + TripType, + WaypointType, +) +from .header import ( + RequestHeader, +) +from .traffic import ( + ConsumableTrafficPolyline, + SpeedReadingInterval, +) +from .trip_api import ( + CreateTripRequest, + GetTripRequest, + ReportBillableTripRequest, + SearchTripsRequest, + SearchTripsResponse, + UpdateTripRequest, +) +from .trips import ( + StopLocation, + Trip, + BillingPlatformIdentifier, + TripStatus, + TripView, +) +from .vehicle_api import ( + CreateVehicleRequest, + GetVehicleRequest, + ListVehiclesRequest, + ListVehiclesResponse, + SearchVehiclesRequest, + SearchVehiclesResponse, + UpdateVehicleAttributesRequest, + UpdateVehicleAttributesResponse, + UpdateVehicleRequest, + VehicleAttributeList, + VehicleMatch, + Waypoint, +) +from .vehicles import ( + BatteryInfo, + DeviceSettings, + LicensePlate, + TrafficPolylineData, + Vehicle, + VisualTrafficReportPolylineRendering, + BatteryStatus, + LocationPowerSaveMode, + PowerSource, + VehicleState, +) + +__all__ = ( + 'TerminalLocation', + 'TerminalPointId', + 'TripWaypoint', + 'VehicleAttribute', + 'VehicleLocation', + 'LocationSensor', + 'NavigationStatus', + 'PolylineFormatType', + 'TripType', + 'WaypointType', + 'RequestHeader', + 'ConsumableTrafficPolyline', + 'SpeedReadingInterval', + 'CreateTripRequest', + 'GetTripRequest', + 'ReportBillableTripRequest', + 'SearchTripsRequest', + 'SearchTripsResponse', + 'UpdateTripRequest', + 'StopLocation', + 'Trip', + 'BillingPlatformIdentifier', + 'TripStatus', + 'TripView', + 'CreateVehicleRequest', + 'GetVehicleRequest', + 'ListVehiclesRequest', + 'ListVehiclesResponse', + 'SearchVehiclesRequest', + 'SearchVehiclesResponse', + 'UpdateVehicleAttributesRequest', + 'UpdateVehicleAttributesResponse', + 'UpdateVehicleRequest', + 'VehicleAttributeList', + 'VehicleMatch', + 'Waypoint', + 'BatteryInfo', + 'DeviceSettings', + 'LicensePlate', + 'TrafficPolylineData', + 'Vehicle', + 'VisualTrafficReportPolylineRendering', + 'BatteryStatus', + 'LocationPowerSaveMode', + 'PowerSource', + 'VehicleState', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py new file mode 100644 index 000000000000..95fe3f592984 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py @@ -0,0 +1,628 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.fleetengine_v1.types import traffic +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.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'TripType', + 'WaypointType', + 'PolylineFormatType', + 'NavigationStatus', + 'LocationSensor', + 'TerminalPointId', + 'TerminalLocation', + 'TripWaypoint', + 'VehicleAttribute', + 'VehicleLocation', + }, +) + + +class TripType(proto.Enum): + r"""The type of a trip. + + Values: + UNKNOWN_TRIP_TYPE (0): + Default, used for unspecified or unrecognized + trip types. + SHARED (1): + The trip may share a vehicle with other + trips. + EXCLUSIVE (2): + The trip is exclusive to a vehicle. + """ + UNKNOWN_TRIP_TYPE = 0 + SHARED = 1 + EXCLUSIVE = 2 + + +class WaypointType(proto.Enum): + r"""The type of waypoint. + + Values: + UNKNOWN_WAYPOINT_TYPE (0): + Unknown or unspecified waypoint type. + PICKUP_WAYPOINT_TYPE (1): + Waypoints for picking up riders or items. + DROP_OFF_WAYPOINT_TYPE (2): + Waypoints for dropping off riders or items. + INTERMEDIATE_DESTINATION_WAYPOINT_TYPE (3): + Waypoints for intermediate destinations in a + multi-destination trip. + """ + UNKNOWN_WAYPOINT_TYPE = 0 + PICKUP_WAYPOINT_TYPE = 1 + DROP_OFF_WAYPOINT_TYPE = 2 + INTERMEDIATE_DESTINATION_WAYPOINT_TYPE = 3 + + +class PolylineFormatType(proto.Enum): + r"""The type of polyline format. + + Values: + UNKNOWN_FORMAT_TYPE (0): + The format is unspecified or unknown. + LAT_LNG_LIST_TYPE (1): + A list of ``google.type.LatLng``. + ENCODED_POLYLINE_TYPE (2): + A polyline encoded with a polyline + compression algorithm. Decoding is not yet + supported. + """ + UNKNOWN_FORMAT_TYPE = 0 + LAT_LNG_LIST_TYPE = 1 + ENCODED_POLYLINE_TYPE = 2 + + +class NavigationStatus(proto.Enum): + r"""The vehicle's navigation status. + + Values: + UNKNOWN_NAVIGATION_STATUS (0): + Unspecified navigation status. + NO_GUIDANCE (1): + The Driver app's navigation is in ``FREE_NAV`` mode. + ENROUTE_TO_DESTINATION (2): + Turn-by-turn navigation is available and the Driver app + navigation has entered ``GUIDED_NAV`` mode. + OFF_ROUTE (3): + The vehicle has gone off the suggested route. + ARRIVED_AT_DESTINATION (4): + The vehicle is within approximately 50m of + the destination. + """ + UNKNOWN_NAVIGATION_STATUS = 0 + NO_GUIDANCE = 1 + ENROUTE_TO_DESTINATION = 2 + OFF_ROUTE = 3 + ARRIVED_AT_DESTINATION = 4 + + +class LocationSensor(proto.Enum): + r"""The sensor or methodology used to determine the location. + + Values: + UNKNOWN_SENSOR (0): + The sensor is unspecified or unknown. + GPS (1): + GPS or Assisted GPS. + NETWORK (2): + Assisted GPS, cell tower ID, or WiFi access + point. + PASSIVE (3): + Cell tower ID or WiFi access point. + ROAD_SNAPPED_LOCATION_PROVIDER (4): + A location determined by the mobile device to + be the most likely road position. + CUSTOMER_SUPPLIED_LOCATION (5): + A customer-supplied location from an independent source. + Typically, this value is used for a location provided from + sources other than the mobile device running Driver SDK. If + the original source is described by one of the other enum + values, use that value. Locations marked + CUSTOMER_SUPPLIED_LOCATION are typically provided via a + Vehicle's ``last_location.supplemental_location_sensor``. + FLEET_ENGINE_LOCATION (6): + A location calculated by Fleet Engine based + on the signals available to it. Output only. + This value will be rejected if it is received in + a request. + FUSED_LOCATION_PROVIDER (100): + Android's Fused Location Provider. + CORE_LOCATION (200): + The location provider on Apple operating + systems. + """ + UNKNOWN_SENSOR = 0 + GPS = 1 + NETWORK = 2 + PASSIVE = 3 + ROAD_SNAPPED_LOCATION_PROVIDER = 4 + CUSTOMER_SUPPLIED_LOCATION = 5 + FLEET_ENGINE_LOCATION = 6 + FUSED_LOCATION_PROVIDER = 100 + CORE_LOCATION = 200 + + +class TerminalPointId(proto.Message): + r"""Deprecated: TerminalPoints are no longer supported in Fleet Engine. + Use ``TerminalLocation.point`` instead. + + 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_id (str): + Deprecated. + + This field is a member of `oneof`_ ``Id``. + generated_id (str): + Deprecated. + + This field is a member of `oneof`_ ``Id``. + value (str): + Deprecated. + """ + + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='Id', + ) + generated_id: str = proto.Field( + proto.STRING, + number=3, + oneof='Id', + ) + value: str = proto.Field( + proto.STRING, + number=4, + ) + + +class TerminalLocation(proto.Message): + r"""Describes the location of a waypoint. + + Attributes: + point (google.type.latlng_pb2.LatLng): + Required. Denotes the location of a trip + waypoint. + terminal_point_id (google.maps.fleetengine_v1.types.TerminalPointId): + Deprecated: Specify the ``point`` field instead. + access_point_id (str): + Deprecated: Specify the ``point`` field instead. + trip_id (str): + Deprecated. + terminal_location_type (google.maps.fleetengine_v1.types.WaypointType): + Deprecated: ``Vehicle.waypoint`` will have this data. + """ + + point: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + terminal_point_id: 'TerminalPointId' = proto.Field( + proto.MESSAGE, + number=2, + message='TerminalPointId', + ) + access_point_id: str = proto.Field( + proto.STRING, + number=3, + ) + trip_id: str = proto.Field( + proto.STRING, + number=4, + ) + terminal_location_type: 'WaypointType' = proto.Field( + proto.ENUM, + number=5, + enum='WaypointType', + ) + + +class TripWaypoint(proto.Message): + r"""Describes a stopping point on a vehicle's route or an ending + point on a vehicle's trip. + + Attributes: + location (google.maps.fleetengine_v1.types.TerminalLocation): + The location of this waypoint. + trip_id (str): + The trip associated with this waypoint. + waypoint_type (google.maps.fleetengine_v1.types.WaypointType): + The role this waypoint plays in this trip, + such as pickup or dropoff. + path_to_waypoint (MutableSequence[google.type.latlng_pb2.LatLng]): + The path from the previous waypoint to the + current waypoint. Undefined for the first + waypoint in a list. This field is only populated + when requested. + encoded_path_to_waypoint (str): + The encoded path from the previous waypoint + to the current waypoint. +

Note: This field is intended only for use by + the Driver SDK and Consumer SDK. Decoding is not + yet supported. + traffic_to_waypoint (google.maps.fleetengine_v1.types.ConsumableTrafficPolyline): + The traffic conditions along the path to this + waypoint. Note that traffic is only available + for Google Map Platform Rides and Deliveries + Solution customers. + distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The path distance from the previous waypoint + to the current waypoint. Undefined for the first + waypoint in a list. + eta (google.protobuf.timestamp_pb2.Timestamp): + The estimated time of arrival at this + waypoint. Undefined for the first waypoint in a + list. + duration (google.protobuf.duration_pb2.Duration): + The travel time from previous waypoint to + this point. Undefined for the first waypoint in + a list. + """ + + location: 'TerminalLocation' = proto.Field( + proto.MESSAGE, + number=1, + message='TerminalLocation', + ) + trip_id: str = proto.Field( + proto.STRING, + number=2, + ) + waypoint_type: 'WaypointType' = proto.Field( + proto.ENUM, + number=3, + enum='WaypointType', + ) + path_to_waypoint: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=latlng_pb2.LatLng, + ) + encoded_path_to_waypoint: str = proto.Field( + proto.STRING, + number=5, + ) + traffic_to_waypoint: traffic.ConsumableTrafficPolyline = proto.Field( + proto.MESSAGE, + number=10, + message=traffic.ConsumableTrafficPolyline, + ) + distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.Int32Value, + ) + eta: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class VehicleAttribute(proto.Message): + r"""Describes a vehicle attribute as a key-value pair. The + "key:value" string length cannot exceed 256 characters. + + 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: + key (str): + The attribute's key. Keys may not contain the + colon character (:). + value (str): + The attribute's value. + string_value (str): + String typed attribute value. + + Note: This is identical to the ``value`` field which will + eventually be deprecated. For create or update methods, + either field can be used, but it's strongly recommended to + use ``string_value``. If both ``string_value`` and ``value`` + are set, they must be identical or an error will be thrown. + Both fields are populated in responses. + + This field is a member of `oneof`_ ``vehicle_attribute_value``. + bool_value (bool): + Boolean typed attribute value. + + This field is a member of `oneof`_ ``vehicle_attribute_value``. + number_value (float): + Double typed attribute value. + + This field is a member of `oneof`_ ``vehicle_attribute_value``. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + string_value: str = proto.Field( + proto.STRING, + number=3, + oneof='vehicle_attribute_value', + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=4, + oneof='vehicle_attribute_value', + ) + number_value: float = proto.Field( + proto.DOUBLE, + number=5, + oneof='vehicle_attribute_value', + ) + + +class VehicleLocation(proto.Message): + r"""The location, speed, and heading of a vehicle at a point in + time. + + Attributes: + location (google.type.latlng_pb2.LatLng): + The location of the vehicle. When it is sent to Fleet + Engine, the vehicle's location is a GPS location. When you + receive it in a response, the vehicle's location can be + either a GPS location, a supplemental location, or some + other estimated location. The source is specified in + ``location_sensor``. + horizontal_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Deprecated: Use ``latlng_accuracy`` instead. + latlng_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``location`` in meters as a radius. + heading (google.protobuf.wrappers_pb2.Int32Value): + Direction the vehicle is moving in degrees. 0 represents + North. The valid range is [0,360). + bearing_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Deprecated: Use ``heading_accuracy`` instead. + heading_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``heading`` in degrees. + altitude (google.protobuf.wrappers_pb2.DoubleValue): + Altitude in meters above WGS84. + vertical_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Deprecated: Use ``altitude_accuracy`` instead. + altitude_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``altitude`` in meters. + speed_kmph (google.protobuf.wrappers_pb2.Int32Value): + Speed of the vehicle in kilometers per hour. Deprecated: Use + ``speed`` instead. + speed (google.protobuf.wrappers_pb2.DoubleValue): + Speed of the vehicle in meters/second + speed_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``speed`` in meters/second. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when ``location`` was reported by the sensor + according to the sensor's clock. + server_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the server + received the location information. + location_sensor (google.maps.fleetengine_v1.types.LocationSensor): + Provider of location data (for example, ``GPS``). + is_road_snapped (google.protobuf.wrappers_pb2.BoolValue): + Whether ``location`` is snapped to a road. + is_gps_sensor_enabled (google.protobuf.wrappers_pb2.BoolValue): + Input only. Indicates whether the GPS sensor + is enabled on the mobile device. + time_since_update (google.protobuf.wrappers_pb2.Int32Value): + Input only. Time (in seconds) since this + location was first sent to the server. This will + be zero for the first update. If the time is + unknown (for example, when the app restarts), + this value resets to zero. + num_stale_updates (google.protobuf.wrappers_pb2.Int32Value): + Input only. Deprecated: Other signals are now + used to determine if a location is stale. + raw_location (google.type.latlng_pb2.LatLng): + Raw vehicle location (unprocessed by + road-snapper). + raw_location_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp associated with the raw location. + raw_location_sensor (google.maps.fleetengine_v1.types.LocationSensor): + Source of the raw location. Defaults to ``GPS``. + raw_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``raw_location`` as a radius, in meters. + supplemental_location (google.type.latlng_pb2.LatLng): + Supplemental location provided by the + integrating app. + supplemental_location_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp associated with the supplemental + location. + supplemental_location_sensor (google.maps.fleetengine_v1.types.LocationSensor): + Source of the supplemental location. Defaults to + ``CUSTOMER_SUPPLIED_LOCATION``. + supplemental_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``supplemental_location`` as a radius, in + meters. + road_snapped (bool): + Deprecated: Use ``is_road_snapped`` instead. + """ + + location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + horizontal_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=8, + message=wrappers_pb2.DoubleValue, + ) + latlng_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=22, + message=wrappers_pb2.DoubleValue, + ) + heading: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + bearing_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=10, + message=wrappers_pb2.DoubleValue, + ) + heading_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=23, + message=wrappers_pb2.DoubleValue, + ) + altitude: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.DoubleValue, + ) + vertical_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=9, + message=wrappers_pb2.DoubleValue, + ) + altitude_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=24, + message=wrappers_pb2.DoubleValue, + ) + speed_kmph: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int32Value, + ) + speed: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.DoubleValue, + ) + speed_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.DoubleValue, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + server_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=13, + message=timestamp_pb2.Timestamp, + ) + location_sensor: 'LocationSensor' = proto.Field( + proto.ENUM, + number=11, + enum='LocationSensor', + ) + is_road_snapped: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=27, + message=wrappers_pb2.BoolValue, + ) + is_gps_sensor_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=12, + message=wrappers_pb2.BoolValue, + ) + time_since_update: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=14, + message=wrappers_pb2.Int32Value, + ) + num_stale_updates: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=15, + message=wrappers_pb2.Int32Value, + ) + raw_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=16, + message=latlng_pb2.LatLng, + ) + raw_location_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=17, + message=timestamp_pb2.Timestamp, + ) + raw_location_sensor: 'LocationSensor' = proto.Field( + proto.ENUM, + number=28, + enum='LocationSensor', + ) + raw_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=25, + message=wrappers_pb2.DoubleValue, + ) + supplemental_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=18, + message=latlng_pb2.LatLng, + ) + supplemental_location_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + supplemental_location_sensor: 'LocationSensor' = proto.Field( + proto.ENUM, + number=20, + enum='LocationSensor', + ) + supplemental_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=21, + message=wrappers_pb2.DoubleValue, + ) + road_snapped: bool = proto.Field( + proto.BOOL, + number=26, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py new file mode 100644 index 000000000000..6cc60e782c23 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'RequestHeader', + }, +) + + +class RequestHeader(proto.Message): + r"""A RequestHeader contains fields common to all Fleet Engine + RPC requests. + + Attributes: + language_code (str): + The BCP-47 language code, such as en-US or sr-Latn. For more + information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + If none is specified, the response may be in any language, + with a preference for English if such a name exists. Field + value example: ``en-US``. + region_code (str): + Required. CLDR region code of the region where the request + originates. Field value example: ``US``. + sdk_version (str): + Version of the calling SDK, if applicable. The version + format is "major.minor.patch", example: ``1.1.2``. + os_version (str): + Version of the operating system on which the calling SDK is + running. Field value examples: ``4.4.1``, ``12.1``. + device_model (str): + Model of the device on which the calling SDK is running. + Field value examples: ``iPhone12,1``, ``SM-G920F``. + sdk_type (google.maps.fleetengine_v1.types.RequestHeader.SdkType): + The type of SDK sending the request. + maps_sdk_version (str): + Version of the MapSDK which the calling SDK depends on, if + applicable. The version format is "major.minor.patch", + example: ``5.2.1``. + nav_sdk_version (str): + Version of the NavSDK which the calling SDK depends on, if + applicable. The version format is "major.minor.patch", + example: ``2.1.0``. + platform (google.maps.fleetengine_v1.types.RequestHeader.Platform): + Platform of the calling SDK. + manufacturer (str): + Manufacturer of the Android device from the calling SDK, + only applicable for the Android SDKs. Field value example: + ``Samsung``. + android_api_level (int): + Android API level of the calling SDK, only applicable for + the Android SDKs. Field value example: ``23``. + trace_id (str): + Optional ID that can be provided for logging + purposes in order to identify the request. + """ + class SdkType(proto.Enum): + r"""Possible types of SDK. + + Values: + SDK_TYPE_UNSPECIFIED (0): + The default value. This value is used if the ``sdk_type`` is + omitted. + CONSUMER (1): + The calling SDK is Consumer. + DRIVER (2): + The calling SDK is Driver. + JAVASCRIPT (3): + The calling SDK is JavaScript. + """ + SDK_TYPE_UNSPECIFIED = 0 + CONSUMER = 1 + DRIVER = 2 + JAVASCRIPT = 3 + + class Platform(proto.Enum): + r"""The platform of the calling SDK. + + Values: + PLATFORM_UNSPECIFIED (0): + The default value. This value is used if the + platform is omitted. + ANDROID (1): + The request is coming from Android. + IOS (2): + The request is coming from iOS. + WEB (3): + The request is coming from the web. + """ + PLATFORM_UNSPECIFIED = 0 + ANDROID = 1 + IOS = 2 + WEB = 3 + + language_code: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + sdk_version: str = proto.Field( + proto.STRING, + number=3, + ) + os_version: str = proto.Field( + proto.STRING, + number=4, + ) + device_model: str = proto.Field( + proto.STRING, + number=5, + ) + sdk_type: SdkType = proto.Field( + proto.ENUM, + number=6, + enum=SdkType, + ) + maps_sdk_version: str = proto.Field( + proto.STRING, + number=7, + ) + nav_sdk_version: str = proto.Field( + proto.STRING, + number=8, + ) + platform: Platform = proto.Field( + proto.ENUM, + number=9, + enum=Platform, + ) + manufacturer: str = proto.Field( + proto.STRING, + number=10, + ) + android_api_level: int = proto.Field( + proto.INT32, + number=11, + ) + trace_id: str = proto.Field( + proto.STRING, + number=12, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py new file mode 100644 index 000000000000..c67d29281d61 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'SpeedReadingInterval', + 'ConsumableTrafficPolyline', + }, +) + + +class SpeedReadingInterval(proto.Message): + r"""Traffic density indicator on a contiguous segment of a 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. + + Attributes: + start_polyline_point_index (int): + The starting index of this interval in the + path. In JSON, when the index is 0, the field + will appear to be unpopulated. + end_polyline_point_index (int): + The ending index of this interval in the + path. In JSON, when the index is 0, the field + will appear to be unpopulated. + speed (google.maps.fleetengine_v1.types.SpeedReadingInterval.Speed): + Traffic speed in this interval. + """ + 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, + ) + end_polyline_point_index: int = proto.Field( + proto.INT32, + number=2, + ) + speed: Speed = proto.Field( + proto.ENUM, + number=3, + enum=Speed, + ) + + +class ConsumableTrafficPolyline(proto.Message): + r"""Traffic density along a Vehicle's path. + + Attributes: + speed_reading_interval (MutableSequence[google.maps.fleetengine_v1.types.SpeedReadingInterval]): + Traffic speed along the path from the + previous waypoint to the current waypoint. + encoded_path_to_waypoint (str): + The path the driver is taking from the previous waypoint to + the current waypoint. This path has landmarks in it so + clients can show traffic markers along the path (see + ``speed_reading_interval``). Decoding is not yet supported. + """ + + speed_reading_interval: MutableSequence['SpeedReadingInterval'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SpeedReadingInterval', + ) + encoded_path_to_waypoint: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py new file mode 100644 index 000000000000..911a0a2053c2 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import header as mf_header +from google.maps.fleetengine_v1.types import trips as mf_trips +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'CreateTripRequest', + 'GetTripRequest', + 'ReportBillableTripRequest', + 'UpdateTripRequest', + 'SearchTripsRequest', + 'SearchTripsResponse', + }, +) + + +class CreateTripRequest(proto.Message): + r"""CreateTrip request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + trip_id (str): + Required. Unique Trip ID. Subject to the following + restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + trip (google.maps.fleetengine_v1.types.Trip): + Required. Trip entity to create. + + When creating a Trip, the following fields are required: + + - ``trip_type`` + - ``pickup_point`` + + The following fields are used if you provide them: + + - ``number_of_passengers`` + - ``vehicle_id`` + - ``dropoff_point`` + - ``intermediate_destinations`` + - ``vehicle_waypoints`` + + All other Trip fields are ignored. For example, all trips + start with a ``trip_status`` of ``NEW`` even if you pass in + a ``trip_status`` of ``CANCELED`` in the creation request. + + Only ``EXCLUSIVE`` trips support + ``intermediate_destinations``. + + When ``vehicle_id`` is set for a shared trip, you must + supply the list of ``Trip.vehicle_waypoints`` to specify the + order of the remaining waypoints for the vehicle, otherwise + the waypoint order will be undetermined. + + When you specify ``Trip.vehicle_waypoints``, the list must + contain all the remaining waypoints of the vehicle's trips, + with no extra waypoints. You must order these waypoints such + that for a given trip, the pickup point is before + intermediate destinations, and all intermediate destinations + come before the drop-off point. An ``EXCLUSIVE`` trip's + waypoints must not interleave with any other trips. + + The ``trip_id``, ``waypoint_type`` and ``location`` fields + are used, and all other TripWaypoint fields in + ``vehicle_waypoints`` are ignored. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + trip_id: str = proto.Field( + proto.STRING, + number=5, + ) + trip: mf_trips.Trip = proto.Field( + proto.MESSAGE, + number=4, + message=mf_trips.Trip, + ) + + +class GetTripRequest(proto.Message): + r"""GetTrip request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/trips/{trip}``. The provider must be + the Project ID (for example, ``sample-cloud-project``) of + the Google Cloud Project of which the service account making + this call is a member. + view (google.maps.fleetengine_v1.types.TripView): + The subset of Trip fields that should be + returned and their interpretation. + current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Trip.route`` or ``Trip.current_route_segment`` data are + retrieved. If route data are unchanged since this timestamp, + the route field is not set in the response. If a minimum is + unspecified, the route data are always retrieved. + remaining_waypoints_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Trip.remaining_waypoints`` are retrieved. If they are + unchanged since this timestamp, the ``remaining_waypoints`` + are not set in the response. If this field is unspecified, + ``remaining_waypoints`` is always retrieved. + route_format_type (google.maps.fleetengine_v1.types.PolylineFormatType): + The returned current route format, ``LAT_LNG_LIST_TYPE`` (in + ``Trip.route``), or ``ENCODED_POLYLINE_TYPE`` (in + ``Trip.current_route_segment``). The default is + ``LAT_LNG_LIST_TYPE``. + current_route_segment_traffic_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Trip.current_route_segment_traffic`` is retrieved. If + traffic data are unchanged since this timestamp, the + ``current_route_segment_traffic`` field is not set in the + response. If a minimum is unspecified, the traffic data are + always retrieved. Note that traffic is only available for + On-Demand Rides and Deliveries Solution customers. + remaining_waypoints_route_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Trip.remaining_waypoints.traffic_to_waypoint`` and + ``Trip.remaining_waypoints.path_to_waypoint`` data are + retrieved. If data are unchanged since this timestamp, the + fields above are not set in the response. If + ``remaining_waypoints_route_version`` is unspecified, + traffic and path are always retrieved. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + view: mf_trips.TripView = proto.Field( + proto.ENUM, + number=11, + enum=mf_trips.TripView, + ) + current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + remaining_waypoints_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + route_format_type: fleetengine.PolylineFormatType = proto.Field( + proto.ENUM, + number=8, + enum=fleetengine.PolylineFormatType, + ) + current_route_segment_traffic_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + remaining_waypoints_route_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +class ReportBillableTripRequest(proto.Message): + r"""ReportBillableTrip request message. + + Attributes: + name (str): + Required. Must be in the format + ``providers/{provider}/billableTrips/{billable_trip}``. The + provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + country_code (str): + Required. Two letter country code of the + country where the trip takes place. Price is + defined according to country code. + platform (google.maps.fleetengine_v1.types.BillingPlatformIdentifier): + The platform upon which the request was + issued. + related_ids (MutableSequence[str]): + The identifiers that are directly related to the trip being + reported. These are usually IDs (for example, session IDs) + of pre-booking operations done before the trip ID is + available. The number of ``related_ids`` is limited to 50. + solution_type (google.maps.fleetengine_v1.types.ReportBillableTripRequest.SolutionType): + The type of GMP product solution (for example, + ``ON_DEMAND_RIDESHARING_AND_DELIVERIES``) used for the + reported trip. + """ + class SolutionType(proto.Enum): + r"""Selector for different solution types of a reported trip. + + Values: + SOLUTION_TYPE_UNSPECIFIED (0): + The default value. For backwards-compatibility, the API will + use ``ON_DEMAND_RIDESHARING_AND_DELIVERIES`` by default + which is the first supported solution type. + ON_DEMAND_RIDESHARING_AND_DELIVERIES (1): + The solution is an on-demand ridesharing and + deliveries trip. + """ + SOLUTION_TYPE_UNSPECIFIED = 0 + ON_DEMAND_RIDESHARING_AND_DELIVERIES = 1 + + name: str = proto.Field( + proto.STRING, + number=2, + ) + country_code: str = proto.Field( + proto.STRING, + number=3, + ) + platform: mf_trips.BillingPlatformIdentifier = proto.Field( + proto.ENUM, + number=5, + enum=mf_trips.BillingPlatformIdentifier, + ) + related_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + solution_type: SolutionType = proto.Field( + proto.ENUM, + number=7, + enum=SolutionType, + ) + + +class UpdateTripRequest(proto.Message): + r"""UpdateTrip request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/trips/{trip}``. The provider must be + the Project ID (for example, ``sample-consumer-project``) of + the Google Cloud Project of which the service account making + this call is a member. + trip (google.maps.fleetengine_v1.types.Trip): + Required. The Trip associated with the update. + + The following fields are maintained by the Fleet Engine. Do + not update them using Trip.update. + + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_traffic`` + - ``current_route_segment_traffic_version`` + - ``current_route_segment_version`` + - ``dropoff_time`` + - ``eta_to_next_waypoint`` + - ``intermediate_destinations_version`` + - ``last_location`` + - ``name`` + - ``number_of_passengers`` + - ``pickup_time`` + - ``remaining_distance_meters`` + - ``remaining_time_to_first_waypoint`` + - ``remaining_waypoints`` + - ``remaining_waypoints_version`` + - ``route`` + + When you update the ``Trip.vehicle_id`` for a shared trip, + you must supply the list of ``Trip.vehicle_waypoints`` to + specify the order of the remaining waypoints, otherwise the + order will be undetermined. + + When you specify ``Trip.vehicle_waypoints``, the list must + contain all the remaining waypoints of the vehicle's trips, + with no extra waypoints. You must order these waypoints such + that for a given trip, the pickup point is before + intermediate destinations, and all intermediate destinations + come before the drop-off point. An ``EXCLUSIVE`` trip's + waypoints must not interleave with any other trips. The + ``trip_id``, ``waypoint_type`` and ``location`` fields are + used, and all other TripWaypoint fields in + ``vehicle_waypoints`` are ignored. + + To avoid a race condition for trips with multiple + destinations, you should provide + ``Trip.intermediate_destinations_version`` when updating the + trip status to ``ENROUTE_TO_INTERMEDIATE_DESTINATION``. The + ``Trip.intermediate_destinations_version`` passed must be + consistent with Fleet Engine's version. If it isn't, the + request fails. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field mask indicating which fields in Trip to + update. The ``update_mask`` must contain at least one field. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + trip: mf_trips.Trip = proto.Field( + proto.MESSAGE, + number=4, + message=mf_trips.Trip, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class SearchTripsRequest(proto.Message): + r"""SearchTrips request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + vehicle_id (str): + The vehicle associated with the trips in the request. If + unspecified, the returned trips do not contain: + + - ``current_route_segment`` + - ``remaining_waypoints`` + - ``remaining_distance_meters`` + - ``eta_to_first_waypoint`` + active_trips_only (bool): + If set to true, the response includes Trips + that influence a driver's route. + page_size (int): + If not set, the server decides the number of + results to return. + page_token (str): + Set this to a value previously returned in the + ``SearchTripsResponse`` to continue from previous results. + minimum_staleness (google.protobuf.duration_pb2.Duration): + If specified, returns the trips that have not been updated + after the time ``(current - minimum_staleness)``. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + vehicle_id: str = proto.Field( + proto.STRING, + number=4, + ) + active_trips_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + page_size: int = proto.Field( + proto.INT32, + number=6, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + minimum_staleness: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class SearchTripsResponse(proto.Message): + r"""SearchTrips response message. + + Attributes: + trips (MutableSequence[google.maps.fleetengine_v1.types.Trip]): + The list of trips for the requested vehicle. + next_page_token (str): + Pass this token in the SearchTripsRequest to + page through list results. The API returns a + trip list on each call, and when no more results + remain the trip list is empty. + """ + + @property + def raw_page(self): + return self + + trips: MutableSequence[mf_trips.Trip] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=mf_trips.Trip, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py new file mode 100644 index 000000000000..7fd145d8cd69 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py @@ -0,0 +1,490 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import traffic +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.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'TripStatus', + 'BillingPlatformIdentifier', + 'TripView', + 'Trip', + 'StopLocation', + }, +) + + +class TripStatus(proto.Enum): + r"""The status of a trip indicating its progression. + + Values: + UNKNOWN_TRIP_STATUS (0): + Default, used for unspecified or unrecognized + trip status. + NEW (1): + Newly created trip. + ENROUTE_TO_PICKUP (2): + The driver is on their way to the pickup + point. + ARRIVED_AT_PICKUP (3): + The driver has arrived at the pickup point. + ARRIVED_AT_INTERMEDIATE_DESTINATION (7): + The driver has arrived at an intermediate + destination and is waiting for the rider. + ENROUTE_TO_INTERMEDIATE_DESTINATION (8): + The driver is on their way to an intermediate + destination (not the dropoff point). + ENROUTE_TO_DROPOFF (4): + The driver has picked up the rider and is on + their way to the next destination. + COMPLETE (5): + The rider has been dropped off and the trip + is complete. + CANCELED (6): + The trip was canceled prior to pickup by the + driver, rider, or rideshare provider. + """ + UNKNOWN_TRIP_STATUS = 0 + NEW = 1 + ENROUTE_TO_PICKUP = 2 + ARRIVED_AT_PICKUP = 3 + ARRIVED_AT_INTERMEDIATE_DESTINATION = 7 + ENROUTE_TO_INTERMEDIATE_DESTINATION = 8 + ENROUTE_TO_DROPOFF = 4 + COMPLETE = 5 + CANCELED = 6 + + +class BillingPlatformIdentifier(proto.Enum): + r"""A set of values that indicate upon which platform the request + was issued. + + Values: + BILLING_PLATFORM_IDENTIFIER_UNSPECIFIED (0): + Default. Used for unspecified platforms. + SERVER (1): + The platform is a client server. + WEB (2): + The platform is a web browser. + ANDROID (3): + The platform is an Android mobile device. + IOS (4): + The platform is an IOS mobile device. + OTHERS (5): + Other platforms that are not listed in this + enumeration. + """ + BILLING_PLATFORM_IDENTIFIER_UNSPECIFIED = 0 + SERVER = 1 + WEB = 2 + ANDROID = 3 + IOS = 4 + OTHERS = 5 + + +class TripView(proto.Enum): + r"""Selector for different sets of Trip fields in a ``GetTrip`` + response. See `AIP-157 `__ for context. + Additional views are likely to be added. + + Values: + TRIP_VIEW_UNSPECIFIED (0): + The default value. For backwards-compatibility, the API will + default to an SDK view. To ensure stability and support, + customers are advised to select a ``TripView`` other than + ``SDK``. + SDK (1): + Includes fields that may not be interpretable + or supportable using publicly available + libraries. + JOURNEY_SHARING_V1S (2): + Trip fields are populated for the Journey + Sharing use case. This view is intended for + server-to-server communications. + """ + TRIP_VIEW_UNSPECIFIED = 0 + SDK = 1 + JOURNEY_SHARING_V1S = 2 + + +class Trip(proto.Message): + r"""Trip metadata. + + Attributes: + name (str): + Output only. In the format + "providers/{provider}/trips/{trip}". + vehicle_id (str): + ID of the vehicle making this trip. + trip_status (google.maps.fleetengine_v1.types.TripStatus): + Current status of the trip. + trip_type (google.maps.fleetengine_v1.types.TripType): + The type of the trip. + pickup_point (google.maps.fleetengine_v1.types.TerminalLocation): + Location where customer indicates they will + be picked up. + actual_pickup_point (google.maps.fleetengine_v1.types.StopLocation): + Input only. The actual location when and + where customer was picked up. This field is for + provider to provide feedback on actual pickup + information. + actual_pickup_arrival_point (google.maps.fleetengine_v1.types.StopLocation): + Input only. The actual time and location of + the driver arrival at the pickup point. + This field is for provider to provide feedback + on actual arrival information at the pickup + point. + pickup_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Either the estimated future time + when the rider(s) will be picked up, or the + actual time when they were picked up. + intermediate_destinations (MutableSequence[google.maps.fleetengine_v1.types.TerminalLocation]): + Intermediate stops in order that the trip + requests (in addition to pickup and dropoff). + Initially this will not be supported for shared + trips. + intermediate_destinations_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the last time the ``intermediate_destinations`` + was modified. Your server should cache this value and pass + it in ``UpdateTripRequest`` when update + ``intermediate_destination_index`` to ensure the + ``intermediate_destinations`` is not changed. + intermediate_destination_index (int): + When ``TripStatus`` is + ``ENROUTE_TO_INTERMEDIATE_DESTINATION``, a number between + [0..N-1] indicating which intermediate destination the + vehicle will cross next. When ``TripStatus`` is + ``ARRIVED_AT_INTERMEDIATE_DESTINATION``, a number between + [0..N-1] indicating which intermediate destination the + vehicle is at. The provider sets this value. If there are no + ``intermediate_destinations``, this field is ignored. + actual_intermediate_destination_arrival_points (MutableSequence[google.maps.fleetengine_v1.types.StopLocation]): + Input only. The actual time and location of + the driver's arrival at an intermediate + destination. This field is for provider to + provide feedback on actual arrival information + at intermediate destinations. + actual_intermediate_destinations (MutableSequence[google.maps.fleetengine_v1.types.StopLocation]): + Input only. The actual time and location when + and where the customer was picked up from an + intermediate destination. This field is for + provider to provide feedback on actual pickup + information at intermediate destinations. + dropoff_point (google.maps.fleetengine_v1.types.TerminalLocation): + Location where customer indicates they will + be dropped off. + actual_dropoff_point (google.maps.fleetengine_v1.types.StopLocation): + Input only. The actual time and location when + and where customer was dropped off. This field + is for provider to provide feedback on actual + dropoff information. + dropoff_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Either the estimated future time + when the rider(s) will be dropped off at the + final destination, or the actual time when they + were dropped off. + remaining_waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): + Output only. The full path from the current + location to the dropoff point, inclusive. This + path could include waypoints from other trips. + vehicle_waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): + This field supports manual ordering of the waypoints for the + trip. It contains all of the remaining waypoints for the + assigned vehicle, as well as the pickup and drop-off + waypoints for this trip. If the trip hasn't been assigned to + a vehicle, then Fleet Engine ignores this field. For privacy + reasons, this field is only populated by the server on + ``UpdateTrip`` and ``CreateTrip`` calls, NOT on ``GetTrip`` + calls. + route (MutableSequence[google.type.latlng_pb2.LatLng]): + Output only. Anticipated route for this trip to the first + entry in remaining_waypoints. Note that the first waypoint + may belong to a different trip. + current_route_segment (str): + Output only. An encoded path to the next + waypoint. + Note: This field is intended only for use by the + Driver SDK and Consumer SDK. Decoding is not yet + supported. + current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Indicates the last time the + route was modified. + Note: This field is intended only for use by the + Driver SDK and Consumer SDK. + current_route_segment_traffic (google.maps.fleetengine_v1.types.ConsumableTrafficPolyline): + Output only. Indicates the traffic conditions along the + ``current_route_segment`` when they're available. + + Note: This field is intended only for use by the Driver SDK + and Consumer SDK. + current_route_segment_traffic_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Indicates the last time the + ``current_route_segment_traffic`` was modified. + + Note: This field is intended only for use by the Driver SDK + and Consumer SDK. + current_route_segment_end_point (google.maps.fleetengine_v1.types.TripWaypoint): + Output only. The waypoint where ``current_route_segment`` + ends. + remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + Output only. The remaining driving distance in the + ``current_route_segment`` field. The value is unspecified if + the trip is not assigned to a vehicle, or the trip is + completed or cancelled. + eta_to_first_waypoint (google.protobuf.timestamp_pb2.Timestamp): + Output only. The ETA to the next waypoint (the first entry + in the ``remaining_waypoints`` field). The value is + unspecified if the trip is not assigned to a vehicle, or the + trip is inactive (completed or cancelled). + remaining_time_to_first_waypoint (google.protobuf.duration_pb2.Duration): + Output only. The duration from when the Trip data is + returned to the time in ``Trip.eta_to_first_waypoint``. The + value is unspecified if the trip is not assigned to a + vehicle, or the trip is inactive (completed or cancelled). + remaining_waypoints_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Indicates the last time that + ``remaining_waypoints`` was changed (a waypoint was added, + removed, or changed). + remaining_waypoints_route_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Indicates the last time the + ``remaining_waypoints.path_to_waypoint`` and + ``remaining_waypoints.traffic_to_waypoint`` were modified. + Your client app should cache this value and pass it in + ``GetTripRequest`` to ensure the paths and traffic for + ``remaining_waypoints`` are only returned if updated. + number_of_passengers (int): + Immutable. Indicates the number of passengers on this trip + and does not include the driver. A vehicle must have + available capacity to be returned in a ``SearchVehicles`` + response. + last_location (google.maps.fleetengine_v1.types.VehicleLocation): + Output only. Indicates the last reported + location of the vehicle along the route. + last_location_snappable (bool): + Output only. Indicates whether the vehicle's + ``last_location`` can be snapped to the + current_route_segment. False if ``last_location`` or + ``current_route_segment`` doesn't exist. It is computed by + Fleet Engine. Any update from clients will be ignored. + view (google.maps.fleetengine_v1.types.TripView): + The subset of Trip fields that are populated + and how they should be interpreted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + vehicle_id: str = proto.Field( + proto.STRING, + number=2, + ) + trip_status: 'TripStatus' = proto.Field( + proto.ENUM, + number=3, + enum='TripStatus', + ) + trip_type: fleetengine.TripType = proto.Field( + proto.ENUM, + number=4, + enum=fleetengine.TripType, + ) + pickup_point: fleetengine.TerminalLocation = proto.Field( + proto.MESSAGE, + number=5, + message=fleetengine.TerminalLocation, + ) + actual_pickup_point: 'StopLocation' = proto.Field( + proto.MESSAGE, + number=22, + message='StopLocation', + ) + actual_pickup_arrival_point: 'StopLocation' = proto.Field( + proto.MESSAGE, + number=32, + message='StopLocation', + ) + pickup_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + intermediate_destinations: MutableSequence[fleetengine.TerminalLocation] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=fleetengine.TerminalLocation, + ) + intermediate_destinations_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=25, + message=timestamp_pb2.Timestamp, + ) + intermediate_destination_index: int = proto.Field( + proto.INT32, + number=15, + ) + actual_intermediate_destination_arrival_points: MutableSequence['StopLocation'] = proto.RepeatedField( + proto.MESSAGE, + number=33, + message='StopLocation', + ) + actual_intermediate_destinations: MutableSequence['StopLocation'] = proto.RepeatedField( + proto.MESSAGE, + number=34, + message='StopLocation', + ) + dropoff_point: fleetengine.TerminalLocation = proto.Field( + proto.MESSAGE, + number=7, + message=fleetengine.TerminalLocation, + ) + actual_dropoff_point: 'StopLocation' = proto.Field( + proto.MESSAGE, + number=23, + message='StopLocation', + ) + dropoff_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + remaining_waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message=fleetengine.TripWaypoint, + ) + vehicle_waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message=fleetengine.TripWaypoint, + ) + route: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=latlng_pb2.LatLng, + ) + current_route_segment: str = proto.Field( + proto.STRING, + number=21, + ) + current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=17, + message=timestamp_pb2.Timestamp, + ) + current_route_segment_traffic: traffic.ConsumableTrafficPolyline = proto.Field( + proto.MESSAGE, + number=28, + message=traffic.ConsumableTrafficPolyline, + ) + current_route_segment_traffic_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=30, + message=timestamp_pb2.Timestamp, + ) + current_route_segment_end_point: fleetengine.TripWaypoint = proto.Field( + proto.MESSAGE, + number=24, + message=fleetengine.TripWaypoint, + ) + remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=12, + message=wrappers_pb2.Int32Value, + ) + eta_to_first_waypoint: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=13, + message=timestamp_pb2.Timestamp, + ) + remaining_time_to_first_waypoint: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=27, + message=duration_pb2.Duration, + ) + remaining_waypoints_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + remaining_waypoints_route_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=29, + message=timestamp_pb2.Timestamp, + ) + number_of_passengers: int = proto.Field( + proto.INT32, + number=10, + ) + last_location: fleetengine.VehicleLocation = proto.Field( + proto.MESSAGE, + number=11, + message=fleetengine.VehicleLocation, + ) + last_location_snappable: bool = proto.Field( + proto.BOOL, + number=26, + ) + view: 'TripView' = proto.Field( + proto.ENUM, + number=31, + enum='TripView', + ) + + +class StopLocation(proto.Message): + r"""The actual location where a stop (pickup/dropoff) happened. + + Attributes: + point (google.type.latlng_pb2.LatLng): + Required. Denotes the actual location. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + Indicates when the stop happened. + stop_time (google.protobuf.timestamp_pb2.Timestamp): + Input only. Deprecated. Use the timestamp + field. + """ + + point: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + stop_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py new file mode 100644 index 000000000000..a3097884c456 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py @@ -0,0 +1,1050 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import header as mf_header +from google.maps.fleetengine_v1.types import vehicles as mf_vehicles +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'CreateVehicleRequest', + 'GetVehicleRequest', + 'UpdateVehicleRequest', + 'UpdateVehicleAttributesRequest', + 'UpdateVehicleAttributesResponse', + 'SearchVehiclesRequest', + 'SearchVehiclesResponse', + 'ListVehiclesRequest', + 'ListVehiclesResponse', + 'Waypoint', + 'VehicleMatch', + 'VehicleAttributeList', + }, +) + + +class CreateVehicleRequest(proto.Message): + r"""``CreateVehicle`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + vehicle_id (str): + Required. Unique Vehicle ID. Subject to the following + restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + vehicle (google.maps.fleetengine_v1.types.Vehicle): + Required. The Vehicle entity to create. When creating a + Vehicle, the following fields are required: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + When creating a Vehicle, the following fields are ignored: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + vehicle_id: str = proto.Field( + proto.STRING, + number=4, + ) + vehicle: mf_vehicles.Vehicle = proto.Field( + proto.MESSAGE, + number=5, + message=mf_vehicles.Vehicle, + ) + + +class GetVehicleRequest(proto.Message): + r"""``GetVehicle`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/vehicles/{vehicle}``. The provider + must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Vehicle.current_route_segment`` is retrieved. If the route + is unchanged since this timestamp, the + ``current_route_segment`` field is not set in the response. + If a minimum is unspecified, the ``current_route_segment`` + is always retrieved. + waypoints_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Vehicle.waypoints`` data is retrieved. If the waypoints + are unchanged since this timestamp, the + ``vehicle.waypoints`` data is not set in the response. If + this field is unspecified, ``vehicle.waypoints`` is always + retrieved. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + waypoints_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class UpdateVehicleRequest(proto.Message): + r"""\`UpdateVehicle request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/vehicles/{vehicle}``. The {provider} + must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + vehicle (google.maps.fleetengine_v1.types.Vehicle): + Required. The ``Vehicle`` entity values to apply. When + updating a ``Vehicle``, the following fields may not be + updated as they are managed by the server. + + - ``available_capacity`` + - ``current_route_segment_version`` + - ``current_trips`` + - ``name`` + - ``waypoints_version`` + + If the ``attributes`` field is updated, **all** the + vehicle's attributes are replaced with the attributes + provided in the request. If you want to update only some + attributes, see the ``UpdateVehicleAttributes`` method. + + Likewise, the ``waypoints`` field can be updated, but must + contain all the waypoints currently on the vehicle, and no + other waypoints. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask indicating which fields of the + ``Vehicle`` to update. At least one field name must be + provided. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + vehicle: mf_vehicles.Vehicle = proto.Field( + proto.MESSAGE, + number=4, + message=mf_vehicles.Vehicle, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateVehicleAttributesRequest(proto.Message): + r"""``UpdateVehicleAttributes`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/vehicles/{vehicle}``. The provider + must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + Required. The vehicle attributes to update. + Unmentioned attributes are not altered or + removed. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=fleetengine.VehicleAttribute, + ) + + +class UpdateVehicleAttributesResponse(proto.Message): + r"""``UpdateVehicleAttributes`` response message. + + Attributes: + attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + Required. The updated full list of vehicle + attributes, including new, altered, and + untouched attributes. + """ + + attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=fleetengine.VehicleAttribute, + ) + + +class SearchVehiclesRequest(proto.Message): + r"""``SearchVehicles`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + pickup_point (google.maps.fleetengine_v1.types.TerminalLocation): + Required. The pickup point to search near. + dropoff_point (google.maps.fleetengine_v1.types.TerminalLocation): + The customer's intended dropoff location. The field is + required if ``trip_types`` contains ``TripType.SHARED``. + pickup_radius_meters (int): + Required. Defines the vehicle search radius + around the pickup point. Only vehicles within + the search radius will be returned. Value must + be between 400 and 10000 meters (inclusive). + count (int): + Required. Specifies the maximum number of + vehicles to return. The value must be between 1 + and 50 (inclusive). + minimum_capacity (int): + Required. Specifies the number of passengers + being considered for a trip. The value must be + greater than or equal to one. The driver is not + considered in the capacity value. + trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): + Required. Represents the type of proposed trip. Must include + exactly one type. ``UNKNOWN_TRIP_TYPE`` is not allowed. + Restricts the search to only those vehicles that can support + that trip type. + maximum_staleness (google.protobuf.duration_pb2.Duration): + Restricts the search to only those vehicles + that have sent location updates to Fleet Engine + within the specified duration. Stationary + vehicles still transmitting their locations are + not considered stale. If this field is not set, + the server uses five minutes as the default + value. + vehicle_types (MutableSequence[google.maps.fleetengine_v1.types.Vehicle.VehicleType]): + Required. Restricts the search to vehicles with one of the + specified types. At least one vehicle type must be + specified. VehicleTypes with a category of ``UNKNOWN`` are + not allowed. + required_attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + Callers can form complex logical operations using any + combination of the ``required_attributes``, + ``required_one_of_attributes``, and + ``required_one_of_attribute_sets`` fields. + + ``required_attributes`` is a list; + ``required_one_of_attributes`` uses a message which allows a + list of lists. In combination, the two fields allow the + composition of this expression: + + :: + + (required_attributes[0] AND required_attributes[1] AND ...) + AND + (required_one_of_attributes[0][0] OR required_one_of_attributes[0][1] OR + ...) + AND + (required_one_of_attributes[1][0] OR required_one_of_attributes[1][1] OR + ...) + + Restricts the search to only those vehicles with the + specified attributes. This field is a conjunction/AND + operation. A max of 50 required_attributes is allowed. This + matches the maximum number of attributes allowed on a + vehicle. + required_one_of_attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttributeList]): + Restricts the search to only those vehicles with at least + one of the specified attributes in each + ``VehicleAttributeList``. Within each list, a vehicle must + match at least one of the attributes. This field is an + inclusive disjunction/OR operation in each + ``VehicleAttributeList`` and a conjunction/AND operation + across the collection of ``VehicleAttributeList``. + required_one_of_attribute_sets (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttributeList]): + ``required_one_of_attribute_sets`` provides additional + functionality. + + Similar to ``required_one_of_attributes``, + ``required_one_of_attribute_sets`` uses a message which + allows a list of lists, allowing expressions such as this + one: + + :: + + (required_attributes[0] AND required_attributes[1] AND ...) + AND + ( + (required_one_of_attribute_sets[0][0] AND + required_one_of_attribute_sets[0][1] AND + ...) + OR + (required_one_of_attribute_sets[1][0] AND + required_one_of_attribute_sets[1][1] AND + ...) + ) + + Restricts the search to only those vehicles with all the + attributes in a ``VehicleAttributeList``. Within each list, + a vehicle must match all of the attributes. This field is a + conjunction/AND operation in each ``VehicleAttributeList`` + and inclusive disjunction/OR operation across the collection + of ``VehicleAttributeList``. + order_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): + Required. Specifies the desired ordering + criterion for results. + include_back_to_back (bool): + This indicates if vehicles with a single active trip are + eligible for this search. This field is only used when + ``current_trips_present`` is unspecified. When + ``current_trips_present`` is unspecified and this field is + ``false``, vehicles with assigned trips are excluded from + the search results. When ``current_trips_present`` is + unspecified and this field is ``true``, search results can + include vehicles with one active trip that has a status of + ``ENROUTE_TO_DROPOFF``. When ``current_trips_present`` is + specified, this field cannot be set to true. + + The default value is ``false``. + trip_id (str): + Indicates the trip associated with this + ``SearchVehicleRequest``. + current_trips_present (google.maps.fleetengine_v1.types.SearchVehiclesRequest.CurrentTripsPresent): + This indicates if vehicles with active trips are eligible + for this search. This must be set to something other than + ``CURRENT_TRIPS_PRESENT_UNSPECIFIED`` if ``trip_type`` + includes ``SHARED``. + filter (str): + Optional. A filter query to apply when searching vehicles. + See http://aip.dev/160 for examples of the filter syntax. + + This field is designed to replace the + ``required_attributes``, ``required_one_of_attributes``, and + ``required_one_of_attributes_sets`` fields. If a non-empty + value is specified here, the following fields must be empty: + ``required_attributes``, ``required_one_of_attributes``, and + ``required_one_of_attributes_sets``. + + This filter functions as an AND clause with other + constraints, such as ``minimum_capacity`` or + ``vehicle_types``. + + Note that the only queries supported are on vehicle + attributes (for example, ``attributes. = `` or + ``attributes. = AND attributes. = ``). + The maximum number of restrictions allowed in a filter query + is 50. + + Also, all attributes are stored as strings, so the only + supported comparisons against attributes are string + comparisons. In order to compare against number or boolean + values, the values must be explicitly quoted to be treated + as strings (for example, ``attributes. = "10"`` or + ``attributes. = "true"``). + """ + class VehicleMatchOrder(proto.Enum): + r"""Specifies the order of the vehicle matches in the response. + + Values: + UNKNOWN_VEHICLE_MATCH_ORDER (0): + Default, used for unspecified or unrecognized + vehicle matches order. + PICKUP_POINT_ETA (1): + Ascending order by vehicle driving time to + the pickup point. + PICKUP_POINT_DISTANCE (2): + Ascending order by vehicle driving distance + to the pickup point. + DROPOFF_POINT_ETA (3): + Ascending order by vehicle driving time to + the dropoff point. This order can only be used + if the dropoff point is specified in the + request. + PICKUP_POINT_STRAIGHT_DISTANCE (4): + Ascending order by straight-line distance + from the vehicle's last reported location to the + pickup point. + COST (5): + Ascending order by the configured match cost. + Match cost is defined as a weighted calculation + between straight-line distance and ETA. Weights + are set with default values and can be modified + per customer. Please contact Google support if + these weights need to be modified for your + project. + """ + UNKNOWN_VEHICLE_MATCH_ORDER = 0 + PICKUP_POINT_ETA = 1 + PICKUP_POINT_DISTANCE = 2 + DROPOFF_POINT_ETA = 3 + PICKUP_POINT_STRAIGHT_DISTANCE = 4 + COST = 5 + + class CurrentTripsPresent(proto.Enum): + r"""Specifies the types of restrictions on a vehicle's current + trips. + + Values: + CURRENT_TRIPS_PRESENT_UNSPECIFIED (0): + The availability of vehicles with trips present is governed + by the ``include_back_to_back`` field. + NONE (1): + Vehicles without trips can appear in search results. When + this value is used, ``include_back_to_back`` cannot be + ``true``. + ANY (2): + Vehicles with at most 5 current trips and 10 waypoints are + included in the search results. When this value is used, + ``include_back_to_back`` cannot be ``true``. + """ + CURRENT_TRIPS_PRESENT_UNSPECIFIED = 0 + NONE = 1 + ANY = 2 + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + pickup_point: fleetengine.TerminalLocation = proto.Field( + proto.MESSAGE, + number=4, + message=fleetengine.TerminalLocation, + ) + dropoff_point: fleetengine.TerminalLocation = proto.Field( + proto.MESSAGE, + number=5, + message=fleetengine.TerminalLocation, + ) + pickup_radius_meters: int = proto.Field( + proto.INT32, + number=6, + ) + count: int = proto.Field( + proto.INT32, + number=7, + ) + minimum_capacity: int = proto.Field( + proto.INT32, + number=8, + ) + trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( + proto.ENUM, + number=9, + enum=fleetengine.TripType, + ) + maximum_staleness: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + message=duration_pb2.Duration, + ) + vehicle_types: MutableSequence[mf_vehicles.Vehicle.VehicleType] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=mf_vehicles.Vehicle.VehicleType, + ) + required_attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=fleetengine.VehicleAttribute, + ) + required_one_of_attributes: MutableSequence['VehicleAttributeList'] = proto.RepeatedField( + proto.MESSAGE, + number=15, + message='VehicleAttributeList', + ) + required_one_of_attribute_sets: MutableSequence['VehicleAttributeList'] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message='VehicleAttributeList', + ) + order_by: VehicleMatchOrder = proto.Field( + proto.ENUM, + number=13, + enum=VehicleMatchOrder, + ) + include_back_to_back: bool = proto.Field( + proto.BOOL, + number=18, + ) + trip_id: str = proto.Field( + proto.STRING, + number=19, + ) + current_trips_present: CurrentTripsPresent = proto.Field( + proto.ENUM, + number=21, + enum=CurrentTripsPresent, + ) + filter: str = proto.Field( + proto.STRING, + number=22, + ) + + +class SearchVehiclesResponse(proto.Message): + r"""``SearchVehicles`` response message. + + Attributes: + matches (MutableSequence[google.maps.fleetengine_v1.types.VehicleMatch]): + List of vehicles that match the ``SearchVehiclesRequest`` + criteria, ordered according to + ``SearchVehiclesRequest.order_by`` field. + """ + + matches: MutableSequence['VehicleMatch'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VehicleMatch', + ) + + +class ListVehiclesRequest(proto.Message): + r"""``ListVehicles`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + page_size (int): + The maximum number of vehicles to return. + Default value: 100. + page_token (str): + The value of the ``next_page_token`` provided by a previous + call to ``ListVehicles`` so that you can paginate through + groups of vehicles. The value is undefined if the filter + criteria of the request is not the same as the filter + criteria for the previous call to ``ListVehicles``. + minimum_capacity (google.protobuf.wrappers_pb2.Int32Value): + Specifies the required minimum capacity of the vehicle. All + vehicles returned will have a ``maximum_capacity`` greater + than or equal to this value. If set, must be greater or + equal to 0. + trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): + Restricts the response to vehicles that + support at least one of the specified trip + types. + maximum_staleness (google.protobuf.duration_pb2.Duration): + Restricts the response to vehicles that have + sent location updates to Fleet Engine within the + specified duration. Stationary vehicles still + transmitting their locations are not considered + stale. If present, must be a valid positive + duration. + vehicle_type_categories (MutableSequence[google.maps.fleetengine_v1.types.Vehicle.VehicleType.Category]): + Required. Restricts the response to vehicles with one of the + specified type categories. ``UNKNOWN`` is not allowed. + required_attributes (MutableSequence[str]): + Callers can form complex logical operations using any + combination of the ``required_attributes``, + ``required_one_of_attributes``, and + ``required_one_of_attribute_sets`` fields. + + ``required_attributes`` is a list; + ``required_one_of_attributes`` uses a message which allows a + list of lists. In combination, the two fields allow the + composition of this expression: + + :: + + (required_attributes[0] AND required_attributes[1] AND ...) + AND + (required_one_of_attributes[0][0] OR required_one_of_attributes[0][1] OR + ...) + AND + (required_one_of_attributes[1][0] OR required_one_of_attributes[1][1] OR + ...) + + Restricts the response to vehicles with the specified + attributes. This field is a conjunction/AND operation. A max + of 50 required_attributes is allowed. This matches the + maximum number of attributes allowed on a vehicle. Each + repeated string should be of the format "key:value". + required_one_of_attributes (MutableSequence[str]): + Restricts the response to vehicles with at least one of the + specified attributes in each ``VehicleAttributeList``. + Within each list, a vehicle must match at least one of the + attributes. This field is an inclusive disjunction/OR + operation in each ``VehicleAttributeList`` and a + conjunction/AND operation across the collection of + ``VehicleAttributeList``. Each repeated string should be of + the format "key1:value1|key2:value2|key3:value3". + required_one_of_attribute_sets (MutableSequence[str]): + ``required_one_of_attribute_sets`` provides additional + functionality. + + Similar to ``required_one_of_attributes``, + ``required_one_of_attribute_sets`` uses a message which + allows a list of lists, allowing expressions such as this + one: + + :: + + (required_attributes[0] AND required_attributes[1] AND ...) + AND + ( + (required_one_of_attribute_sets[0][0] AND + required_one_of_attribute_sets[0][1] AND + ...) + OR + (required_one_of_attribute_sets[1][0] AND + required_one_of_attribute_sets[1][1] AND + ...) + ) + + Restricts the response to vehicles that match all the + attributes in a ``VehicleAttributeList``. Within each list, + a vehicle must match all of the attributes. This field is a + conjunction/AND operation in each ``VehicleAttributeList`` + and inclusive disjunction/OR operation across the collection + of ``VehicleAttributeList``. Each repeated string should be + of the format "key1:value1|key2:value2|key3:value3". + vehicle_state (google.maps.fleetengine_v1.types.VehicleState): + Restricts the response to vehicles that have + this vehicle state. + on_trip_only (bool): + Only return the vehicles with current + trip(s). + filter (str): + Optional. A filter query to apply when listing vehicles. See + http://aip.dev/160 for examples of the filter syntax. + + This field is designed to replace the + ``required_attributes``, ``required_one_of_attributes``, and + ``required_one_of_attributes_sets`` fields. If a non-empty + value is specified here, the following fields must be empty: + ``required_attributes``, ``required_one_of_attributes``, and + ``required_one_of_attributes_sets``. + + This filter functions as an AND clause with other + constraints, such as ``vehicle_state`` or ``on_trip_only``. + + Note that the only queries supported are on vehicle + attributes (for example, ``attributes. = `` or + ``attributes. = AND attributes. = ``). + The maximum number of restrictions allowed in a filter query + is 50. + + Also, all attributes are stored as strings, so the only + supported comparisons against attributes are string + comparisons. In order to compare against number or boolean + values, the values must be explicitly quoted to be treated + as strings (for example, ``attributes. = "10"`` or + ``attributes. = "true"``). + viewport (google.geo.type.types.Viewport): + Optional. A filter that limits the vehicles + returned to those whose last known location was + in the rectangular area defined by the viewport. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=12, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + minimum_capacity: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.Int32Value, + ) + trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( + proto.ENUM, + number=7, + enum=fleetengine.TripType, + ) + maximum_staleness: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + vehicle_type_categories: MutableSequence[mf_vehicles.Vehicle.VehicleType.Category] = proto.RepeatedField( + proto.ENUM, + number=9, + enum=mf_vehicles.Vehicle.VehicleType.Category, + ) + required_attributes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + required_one_of_attributes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=13, + ) + required_one_of_attribute_sets: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + vehicle_state: mf_vehicles.VehicleState = proto.Field( + proto.ENUM, + number=11, + enum=mf_vehicles.VehicleState, + ) + on_trip_only: bool = proto.Field( + proto.BOOL, + number=14, + ) + filter: str = proto.Field( + proto.STRING, + number=16, + ) + viewport: ggt_viewport.Viewport = proto.Field( + proto.MESSAGE, + number=17, + message=ggt_viewport.Viewport, + ) + + +class ListVehiclesResponse(proto.Message): + r"""``ListVehicles`` response message. + + Attributes: + vehicles (MutableSequence[google.maps.fleetengine_v1.types.Vehicle]): + Vehicles matching the criteria in the request. The maximum + number of vehicles returned is determined by the + ``page_size`` field in the request. + next_page_token (str): + Token to retrieve the next page of vehicles, + or empty if there are no more vehicles that meet + the request criteria. + total_size (int): + Required. Total number of vehicles matching + the request criteria across all pages. + """ + + @property + def raw_page(self): + return self + + vehicles: MutableSequence[mf_vehicles.Vehicle] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=mf_vehicles.Vehicle, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT64, + number=3, + ) + + +class Waypoint(proto.Message): + r"""Describes intermediate points along a route for a ``VehicleMatch`` + in a ``SearchVehiclesResponse``. This concept is represented as a + ``TripWaypoint`` in all other endpoints. + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The location of this waypoint. + eta (google.protobuf.timestamp_pb2.Timestamp): + The estimated time that the vehicle will + arrive at this waypoint. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + eta: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class VehicleMatch(proto.Message): + r"""Contains the vehicle and related estimates for a vehicle that match + the points of active trips for the vehicle + ``SearchVehiclesRequest``. + + Attributes: + vehicle (google.maps.fleetengine_v1.types.Vehicle): + Required. A vehicle that matches the request. + vehicle_pickup_eta (google.protobuf.timestamp_pb2.Timestamp): + The vehicle's driving ETA to the pickup point specified in + the request. An empty value indicates a failure in + calculating ETA for the vehicle. If + ``SearchVehiclesRequest.include_back_to_back`` was ``true`` + and this vehicle has an active trip, ``vehicle_pickup_eta`` + includes the time required to complete the current active + trip. + vehicle_pickup_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The distance from the Vehicle's current + location to the pickup point specified in the + request, including any intermediate pickup or + dropoff points for existing trips. This distance + comprises the calculated driving (route) + distance, plus the straight line distance + between the navigation end point and the + requested pickup point. (The distance between + the navigation end point and the requested + pickup point is typically small.) An empty value + indicates an error in calculating the distance. + vehicle_pickup_straight_line_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + Required. The straight-line distance between + the vehicle and the pickup point specified in + the request. + vehicle_dropoff_eta (google.protobuf.timestamp_pb2.Timestamp): + The complete vehicle's driving ETA to the drop off point + specified in the request. The ETA includes stopping at any + waypoints before the ``dropoff_point`` specified in the + request. The value will only be populated when a drop off + point is specified in the request. An empty value indicates + an error calculating the ETA. + vehicle_pickup_to_dropoff_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The vehicle's driving distance (in meters) from the pickup + point to the drop off point specified in the request. The + distance is only between the two points and does not include + the vehicle location or any other points that must be + visited before the vehicle visits either the pickup point or + dropoff point. The value will only be populated when a + ``dropoff_point`` is specified in the request. An empty + value indicates a failure in calculating the distance from + the pickup to drop off point specified in the request. + trip_type (google.maps.fleetengine_v1.types.TripType): + Required. The trip type of the request that + was used to calculate the ETA to the pickup + point. + vehicle_trips_waypoints (MutableSequence[google.maps.fleetengine_v1.types.Waypoint]): + The ordered list of waypoints used to + calculate the ETA. The list includes vehicle + location, the pickup points of active trips for + the vehicle, and the pickup points provided in + the request. An empty list indicates a failure + in calculating ETA for the vehicle. + vehicle_match_type (google.maps.fleetengine_v1.types.VehicleMatch.VehicleMatchType): + Type of the vehicle match. + requested_ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): + The order requested for sorting vehicle + matches. + ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): + The actual order that was used for this vehicle. Normally + this will match the 'order_by' field from the request; + however, in certain circumstances such as an internal server + error, a different method may be used (such as + ``PICKUP_POINT_STRAIGHT_DISTANCE``). + """ + class VehicleMatchType(proto.Enum): + r"""Type of vehicle match. + + Values: + UNKNOWN (0): + Unknown vehicle match type + EXCLUSIVE (1): + The vehicle currently has no trip assigned to + it and can proceed to the pickup point. + BACK_TO_BACK (2): + The vehicle is currently assigned to a trip, + but can proceed to the pickup point after + completing the in-progress trip. ETA and + distance calculations take the existing trip + into account. + CARPOOL (3): + The vehicle has sufficient capacity for a + shared ride. + CARPOOL_BACK_TO_BACK (4): + The vehicle will finish its current, active + trip before proceeding to the pickup point. ETA + and distance calculations take the existing trip + into account. + """ + UNKNOWN = 0 + EXCLUSIVE = 1 + BACK_TO_BACK = 2 + CARPOOL = 3 + CARPOOL_BACK_TO_BACK = 4 + + vehicle: mf_vehicles.Vehicle = proto.Field( + proto.MESSAGE, + number=1, + message=mf_vehicles.Vehicle, + ) + vehicle_pickup_eta: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + vehicle_pickup_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int32Value, + ) + vehicle_pickup_straight_line_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=11, + message=wrappers_pb2.Int32Value, + ) + vehicle_dropoff_eta: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + vehicle_pickup_to_dropoff_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.Int32Value, + ) + trip_type: fleetengine.TripType = proto.Field( + proto.ENUM, + number=6, + enum=fleetengine.TripType, + ) + vehicle_trips_waypoints: MutableSequence['Waypoint'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='Waypoint', + ) + vehicle_match_type: VehicleMatchType = proto.Field( + proto.ENUM, + number=8, + enum=VehicleMatchType, + ) + requested_ordered_by: 'SearchVehiclesRequest.VehicleMatchOrder' = proto.Field( + proto.ENUM, + number=9, + enum='SearchVehiclesRequest.VehicleMatchOrder', + ) + ordered_by: 'SearchVehiclesRequest.VehicleMatchOrder' = proto.Field( + proto.ENUM, + number=10, + enum='SearchVehiclesRequest.VehicleMatchOrder', + ) + + +class VehicleAttributeList(proto.Message): + r"""A list-of-lists datatype for vehicle attributes. + + Attributes: + attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + A list of attributes in this collection. + """ + + attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=fleetengine.VehicleAttribute, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py new file mode 100644 index 000000000000..c4662d189513 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py @@ -0,0 +1,580 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.fleetengine_v1.types import fleetengine +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'VehicleState', + 'LocationPowerSaveMode', + 'BatteryStatus', + 'PowerSource', + 'Vehicle', + 'BatteryInfo', + 'DeviceSettings', + 'LicensePlate', + 'VisualTrafficReportPolylineRendering', + 'TrafficPolylineData', + }, +) + + +class VehicleState(proto.Enum): + r"""The state of a ``Vehicle``. + + Values: + UNKNOWN_VEHICLE_STATE (0): + Default, used for unspecified or unrecognized + vehicle states. + OFFLINE (1): + The vehicle is not accepting new trips. Note: + the vehicle may continue to operate in this + state while completing a trip assigned to it. + ONLINE (2): + The vehicle is accepting new trips. + """ + UNKNOWN_VEHICLE_STATE = 0 + OFFLINE = 1 + ONLINE = 2 + + +class LocationPowerSaveMode(proto.Enum): + r"""How location features are configured to behave on the mobile + device when the devices "battery saver" feature is on. + (https://developer.android.com/reference/android/os/PowerManager#getLocationPowerSaveMode()) + + Values: + UNKNOWN_LOCATION_POWER_SAVE_MODE (0): + Undefined LocationPowerSaveMode + LOCATION_MODE_NO_CHANGE (1): + Either the location providers shouldn't be + affected by battery saver, or battery saver is + off. + LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF (2): + The GPS based location provider should be + disabled when battery saver is on and the device + is non-interactive. + LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF (3): + All location providers should be disabled + when battery saver is on and the device is + non-interactive. + LOCATION_MODE_FOREGROUND_ONLY (4): + All the location providers will be kept + available, but location fixes should only be + provided to foreground apps. + LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF (5): + Location will not be turned off, but + LocationManager will throttle all requests to + providers when the device is non-interactive. + """ + UNKNOWN_LOCATION_POWER_SAVE_MODE = 0 + LOCATION_MODE_NO_CHANGE = 1 + LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF = 2 + LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF = 3 + LOCATION_MODE_FOREGROUND_ONLY = 4 + LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF = 5 + + +class BatteryStatus(proto.Enum): + r"""Status of the battery, whether full or charging etc. + + Values: + UNKNOWN_BATTERY_STATUS (0): + Battery status unknown. + BATTERY_STATUS_CHARGING (1): + Battery is being charged. + BATTERY_STATUS_DISCHARGING (2): + Battery is discharging. + BATTERY_STATUS_FULL (3): + Battery is full. + BATTERY_STATUS_NOT_CHARGING (4): + Battery is not charging. + BATTERY_STATUS_POWER_LOW (5): + Battery is low on power. + """ + UNKNOWN_BATTERY_STATUS = 0 + BATTERY_STATUS_CHARGING = 1 + BATTERY_STATUS_DISCHARGING = 2 + BATTERY_STATUS_FULL = 3 + BATTERY_STATUS_NOT_CHARGING = 4 + BATTERY_STATUS_POWER_LOW = 5 + + +class PowerSource(proto.Enum): + r"""Type of the charger being used to charge the battery. + + Values: + UNKNOWN_POWER_SOURCE (0): + Power source unknown. + POWER_SOURCE_AC (1): + Power source is an AC charger. + POWER_SOURCE_USB (2): + Power source is a USB port. + POWER_SOURCE_WIRELESS (3): + Power source is wireless. + POWER_SOURCE_UNPLUGGED (4): + Battery is unplugged. + """ + UNKNOWN_POWER_SOURCE = 0 + POWER_SOURCE_AC = 1 + POWER_SOURCE_USB = 2 + POWER_SOURCE_WIRELESS = 3 + POWER_SOURCE_UNPLUGGED = 4 + + +class Vehicle(proto.Message): + r"""Vehicle metadata. + + Attributes: + name (str): + Output only. The unique name for this vehicle. The format is + ``providers/{provider}/vehicles/{vehicle}``. + vehicle_state (google.maps.fleetengine_v1.types.VehicleState): + The vehicle state. + supported_trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): + Trip types supported by this vehicle. + current_trips (MutableSequence[str]): + Output only. List of ``trip_id``'s for trips currently + assigned to this vehicle. + last_location (google.maps.fleetengine_v1.types.VehicleLocation): + Last reported location of the vehicle. + maximum_capacity (int): + The total numbers of riders this vehicle can + carry. The driver is not considered in this + value. This value must be greater than or equal + to one. + attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + List of vehicle attributes. A vehicle can + have at most 100 attributes, and each attribute + must have a unique key. + vehicle_type (google.maps.fleetengine_v1.types.Vehicle.VehicleType): + Required. The type of this vehicle. Can be used to filter + vehicles in ``SearchVehicles`` results. Also influences ETA + and route calculations. + license_plate (google.maps.fleetengine_v1.types.LicensePlate): + License plate information for the vehicle. + route (MutableSequence[google.maps.fleetengine_v1.types.TerminalLocation]): + Deprecated: Use ``Vehicle.waypoints`` instead. + current_route_segment (str): + The polyline specifying the route the driver app intends to + take to the next waypoint. This list is also returned in + ``Trip.current_route_segment`` for all active trips assigned + to the vehicle. + + Note: This field is intended only for use by the Driver SDK. + Decoding is not yet supported. + current_route_segment_traffic (google.maps.fleetengine_v1.types.TrafficPolylineData): + Input only. Fleet Engine uses this + information to improve journey sharing. Note: + This field is intended only for use by the + Driver SDK. + current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when ``current_route_segment`` was set. It + can be stored by the client and passed in future + ``GetVehicle`` requests to prevent returning routes that + haven't changed. + current_route_segment_end_point (google.maps.fleetengine_v1.types.TripWaypoint): + The waypoint where ``current_route_segment`` ends. This can + be supplied by drivers on ``UpdateVehicle`` calls either as + a full trip waypoint, a waypoint ``LatLng``, or as the last + ``LatLng`` of the ``current_route_segment``. Fleet Engine + will then do its best to interpolate to an actual waypoint + if it is not fully specified. This field is ignored in + ``UpdateVehicle`` calls unless ``current_route_segment`` is + also specified. + remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The remaining driving distance for the + ``current_route_segment``. This value is also returned in + ``Trip.remaining_distance_meters`` for all active trips + assigned to the vehicle. The value is unspecified if the + ``current_route_segment`` field is empty. + eta_to_first_waypoint (google.protobuf.timestamp_pb2.Timestamp): + The ETA to the first entry in the ``waypoints`` field. The + value is unspecified if the ``waypoints`` field is empty or + the ``Vehicle.current_route_segment`` field is empty. + + When updating a vehicle, ``remaining_time_seconds`` takes + precedence over ``eta_to_first_waypoint`` in the same + request. + remaining_time_seconds (google.protobuf.wrappers_pb2.Int32Value): + Input only. The remaining driving time for the + ``current_route_segment``. The value is unspecified if the + ``waypoints`` field is empty or the + ``Vehicle.current_route_segment`` field is empty. This value + should match ``eta_to_first_waypoint`` - ``current_time`` if + all parties are using the same clock. + + When updating a vehicle, ``remaining_time_seconds`` takes + precedence over ``eta_to_first_waypoint`` in the same + request. + waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): + The remaining waypoints assigned to this + Vehicle. + waypoints_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last time the ``waypoints`` field was updated. + Clients should cache this value and pass it in + ``GetVehicleRequest`` to ensure the ``waypoints`` field is + only returned if it is updated. + back_to_back_enabled (bool): + Indicates if the driver accepts back-to-back trips. If + ``true``, ``SearchVehicles`` may include the vehicle even if + it is currently assigned to a trip. The default value is + ``false``. + navigation_status (google.maps.fleetengine_v1.types.NavigationStatus): + The vehicle's navigation status. + device_settings (google.maps.fleetengine_v1.types.DeviceSettings): + Input only. Information about settings in the + mobile device being used by the driver. + """ + + class VehicleType(proto.Message): + r"""The type of vehicle. + + Attributes: + category (google.maps.fleetengine_v1.types.Vehicle.VehicleType.Category): + Vehicle type category + """ + class Category(proto.Enum): + r"""Vehicle type categories + + Values: + UNKNOWN (0): + Default, used for unspecified or unrecognized + vehicle categories. + AUTO (1): + An automobile. + TAXI (2): + Any vehicle that acts as a taxi (typically + licensed or regulated). + TRUCK (3): + Generally, a vehicle with a large storage + capacity. + TWO_WHEELER (4): + A motorcycle, moped, or other two-wheeled + vehicle + BICYCLE (5): + Human-powered transport. + PEDESTRIAN (6): + A human transporter, typically walking or + running, traveling along pedestrian pathways. + """ + UNKNOWN = 0 + AUTO = 1 + TAXI = 2 + TRUCK = 3 + TWO_WHEELER = 4 + BICYCLE = 5 + PEDESTRIAN = 6 + + category: 'Vehicle.VehicleType.Category' = proto.Field( + proto.ENUM, + number=1, + enum='Vehicle.VehicleType.Category', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + vehicle_state: 'VehicleState' = proto.Field( + proto.ENUM, + number=2, + enum='VehicleState', + ) + supported_trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=fleetengine.TripType, + ) + current_trips: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + last_location: fleetengine.VehicleLocation = proto.Field( + proto.MESSAGE, + number=5, + message=fleetengine.VehicleLocation, + ) + maximum_capacity: int = proto.Field( + proto.INT32, + number=6, + ) + attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=fleetengine.VehicleAttribute, + ) + vehicle_type: VehicleType = proto.Field( + proto.MESSAGE, + number=9, + message=VehicleType, + ) + license_plate: 'LicensePlate' = proto.Field( + proto.MESSAGE, + number=10, + message='LicensePlate', + ) + route: MutableSequence[fleetengine.TerminalLocation] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=fleetengine.TerminalLocation, + ) + current_route_segment: str = proto.Field( + proto.STRING, + number=20, + ) + current_route_segment_traffic: 'TrafficPolylineData' = proto.Field( + proto.MESSAGE, + number=28, + message='TrafficPolylineData', + ) + current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) + current_route_segment_end_point: fleetengine.TripWaypoint = proto.Field( + proto.MESSAGE, + number=24, + message=fleetengine.TripWaypoint, + ) + remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=18, + message=wrappers_pb2.Int32Value, + ) + eta_to_first_waypoint: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + remaining_time_seconds: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=25, + message=wrappers_pb2.Int32Value, + ) + waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( + proto.MESSAGE, + number=22, + message=fleetengine.TripWaypoint, + ) + waypoints_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=16, + message=timestamp_pb2.Timestamp, + ) + back_to_back_enabled: bool = proto.Field( + proto.BOOL, + number=23, + ) + navigation_status: fleetengine.NavigationStatus = proto.Field( + proto.ENUM, + number=26, + enum=fleetengine.NavigationStatus, + ) + device_settings: 'DeviceSettings' = proto.Field( + proto.MESSAGE, + number=27, + message='DeviceSettings', + ) + + +class BatteryInfo(proto.Message): + r"""Information about the device's battery. + + Attributes: + battery_status (google.maps.fleetengine_v1.types.BatteryStatus): + Status of the battery, whether full or + charging etc. + power_source (google.maps.fleetengine_v1.types.PowerSource): + Status of battery power source. + battery_percentage (float): + Current battery percentage [0-100]. + """ + + battery_status: 'BatteryStatus' = proto.Field( + proto.ENUM, + number=1, + enum='BatteryStatus', + ) + power_source: 'PowerSource' = proto.Field( + proto.ENUM, + number=2, + enum='PowerSource', + ) + battery_percentage: float = proto.Field( + proto.FLOAT, + number=3, + ) + + +class DeviceSettings(proto.Message): + r"""Information about various settings on the mobile device. + + Attributes: + location_power_save_mode (google.maps.fleetengine_v1.types.LocationPowerSaveMode): + How location features are set to behave on + the device when battery saver is on. + is_power_save_mode (bool): + Whether the device is currently in power save + mode. + is_interactive (bool): + Whether the device is in an interactive + state. + battery_info (google.maps.fleetengine_v1.types.BatteryInfo): + Information about the battery state. + """ + + location_power_save_mode: 'LocationPowerSaveMode' = proto.Field( + proto.ENUM, + number=1, + enum='LocationPowerSaveMode', + ) + is_power_save_mode: bool = proto.Field( + proto.BOOL, + number=2, + ) + is_interactive: bool = proto.Field( + proto.BOOL, + number=3, + ) + battery_info: 'BatteryInfo' = proto.Field( + proto.MESSAGE, + number=4, + message='BatteryInfo', + ) + + +class LicensePlate(proto.Message): + r"""The license plate information of the Vehicle. To avoid + storing personally-identifiable information, only the minimum + information about the license plate is stored as part of the + entity. + + Attributes: + country_code (str): + Required. CLDR Country/Region Code. For example, ``US`` for + United States, or ``IN`` for India. + last_character (str): + The last digit of the license plate or "-1" to denote no + numeric value is present in the license plate. + + - "ABC 1234" -> "4" + - "AB 123 CD" -> "3" + - "ABCDEF" -> "-1". + """ + + country_code: str = proto.Field( + proto.STRING, + number=1, + ) + last_character: str = proto.Field( + proto.STRING, + number=2, + ) + + +class VisualTrafficReportPolylineRendering(proto.Message): + r"""Describes how clients should color one portion of the + polyline along the route. + + Attributes: + road_stretch (MutableSequence[google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering.RoadStretch]): + Optional. Road stretches that should be + rendered along the polyline. Stretches are + guaranteed to not overlap, and do not + necessarily span the full route. + + In the absence of a road stretch to style, the + client should apply the default for the route. + """ + + class RoadStretch(proto.Message): + r"""One road stretch that should be rendered. + + Attributes: + style (google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering.RoadStretch.Style): + Required. The style to apply. + offset_meters (int): + Required. The style should be applied between + ``[offset_meters, offset_meters + length_meters)``. + length_meters (int): + Required. The length of the path where to + apply the style. + """ + class Style(proto.Enum): + r"""The traffic style, indicating traffic speed. + + Values: + STYLE_UNSPECIFIED (0): + No style selected. + SLOWER_TRAFFIC (1): + Traffic is slowing down. + TRAFFIC_JAM (2): + There is a traffic jam. + """ + STYLE_UNSPECIFIED = 0 + SLOWER_TRAFFIC = 1 + TRAFFIC_JAM = 2 + + style: 'VisualTrafficReportPolylineRendering.RoadStretch.Style' = proto.Field( + proto.ENUM, + number=1, + enum='VisualTrafficReportPolylineRendering.RoadStretch.Style', + ) + offset_meters: int = proto.Field( + proto.INT32, + number=2, + ) + length_meters: int = proto.Field( + proto.INT32, + number=3, + ) + + road_stretch: MutableSequence[RoadStretch] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=RoadStretch, + ) + + +class TrafficPolylineData(proto.Message): + r"""Traffic conditions along the expected vehicle route. + + Attributes: + traffic_rendering (google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering): + A polyline rendering of how fast traffic is + for all regions along one stretch of a customer + ride. + """ + + traffic_rendering: 'VisualTrafficReportPolylineRendering' = proto.Field( + proto.MESSAGE, + number=1, + message='VisualTrafficReportPolylineRendering', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini b/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-fleetengine/v1/noxfile.py b/owl-bot-staging/google-maps-fleetengine/v1/noxfile.py new file mode 100644 index 000000000000..4bc01f860119 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine' + +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/fleetengine_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/fleetengine_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-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py new file mode 100644 index 000000000000..ab45c932839a --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_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 CreateTrip +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_CreateTrip_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_create_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateTripRequest( + parent="parent_value", + trip_id="trip_id_value", + ) + + # Make the request + response = await client.create_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_CreateTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py new file mode 100644 index 000000000000..c4644b1862d3 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_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 CreateTrip +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_CreateTrip_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_create_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateTripRequest( + parent="parent_value", + trip_id="trip_id_value", + ) + + # Make the request + response = client.create_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_CreateTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py new file mode 100644 index 000000000000..0c2d7cd52ca9 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_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 GetTrip +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_GetTrip_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_get_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetTripRequest( + name="name_value", + ) + + # Make the request + response = await client.get_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_GetTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py new file mode 100644 index 000000000000..d3bfcfe709c0 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_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 GetTrip +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_GetTrip_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_get_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetTripRequest( + name="name_value", + ) + + # Make the request + response = client.get_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_GetTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py new file mode 100644 index 000000000000..8e32e9b6f3a9 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_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 ReportBillableTrip +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_ReportBillableTrip_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_report_billable_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.ReportBillableTripRequest( + name="name_value", + country_code="country_code_value", + ) + + # Make the request + await client.report_billable_trip(request=request) + + +# [END fleetengine_v1_generated_TripService_ReportBillableTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py new file mode 100644 index 000000000000..0ea03be8d902 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_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 ReportBillableTrip +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_ReportBillableTrip_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_report_billable_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.ReportBillableTripRequest( + name="name_value", + country_code="country_code_value", + ) + + # Make the request + client.report_billable_trip(request=request) + + +# [END fleetengine_v1_generated_TripService_ReportBillableTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py new file mode 100644 index 000000000000..5cd30f613daa --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_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 SearchTrips +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_SearchTrips_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_search_trips(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchTripsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.search_trips(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END fleetengine_v1_generated_TripService_SearchTrips_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py new file mode 100644 index 000000000000..dfbbfe500c95 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_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 SearchTrips +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_SearchTrips_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_search_trips(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchTripsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.search_trips(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END fleetengine_v1_generated_TripService_SearchTrips_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py new file mode 100644 index 000000000000..f67869a7143d --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_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 UpdateTrip +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_UpdateTrip_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_update_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateTripRequest( + name="name_value", + ) + + # Make the request + response = await client.update_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_UpdateTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py new file mode 100644 index 000000000000..fc41bd61a318 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_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 UpdateTrip +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_UpdateTrip_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_update_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateTripRequest( + name="name_value", + ) + + # Make the request + response = client.update_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_UpdateTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py new file mode 100644 index 000000000000..851946fd95a3 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_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 CreateVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_CreateVehicle_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_create_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateVehicleRequest( + parent="parent_value", + vehicle_id="vehicle_id_value", + ) + + # Make the request + response = await client.create_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_CreateVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py new file mode 100644 index 000000000000..24820678e5df --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_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 CreateVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_CreateVehicle_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_create_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateVehicleRequest( + parent="parent_value", + vehicle_id="vehicle_id_value", + ) + + # Make the request + response = client.create_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_CreateVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py new file mode 100644 index 000000000000..39c32d3272f7 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_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 GetVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_GetVehicle_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_get_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_GetVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py new file mode 100644 index 000000000000..3b852145ad23 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_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 GetVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_GetVehicle_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_get_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.get_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_GetVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py new file mode 100644 index 000000000000..969785d1f002 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_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 ListVehicles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_ListVehicles_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_list_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.ListVehiclesRequest( + parent="parent_value", + vehicle_type_categories=['PEDESTRIAN'], + ) + + # Make the request + page_result = client.list_vehicles(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END fleetengine_v1_generated_VehicleService_ListVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py new file mode 100644 index 000000000000..32329e16b91d --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_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 ListVehicles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_ListVehicles_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_list_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.ListVehiclesRequest( + parent="parent_value", + vehicle_type_categories=['PEDESTRIAN'], + ) + + # Make the request + page_result = client.list_vehicles(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END fleetengine_v1_generated_VehicleService_ListVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py new file mode 100644 index 000000000000..72dbea4e2525 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_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 SearchVehicles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_SearchVehicles_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_search_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchVehiclesRequest( + parent="parent_value", + pickup_radius_meters=2146, + count=553, + minimum_capacity=1705, + trip_types=['EXCLUSIVE'], + order_by="COST", + ) + + # Make the request + response = await client.search_vehicles(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_SearchVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py new file mode 100644 index 000000000000..9d2ea3d1cd7f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_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 SearchVehicles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_SearchVehicles_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_search_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchVehiclesRequest( + parent="parent_value", + pickup_radius_meters=2146, + count=553, + minimum_capacity=1705, + trip_types=['EXCLUSIVE'], + order_by="COST", + ) + + # Make the request + response = client.search_vehicles(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_SearchVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py new file mode 100644 index 000000000000..83ef89e4566b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_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 UpdateVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_UpdateVehicle_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_update_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.update_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_UpdateVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py new file mode 100644 index 000000000000..9b5d10d7db81 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_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 UpdateVehicleAttributes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +async def sample_update_vehicle_attributes(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + attributes = fleetengine_v1.VehicleAttribute() + attributes.string_value = "string_value_value" + + request = fleetengine_v1.UpdateVehicleAttributesRequest( + name="name_value", + attributes=attributes, + ) + + # Make the request + response = await client.update_vehicle_attributes(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py new file mode 100644 index 000000000000..ae0d5f325998 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_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 UpdateVehicleAttributes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_update_vehicle_attributes(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + attributes = fleetengine_v1.VehicleAttribute() + attributes.string_value = "string_value_value" + + request = fleetengine_v1.UpdateVehicleAttributesRequest( + name="name_value", + attributes=attributes, + ) + + # Make the request + response = client.update_vehicle_attributes(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py new file mode 100644 index 000000000000..f1ae021b0f99 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_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 UpdateVehicle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_UpdateVehicle_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 fleetengine_v1 + + +def sample_update_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.update_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_UpdateVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json new file mode 100644 index 000000000000..b0139d358773 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json @@ -0,0 +1,1692 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "maps.fleetengine.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-fleetengine", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.create_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.CreateTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "CreateTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.CreateTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "create_trip" + }, + "description": "Sample for CreateTrip", + "file": "fleetengine_v1_generated_trip_service_create_trip_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_CreateTrip_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": "fleetengine_v1_generated_trip_service_create_trip_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.create_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.CreateTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "CreateTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.CreateTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "create_trip" + }, + "description": "Sample for CreateTrip", + "file": "fleetengine_v1_generated_trip_service_create_trip_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_CreateTrip_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": "fleetengine_v1_generated_trip_service_create_trip_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.get_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.GetTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "GetTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.GetTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "get_trip" + }, + "description": "Sample for GetTrip", + "file": "fleetengine_v1_generated_trip_service_get_trip_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_GetTrip_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": "fleetengine_v1_generated_trip_service_get_trip_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.get_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.GetTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "GetTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.GetTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "get_trip" + }, + "description": "Sample for GetTrip", + "file": "fleetengine_v1_generated_trip_service_get_trip_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_GetTrip_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": "fleetengine_v1_generated_trip_service_get_trip_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.report_billable_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.ReportBillableTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "ReportBillableTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.ReportBillableTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "report_billable_trip" + }, + "description": "Sample for ReportBillableTrip", + "file": "fleetengine_v1_generated_trip_service_report_billable_trip_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_ReportBillableTrip_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_report_billable_trip_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.report_billable_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.ReportBillableTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "ReportBillableTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.ReportBillableTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "report_billable_trip" + }, + "description": "Sample for ReportBillableTrip", + "file": "fleetengine_v1_generated_trip_service_report_billable_trip_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_ReportBillableTrip_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_report_billable_trip_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.search_trips", + "method": { + "fullName": "maps.fleetengine.v1.TripService.SearchTrips", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "SearchTrips" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.SearchTripsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsAsyncPager", + "shortName": "search_trips" + }, + "description": "Sample for SearchTrips", + "file": "fleetengine_v1_generated_trip_service_search_trips_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_SearchTrips_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": "fleetengine_v1_generated_trip_service_search_trips_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.search_trips", + "method": { + "fullName": "maps.fleetengine.v1.TripService.SearchTrips", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "SearchTrips" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.SearchTripsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsPager", + "shortName": "search_trips" + }, + "description": "Sample for SearchTrips", + "file": "fleetengine_v1_generated_trip_service_search_trips_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_SearchTrips_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": "fleetengine_v1_generated_trip_service_search_trips_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.update_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.UpdateTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "UpdateTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "update_trip" + }, + "description": "Sample for UpdateTrip", + "file": "fleetengine_v1_generated_trip_service_update_trip_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_UpdateTrip_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": "fleetengine_v1_generated_trip_service_update_trip_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.update_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.UpdateTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "UpdateTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "update_trip" + }, + "description": "Sample for UpdateTrip", + "file": "fleetengine_v1_generated_trip_service_update_trip_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_UpdateTrip_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": "fleetengine_v1_generated_trip_service_update_trip_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.create_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.CreateVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "CreateVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.CreateVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "create_vehicle" + }, + "description": "Sample for CreateVehicle", + "file": "fleetengine_v1_generated_vehicle_service_create_vehicle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_CreateVehicle_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": "fleetengine_v1_generated_vehicle_service_create_vehicle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.create_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.CreateVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "CreateVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.CreateVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "create_vehicle" + }, + "description": "Sample for CreateVehicle", + "file": "fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_CreateVehicle_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": "fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.get_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.GetVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "GetVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.GetVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "get_vehicle" + }, + "description": "Sample for GetVehicle", + "file": "fleetengine_v1_generated_vehicle_service_get_vehicle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_GetVehicle_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": "fleetengine_v1_generated_vehicle_service_get_vehicle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.get_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.GetVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "GetVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.GetVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "get_vehicle" + }, + "description": "Sample for GetVehicle", + "file": "fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_GetVehicle_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": "fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.list_vehicles", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.ListVehicles", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "ListVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.ListVehiclesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesAsyncPager", + "shortName": "list_vehicles" + }, + "description": "Sample for ListVehicles", + "file": "fleetengine_v1_generated_vehicle_service_list_vehicles_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_ListVehicles_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": "fleetengine_v1_generated_vehicle_service_list_vehicles_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.list_vehicles", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.ListVehicles", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "ListVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.ListVehiclesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesPager", + "shortName": "list_vehicles" + }, + "description": "Sample for ListVehicles", + "file": "fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_ListVehicles_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": "fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.search_vehicles", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.SearchVehicles", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "SearchVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", + "shortName": "search_vehicles" + }, + "description": "Sample for SearchVehicles", + "file": "fleetengine_v1_generated_vehicle_service_search_vehicles_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_SearchVehicles_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": "fleetengine_v1_generated_vehicle_service_search_vehicles_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.search_vehicles", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.SearchVehicles", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "SearchVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", + "shortName": "search_vehicles" + }, + "description": "Sample for SearchVehicles", + "file": "fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_SearchVehicles_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": "fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.update_vehicle_attributes", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleAttributes", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "UpdateVehicleAttributes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse", + "shortName": "update_vehicle_attributes" + }, + "description": "Sample for UpdateVehicleAttributes", + "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_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": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.update_vehicle_attributes", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleAttributes", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "UpdateVehicleAttributes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse", + "shortName": "update_vehicle_attributes" + }, + "description": "Sample for UpdateVehicleAttributes", + "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_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": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.update_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "UpdateVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "update_vehicle" + }, + "description": "Sample for UpdateVehicle", + "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicle_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": "fleetengine_v1_generated_vehicle_service_update_vehicle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.update_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "UpdateVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "update_vehicle" + }, + "description": "Sample for UpdateVehicle", + "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicle_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": "fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py b/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py new file mode 100644 index 000000000000..1a4c9837d26c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py @@ -0,0 +1,186 @@ +#! /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 fleetengineCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_trip': ('parent', 'trip_id', 'trip', 'header', ), + 'create_vehicle': ('parent', 'vehicle_id', 'vehicle', 'header', ), + 'get_trip': ('name', 'header', 'view', 'current_route_segment_version', 'remaining_waypoints_version', 'route_format_type', 'current_route_segment_traffic_version', 'remaining_waypoints_route_version', ), + 'get_vehicle': ('name', 'header', 'current_route_segment_version', 'waypoints_version', ), + 'list_vehicles': ('parent', 'vehicle_type_categories', 'header', 'page_size', 'page_token', 'minimum_capacity', 'trip_types', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'vehicle_state', 'on_trip_only', 'filter', 'viewport', ), + 'report_billable_trip': ('name', 'country_code', 'platform', 'related_ids', 'solution_type', ), + 'search_trips': ('parent', 'header', 'vehicle_id', 'active_trips_only', 'page_size', 'page_token', 'minimum_staleness', ), + 'search_vehicles': ('parent', 'pickup_point', 'pickup_radius_meters', 'count', 'minimum_capacity', 'trip_types', 'vehicle_types', 'order_by', 'header', 'dropoff_point', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'include_back_to_back', 'trip_id', 'current_trips_present', 'filter', ), + 'update_trip': ('name', 'trip', 'update_mask', 'header', ), + 'update_vehicle': ('name', 'vehicle', 'update_mask', 'header', ), + 'update_vehicle_attributes': ('name', 'attributes', 'header', ), + } + + 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=fleetengineCallTransformer(), +): + """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 fleetengine 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-fleetengine/v1/setup.py b/owl-bot-staging/google-maps-fleetengine/v1/setup.py new file mode 100644 index 000000000000..b805ff698554 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine' + + +description = "Google Maps Fleetengine API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/fleetengine/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-fleetengine" + +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-fleetengine/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..277853c664a0 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/tests/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py new file mode 100644 index 000000000000..ce5c3361748e --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py @@ -0,0 +1,3085 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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.fleetengine_v1.services.trip_service import TripServiceAsyncClient +from google.maps.fleetengine_v1.services.trip_service import TripServiceClient +from google.maps.fleetengine_v1.services.trip_service import pagers +from google.maps.fleetengine_v1.services.trip_service import transports +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import header +from google.maps.fleetengine_v1.types import traffic +from google.maps.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_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 TripServiceClient._get_default_mtls_endpoint(None) is None + assert TripServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TripServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TripServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TripServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TripServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert TripServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert TripServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert TripServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + TripServiceClient._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 TripServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert TripServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert TripServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + TripServiceClient._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 TripServiceClient._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 TripServiceClient._get_client_cert_source(None, False) is None + assert TripServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert TripServiceClient._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 TripServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert TripServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = TripServiceClient._DEFAULT_UNIVERSE + default_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert TripServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert TripServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TripServiceClient.DEFAULT_MTLS_ENDPOINT + assert TripServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert TripServiceClient._get_api_endpoint(None, None, default_universe, "always") == TripServiceClient.DEFAULT_MTLS_ENDPOINT + assert TripServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TripServiceClient.DEFAULT_MTLS_ENDPOINT + assert TripServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert TripServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + TripServiceClient._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 TripServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert TripServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert TripServiceClient._get_universe_domain(None, None) == TripServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + TripServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (TripServiceClient, "grpc"), + (TripServiceAsyncClient, "grpc_asyncio"), +]) +def test_trip_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 == ( + 'fleetengine.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.TripServiceGrpcTransport, "grpc"), + (transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_trip_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", [ + (TripServiceClient, "grpc"), + (TripServiceAsyncClient, "grpc_asyncio"), +]) +def test_trip_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 == ( + 'fleetengine.googleapis.com:443' + ) + + +def test_trip_service_client_get_transport_class(): + transport = TripServiceClient.get_transport_class() + available_transports = [ + transports.TripServiceGrpcTransport, + ] + assert transport in available_transports + + transport = TripServiceClient.get_transport_class("grpc") + assert transport == transports.TripServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) +def test_trip_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(TripServiceClient, '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(TripServiceClient, '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", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", "true"), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", "false"), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_trip_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", [ + TripServiceClient, TripServiceAsyncClient +]) +@mock.patch.object(TripServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TripServiceAsyncClient)) +def test_trip_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", [ + TripServiceClient, TripServiceAsyncClient +]) +@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) +def test_trip_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = TripServiceClient._DEFAULT_UNIVERSE + default_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TripServiceClient._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", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_trip_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", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", grpc_helpers), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_trip_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_trip_service_client_client_options_from_dict(): + with mock.patch('google.maps.fleetengine_v1.services.trip_service.transports.TripServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TripServiceClient( + 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", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", grpc_helpers), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_trip_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( + "fleetengine.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="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + trip_api.CreateTripRequest, + dict, +]) +def test_create_trip(request_type, transport: str = 'grpc'): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + ) + response = client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.CreateTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +def test_create_trip_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = trip_api.CreateTripRequest( + parent='parent_value', + trip_id='trip_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_trip(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.CreateTripRequest( + parent='parent_value', + trip_id='trip_id_value', + ) + +def test_create_trip_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_trip in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_trip] = mock_rpc + request = {} + client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_trip(request) + + # Establish that a new wrapper 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_trip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_trip in client._client._transport._wrapped_methods + + # 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_trip] = mock_rpc + + request = {} + await client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_trip(request) + + # Establish that a new wrapper 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_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.CreateTripRequest): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + response = await client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.CreateTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +@pytest.mark.asyncio +async def test_create_trip_async_from_dict(): + await test_create_trip_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + trip_api.GetTripRequest, + dict, +]) +def test_get_trip(request_type, transport: str = 'grpc'): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + ) + response = client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.GetTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +def test_get_trip_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = trip_api.GetTripRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_trip(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.GetTripRequest( + name='name_value', + ) + +def test_get_trip_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_trip in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_trip] = mock_rpc + request = {} + client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_trip(request) + + # Establish that a new wrapper 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_trip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_trip in client._client._transport._wrapped_methods + + # 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_trip] = mock_rpc + + request = {} + await client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_trip(request) + + # Establish that a new wrapper 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_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.GetTripRequest): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + response = await client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.GetTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +@pytest.mark.asyncio +async def test_get_trip_async_from_dict(): + await test_get_trip_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + trip_api.ReportBillableTripRequest, + dict, +]) +def test_report_billable_trip(request_type, transport: str = 'grpc'): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.ReportBillableTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_report_billable_trip_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = trip_api.ReportBillableTripRequest( + name='name_value', + country_code='country_code_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.report_billable_trip(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.ReportBillableTripRequest( + name='name_value', + country_code='country_code_value', + ) + +def test_report_billable_trip_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.report_billable_trip in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.report_billable_trip] = mock_rpc + request = {} + client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.report_billable_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_report_billable_trip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.report_billable_trip in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.report_billable_trip] = mock_rpc + + request = {} + await client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.report_billable_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_report_billable_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.ReportBillableTripRequest): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.ReportBillableTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_report_billable_trip_async_from_dict(): + await test_report_billable_trip_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + trip_api.SearchTripsRequest, + dict, +]) +def test_search_trips(request_type, transport: str = 'grpc'): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_trips), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trip_api.SearchTripsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.SearchTripsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchTripsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_trips_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = trip_api.SearchTripsRequest( + parent='parent_value', + vehicle_id='vehicle_id_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_trips), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_trips(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.SearchTripsRequest( + parent='parent_value', + vehicle_id='vehicle_id_value', + page_token='page_token_value', + ) + +def test_search_trips_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_trips in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_trips] = mock_rpc + request = {} + client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_trips(request) + + # Establish that a new wrapper 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_trips_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_trips in client._client._transport._wrapped_methods + + # 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_trips] = mock_rpc + + request = {} + await client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.search_trips(request) + + # Establish that a new wrapper 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_trips_async(transport: str = 'grpc_asyncio', request_type=trip_api.SearchTripsRequest): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_trips), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.SearchTripsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchTripsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_trips_async_from_dict(): + await test_search_trips_async(request_type=dict) + + +def test_search_trips_pager(transport_name: str = "grpc"): + client = TripServiceClient( + 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_trips), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + trips.Trip(), + ], + next_page_token='abc', + ), + trip_api.SearchTripsResponse( + trips=[], + next_page_token='def', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + ], + next_page_token='ghi', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.search_trips(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, trips.Trip) + for i in results) +def test_search_trips_pages(transport_name: str = "grpc"): + client = TripServiceClient( + 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_trips), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + trips.Trip(), + ], + next_page_token='abc', + ), + trip_api.SearchTripsResponse( + trips=[], + next_page_token='def', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + ], + next_page_token='ghi', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + ], + ), + RuntimeError, + ) + pages = list(client.search_trips(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_trips_async_pager(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + trips.Trip(), + ], + next_page_token='abc', + ), + trip_api.SearchTripsResponse( + trips=[], + next_page_token='def', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + ], + next_page_token='ghi', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_trips(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, trips.Trip) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_trips_async_pages(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + trips.Trip(), + ], + next_page_token='abc', + ), + trip_api.SearchTripsResponse( + trips=[], + next_page_token='def', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + ], + next_page_token='ghi', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + ], + ), + 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_trips(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", [ + trip_api.UpdateTripRequest, + dict, +]) +def test_update_trip(request_type, transport: str = 'grpc'): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + ) + response = client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.UpdateTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +def test_update_trip_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = trip_api.UpdateTripRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_trip(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.UpdateTripRequest( + name='name_value', + ) + +def test_update_trip_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_trip in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_trip] = mock_rpc + request = {} + client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_trip(request) + + # Establish that a new wrapper 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_trip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_trip in client._client._transport._wrapped_methods + + # 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_trip] = mock_rpc + + request = {} + await client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_trip(request) + + # Establish that a new wrapper 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_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.UpdateTripRequest): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + response = await client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.UpdateTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +@pytest.mark.asyncio +async def test_update_trip_async_from_dict(): + await test_update_trip_async(request_type=dict) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TripServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TripServiceClient( + 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 = TripServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TripServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TripServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TripServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TripServiceGrpcTransport, + transports.TripServiceGrpcAsyncIOTransport, +]) +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 = TripServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TripServiceClient( + 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_trip_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.create_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.CreateTripRequest() + + assert args[0] == request_msg + + +# This 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_trip_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.get_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.GetTripRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_report_billable_trip_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + call.return_value = None + client.report_billable_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.ReportBillableTripRequest() + + assert args[0] == request_msg + + +# This 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_trips_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + call.return_value = trip_api.SearchTripsResponse() + client.search_trips(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.SearchTripsRequest() + + assert args[0] == request_msg + + +# This 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_trip_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.update_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.UpdateTripRequest() + + assert args[0] == request_msg + + +def test_create_trip_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.create_trip(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.CreateTripRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_trip_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.get_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.GetTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_report_billable_trip_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + call.return_value = None + client.report_billable_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.ReportBillableTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_search_trips_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + call.return_value = trip_api.SearchTripsResponse() + client.search_trips(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.SearchTripsRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_trip_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.update_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.UpdateTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_kind_grpc_asyncio(): + transport = TripServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TripServiceAsyncClient( + 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_trip_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.create_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.CreateTripRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_trip_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.get_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.GetTripRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_report_billable_trip_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.report_billable_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.ReportBillableTripRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_trips_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( + next_page_token='next_page_token_value', + )) + await client.search_trips(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.SearchTripsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_trip_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.update_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.UpdateTripRequest() + + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_create_trip_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.create_trip(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.CreateTripRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_get_trip_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.get_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.GetTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_report_billable_trip_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.report_billable_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.ReportBillableTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_search_trips_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( + next_page_token='next_page_token_value', + )) + await client.search_trips(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.SearchTripsRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_update_trip_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.update_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.UpdateTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TripServiceGrpcTransport, + ) + +def test_trip_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TripServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_trip_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.fleetengine_v1.services.trip_service.transports.TripServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TripServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_trip', + 'get_trip', + 'report_billable_trip', + 'search_trips', + 'update_trip', + ) + 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_trip_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.maps.fleetengine_v1.services.trip_service.transports.TripServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TripServiceTransport( + 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_trip_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.maps.fleetengine_v1.services.trip_service.transports.TripServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TripServiceTransport() + adc.assert_called_once() + + +def test_trip_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) + TripServiceClient() + 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.TripServiceGrpcTransport, + transports.TripServiceGrpcAsyncIOTransport, + ], +) +def test_trip_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/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TripServiceGrpcTransport, + transports.TripServiceGrpcAsyncIOTransport, + ], +) +def test_trip_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.TripServiceGrpcTransport, grpc_helpers), + (transports.TripServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_trip_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( + "fleetengine.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="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) +def test_trip_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_trip_service_host_no_port(transport_name): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_trip_service_host_with_port(transport_name): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:8000' + ) + +def test_trip_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TripServiceGrpcTransport( + 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_trip_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TripServiceGrpcAsyncIOTransport( + 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.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) +def test_trip_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.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) +def test_trip_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_trip_path(): + provider = "squid" + trip = "clam" + expected = "providers/{provider}/trips/{trip}".format(provider=provider, trip=trip, ) + actual = TripServiceClient.trip_path(provider, trip) + assert expected == actual + + +def test_parse_trip_path(): + expected = { + "provider": "whelk", + "trip": "octopus", + } + path = TripServiceClient.trip_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.parse_trip_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TripServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = TripServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = TripServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = TripServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TripServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = TripServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = TripServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = TripServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.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 = TripServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = TripServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.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.TripServiceTransport, '_prep_wrapped_messages') as prep: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TripServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = TripServiceClient.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 = TripServiceClient( + 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 = TripServiceAsyncClient( + 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_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = TripServiceClient( + 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", [ + (TripServiceClient, transports.TripServiceGrpcTransport), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport), +]) +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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py new file mode 100644 index 000000000000..39ac26e13afb --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py @@ -0,0 +1,3340 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 + +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.fleetengine_v1.services.vehicle_service import VehicleServiceAsyncClient +from google.maps.fleetengine_v1.services.vehicle_service import VehicleServiceClient +from google.maps.fleetengine_v1.services.vehicle_service import pagers +from google.maps.fleetengine_v1.services.vehicle_service import transports +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import header +from google.maps.fleetengine_v1.types import traffic +from google.maps.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_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 VehicleServiceClient._get_default_mtls_endpoint(None) is None + assert VehicleServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VehicleServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VehicleServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VehicleServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VehicleServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert VehicleServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + VehicleServiceClient._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 VehicleServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert VehicleServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + VehicleServiceClient._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 VehicleServiceClient._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 VehicleServiceClient._get_client_cert_source(None, False) is None + assert VehicleServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert VehicleServiceClient._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 VehicleServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert VehicleServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = VehicleServiceClient._DEFAULT_UNIVERSE + default_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert VehicleServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert VehicleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "always") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + assert VehicleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + assert VehicleServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + VehicleServiceClient._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 VehicleServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert VehicleServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert VehicleServiceClient._get_universe_domain(None, None) == VehicleServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + VehicleServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (VehicleServiceClient, "grpc"), + (VehicleServiceAsyncClient, "grpc_asyncio"), +]) +def test_vehicle_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 == ( + 'fleetengine.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VehicleServiceGrpcTransport, "grpc"), + (transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_vehicle_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", [ + (VehicleServiceClient, "grpc"), + (VehicleServiceAsyncClient, "grpc_asyncio"), +]) +def test_vehicle_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 == ( + 'fleetengine.googleapis.com:443' + ) + + +def test_vehicle_service_client_get_transport_class(): + transport = VehicleServiceClient.get_transport_class() + available_transports = [ + transports.VehicleServiceGrpcTransport, + ] + assert transport in available_transports + + transport = VehicleServiceClient.get_transport_class("grpc") + assert transport == transports.VehicleServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) +def test_vehicle_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(VehicleServiceClient, '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(VehicleServiceClient, '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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", "true"), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", "false"), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_vehicle_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", [ + VehicleServiceClient, VehicleServiceAsyncClient +]) +@mock.patch.object(VehicleServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VehicleServiceAsyncClient)) +def test_vehicle_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", [ + VehicleServiceClient, VehicleServiceAsyncClient +]) +@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) +def test_vehicle_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = VehicleServiceClient._DEFAULT_UNIVERSE + default_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = VehicleServiceClient._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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_vehicle_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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", grpc_helpers), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_vehicle_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_vehicle_service_client_client_options_from_dict(): + with mock.patch('google.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VehicleServiceClient( + 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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", grpc_helpers), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_vehicle_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( + "fleetengine.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="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.CreateVehicleRequest, + dict, +]) +def test_create_vehicle(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + ) + response = client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.CreateVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +def test_create_vehicle_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = vehicle_api.CreateVehicleRequest( + parent='parent_value', + vehicle_id='vehicle_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_vehicle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.CreateVehicleRequest( + parent='parent_value', + vehicle_id='vehicle_id_value', + ) + +def test_create_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_vehicle] = mock_rpc + request = {} + client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_vehicle(request) + + # Establish that a new wrapper 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_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_vehicle in client._client._transport._wrapped_methods + + # 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_vehicle] = mock_rpc + + request = {} + await client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_vehicle(request) + + # Establish that a new wrapper 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_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.CreateVehicleRequest): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + response = await client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.CreateVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +@pytest.mark.asyncio +async def test_create_vehicle_async_from_dict(): + await test_create_vehicle_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.GetVehicleRequest, + dict, +]) +def test_get_vehicle(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + ) + response = client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.GetVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +def test_get_vehicle_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = vehicle_api.GetVehicleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_vehicle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.GetVehicleRequest( + name='name_value', + ) + +def test_get_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_vehicle] = mock_rpc + request = {} + client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_vehicle(request) + + # Establish that a new wrapper 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_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_vehicle in client._client._transport._wrapped_methods + + # 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_vehicle] = mock_rpc + + request = {} + await client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_vehicle(request) + + # Establish that a new wrapper 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_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.GetVehicleRequest): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + response = await client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.GetVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +@pytest.mark.asyncio +async def test_get_vehicle_async_from_dict(): + await test_get_vehicle_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.UpdateVehicleRequest, + dict, +]) +def test_update_vehicle(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + ) + response = client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.UpdateVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +def test_update_vehicle_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = vehicle_api.UpdateVehicleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_vehicle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.UpdateVehicleRequest( + name='name_value', + ) + +def test_update_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_vehicle] = mock_rpc + request = {} + client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_vehicle(request) + + # Establish that a new wrapper 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_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_vehicle in client._client._transport._wrapped_methods + + # 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_vehicle] = mock_rpc + + request = {} + await client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_vehicle(request) + + # Establish that a new wrapper 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_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.UpdateVehicleRequest): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + response = await client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.UpdateVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +@pytest.mark.asyncio +async def test_update_vehicle_async_from_dict(): + await test_update_vehicle_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.UpdateVehicleAttributesRequest, + dict, +]) +def test_update_vehicle_attributes(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicle_attributes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicle_api.UpdateVehicleAttributesResponse( + ) + response = client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.UpdateVehicleAttributesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicle_api.UpdateVehicleAttributesResponse) + + +def test_update_vehicle_attributes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = vehicle_api.UpdateVehicleAttributesRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_vehicle_attributes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.UpdateVehicleAttributesRequest( + name='name_value', + ) + +def test_update_vehicle_attributes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_vehicle_attributes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_vehicle_attributes] = mock_rpc + request = {} + client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_vehicle_attributes(request) + + # Establish that a new wrapper 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_vehicle_attributes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_vehicle_attributes in client._client._transport._wrapped_methods + + # 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_vehicle_attributes] = mock_rpc + + request = {} + await client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_vehicle_attributes(request) + + # Establish that a new wrapper 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_vehicle_attributes_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.UpdateVehicleAttributesRequest): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicle_attributes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( + )) + response = await client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.UpdateVehicleAttributesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicle_api.UpdateVehicleAttributesResponse) + + +@pytest.mark.asyncio +async def test_update_vehicle_attributes_async_from_dict(): + await test_update_vehicle_attributes_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.ListVehiclesRequest, + dict, +]) +def test_list_vehicles(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicle_api.ListVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.ListVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVehiclesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_vehicles_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = vehicle_api.ListVehiclesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_vehicles(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.ListVehiclesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_vehicles_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_vehicles in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_vehicles] = mock_rpc + request = {} + client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_vehicles(request) + + # Establish that a new wrapper 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_vehicles_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_vehicles in client._client._transport._wrapped_methods + + # 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_vehicles] = mock_rpc + + request = {} + await client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_vehicles(request) + + # Establish that a new wrapper 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_vehicles_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.ListVehiclesRequest): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.ListVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVehiclesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_vehicles_async_from_dict(): + await test_list_vehicles_async(request_type=dict) + + +def test_list_vehicles_pager(transport_name: str = "grpc"): + client = VehicleServiceClient( + 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_vehicles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + next_page_token='abc', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[], + next_page_token='def', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + ], + next_page_token='ghi', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_vehicles(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, vehicles.Vehicle) + for i in results) +def test_list_vehicles_pages(transport_name: str = "grpc"): + client = VehicleServiceClient( + 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_vehicles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + next_page_token='abc', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[], + next_page_token='def', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + ], + next_page_token='ghi', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + ), + RuntimeError, + ) + pages = list(client.list_vehicles(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_vehicles_async_pager(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + next_page_token='abc', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[], + next_page_token='def', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + ], + next_page_token='ghi', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_vehicles(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, vehicles.Vehicle) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_vehicles_async_pages(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + next_page_token='abc', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[], + next_page_token='def', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + ], + next_page_token='ghi', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + ), + 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_vehicles(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", [ + vehicle_api.SearchVehiclesRequest, + dict, +]) +def test_search_vehicles(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicle_api.SearchVehiclesResponse( + ) + response = client.search_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.SearchVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicle_api.SearchVehiclesResponse) + + +def test_search_vehicles_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = vehicle_api.SearchVehiclesRequest( + parent='parent_value', + trip_id='trip_id_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_vehicles(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.SearchVehiclesRequest( + parent='parent_value', + trip_id='trip_id_value', + filter='filter_value', + ) + +def test_search_vehicles_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_vehicles in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_vehicles] = mock_rpc + request = {} + client.search_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_vehicles(request) + + # Establish that a new wrapper 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_vehicles_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_vehicles in client._client._transport._wrapped_methods + + # 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_vehicles] = mock_rpc + + request = {} + await client.search_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.search_vehicles(request) + + # Establish that a new wrapper 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_vehicles_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.SearchVehiclesRequest): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( + )) + response = await client.search_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.SearchVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicle_api.SearchVehiclesResponse) + + +@pytest.mark.asyncio +async def test_search_vehicles_async_from_dict(): + await test_search_vehicles_async(request_type=dict) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VehicleServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = VehicleServiceClient( + 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 = VehicleServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VehicleServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VehicleServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VehicleServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VehicleServiceGrpcTransport, + transports.VehicleServiceGrpcAsyncIOTransport, +]) +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 = VehicleServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = VehicleServiceClient( + 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_vehicle_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.create_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.CreateVehicleRequest() + + assert args[0] == request_msg + + +# This 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_vehicle_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.get_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.GetVehicleRequest() + + assert args[0] == request_msg + + +# This 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_vehicle_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.update_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleRequest() + + assert args[0] == request_msg + + +# This 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_vehicle_attributes_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + call.return_value = vehicle_api.UpdateVehicleAttributesResponse() + client.update_vehicle_attributes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleAttributesRequest() + + assert args[0] == request_msg + + +# This 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_vehicles_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + call.return_value = vehicle_api.ListVehiclesResponse() + client.list_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.ListVehiclesRequest() + + assert args[0] == request_msg + + +# This 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_vehicles_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + call.return_value = vehicle_api.SearchVehiclesResponse() + client.search_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.SearchVehiclesRequest() + + assert args[0] == request_msg + + +def test_create_vehicle_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.create_vehicle(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.CreateVehicleRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_vehicle_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.get_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.GetVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_vehicle_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.update_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_vehicle_attributes_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + call.return_value = vehicle_api.UpdateVehicleAttributesResponse() + client.update_vehicle_attributes(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleAttributesRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_list_vehicles_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + call.return_value = vehicle_api.ListVehiclesResponse() + client.list_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.ListVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_search_vehicles_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + call.return_value = vehicle_api.SearchVehiclesResponse() + client.search_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_kind_grpc_asyncio(): + transport = VehicleServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = VehicleServiceAsyncClient( + 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_vehicle_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.create_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.CreateVehicleRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_vehicle_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.get_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.GetVehicleRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_vehicle_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.update_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_vehicle_attributes_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( + )) + await client.update_vehicle_attributes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleAttributesRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_vehicles_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.ListVehiclesRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_vehicles_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( + )) + await client.search_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.SearchVehiclesRequest() + + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_create_vehicle_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.create_vehicle(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.CreateVehicleRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_get_vehicle_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.get_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.GetVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_update_vehicle_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.update_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_update_vehicle_attributes_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( + )) + await client.update_vehicle_attributes(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleAttributesRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_list_vehicles_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.ListVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_search_vehicles_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( + )) + await client.search_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VehicleServiceGrpcTransport, + ) + +def test_vehicle_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VehicleServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_vehicle_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VehicleServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_vehicle', + 'get_vehicle', + 'update_vehicle', + 'update_vehicle_attributes', + 'list_vehicles', + 'search_vehicles', + ) + 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_vehicle_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.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VehicleServiceTransport( + 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_vehicle_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.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VehicleServiceTransport() + adc.assert_called_once() + + +def test_vehicle_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) + VehicleServiceClient() + 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.VehicleServiceGrpcTransport, + transports.VehicleServiceGrpcAsyncIOTransport, + ], +) +def test_vehicle_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/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VehicleServiceGrpcTransport, + transports.VehicleServiceGrpcAsyncIOTransport, + ], +) +def test_vehicle_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.VehicleServiceGrpcTransport, grpc_helpers), + (transports.VehicleServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_vehicle_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( + "fleetengine.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="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) +def test_vehicle_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_vehicle_service_host_no_port(transport_name): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_vehicle_service_host_with_port(transport_name): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:8000' + ) + +def test_vehicle_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VehicleServiceGrpcTransport( + 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_vehicle_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VehicleServiceGrpcAsyncIOTransport( + 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.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) +def test_vehicle_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.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) +def test_vehicle_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_vehicle_path(): + provider = "squid" + vehicle = "clam" + expected = "providers/{provider}/vehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) + actual = VehicleServiceClient.vehicle_path(provider, vehicle) + assert expected == actual + + +def test_parse_vehicle_path(): + expected = { + "provider": "whelk", + "vehicle": "octopus", + } + path = VehicleServiceClient.vehicle_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.parse_vehicle_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VehicleServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = VehicleServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = VehicleServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = VehicleServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VehicleServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = VehicleServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = VehicleServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = VehicleServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.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 = VehicleServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = VehicleServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.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.VehicleServiceTransport, '_prep_wrapped_messages') as prep: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VehicleServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = VehicleServiceClient.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 = VehicleServiceClient( + 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 = VehicleServiceAsyncClient( + 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_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = VehicleServiceClient( + 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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport), +]) +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-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..1b704ccdc187 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py @@ -0,0 +1,907 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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..4839d35b574d --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py @@ -0,0 +1,1258 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + MapsPlatformDatasetsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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..9bb35d1acfb2 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..4a399925dcf4 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py @@ -0,0 +1,403 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..96bc3c4511b3 --- /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,476 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..7b4183f36a90 --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py @@ -0,0 +1,787 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[maps_platform_datasets.CreateDatasetRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[maps_platform_datasets.DeleteDatasetRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[maps_platform_datasets.FetchDatasetErrorsRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[maps_platform_datasets.GetDatasetRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[maps_platform_datasets.ListDatasetsRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[maps_platform_datasets.UpdateDatasetMetadataRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..ef06d5878d41 --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..85e0ad71af9f --- /dev/null +++ b/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py @@ -0,0 +1,6146 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc"), + (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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..da49a941ee60 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places/__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.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.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', + '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..3c5e4f5b980e --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_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.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.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', +'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..87bbcc56beb4 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 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 + + +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, + + ) + + 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]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..d0cc9cedf8e3 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py @@ -0,0 +1,1073 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = PlacesClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + PlacesClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..c860eeb19cfa --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..56c4c2a197aa --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py @@ -0,0 +1,421 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..de4d01a7ca8f --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[places_service.AutocompletePlacesRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[places_service.GetPhotoMediaRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[places_service.GetPlaceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[places_service.SearchNearbyRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[places_service.SearchTextRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..013126637ac4 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 .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', + '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..36525aff107f --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py @@ -0,0 +1,1208 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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 reference +from google.maps.places_v1.types import review +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. + 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): + The business status for the place. + 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. + """ + 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. + """ + 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', + ) + + 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, + ) + + 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, + ) + + +__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..6abdcd07f4c2 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py @@ -0,0 +1,1316 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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. + """ + 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, + ) + + +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. + """ + + 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, + ) + + +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/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..121b25b6cd0b --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.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 __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. + """ + + 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, + ) + + +__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..74eb224b30a6 --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..886ede01a438 --- /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', ), + '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', ), + } + + 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..ffcaa117ba26 --- /dev/null +++ b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py @@ -0,0 +1,4498 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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_class,transport_name", [ + (PlacesClient, transports.PlacesGrpcTransport, "grpc"), + (PlacesClient, transports.PlacesRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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, + ) + 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 + + +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, + )) + 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 + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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, + )) + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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, + ) + + # Wrap 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 + 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 + + +@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 + 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 + 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 + 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 + 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..d21fc35ea40a --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py @@ -0,0 +1,548 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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..437dbebd654f --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py @@ -0,0 +1,898 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + RouteOptimizationClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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..166140484608 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py @@ -0,0 +1,394 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..1152e68b64ba --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..cc0cee239709 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[route_optimization_service.BatchOptimizeToursRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[route_optimization_service.OptimizeToursRequest, Sequence[Tuple[str, str]]]: + """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, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..c329d83ca2a2 --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..b292a592bc35 --- /dev/null +++ b/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py @@ -0,0 +1,2749 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc"), + (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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..6435ad0166ed --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.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 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.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', + '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..cdae66b5d7f6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.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', +'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..3315c0768267 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.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. +# +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 + + +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, + + ) + + 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]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..9276016535fb --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py @@ -0,0 +1,808 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = RoutesClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + RoutesClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..223360b6ba76 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.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 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 + +import grpc # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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..e4752aeff4c2 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py @@ -0,0 +1,395 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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..e62eb44c3f16 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.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 google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..56fa2a5f9cbb --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.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 .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 .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', + '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/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py new file mode 100644 index 000000000000..e2353aaa6c46 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py @@ -0,0 +1,787 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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 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): + A web-safe, base64-encoded route token that can be passed to + the Navigation SDK, that allows the Navigation SDK to + reconstruct the route during navigation, and, in the event + of rerouting, honor the original intention when you created + the route by calling ComputeRoutes. Customers should treat + this token as an opaque blob. It is not meant for reading or + mutating. 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. + """ + + 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 taking traffic conditions into consideration, + represented in text form. Note: If you did not request + traffic information, this value will be 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, + ) + + +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 taking traffic conditions into consideration + represented in text form. Note: If you did not request + traffic information, this value will be 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 will return 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..afa49bc25ec3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.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 + + +__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. + """ + ROUTE_LABEL_UNSPECIFIED = 0 + DEFAULT_ROUTE = 1 + DEFAULT_ROUTE_ALTERNATE = 2 + FUEL_EFFICIENT = 3 + + +__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..622d38e9f513 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py @@ -0,0 +1,713 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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. + 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. Routes labeled with + this value are determined to be optimized for + parameters such as fuel consumption. + """ + REFERENCE_ROUTE_UNSPECIFIED = 0 + FUEL_EFFICIENT = 1 + + 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. + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + FUEL_CONSUMPTION = 2 + TRAFFIC_ON_POLYLINE = 3 + HTML_FORMATTED_NAVIGATION_INSTRUCTIONS = 4 + + 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..b5ed5aca319c --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..313833af9740 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py @@ -0,0 +1,2389 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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..f554e566179b --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py @@ -0,0 +1,521 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..0b3a35d70db6 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py @@ -0,0 +1,869 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = SolarClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + SolarClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..86aa6371b33d --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..e0313519f457 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.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 inspect +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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..d1a651b34c9f --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py @@ -0,0 +1,548 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[solar_service.FindClosestBuildingInsightsRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[solar_service.GetDataLayersRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[solar_service.GetGeoTiffRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..ef51a4e54a98 --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..d2237d436239 --- /dev/null +++ b/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.py @@ -0,0 +1,2921 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (SolarClient, transports.SolarGrpcTransport, "grpc"), + (SolarClient, transports.SolarRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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..9899f408e93a --- /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,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. +# +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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..2d2824f1c687 --- /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,722 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + AccountIssueServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..122c88fcdd42 --- /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,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..be25edbe0083 --- /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,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. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_accounts_v1beta.types import accountissue +from .base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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..5b7a4183cac6 --- /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,292 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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..640f0e42e6c4 --- /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,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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[accountissue.ListAccountIssuesRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..898b44e47160 --- /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,588 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..01464cb91e35 --- /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,942 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = AccountTaxServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + AccountTaxServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..4560040913d8 --- /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,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..d7dc1b538d8f --- /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,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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..f4eb0d3545b4 --- /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,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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..cc25b5101013 --- /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,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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[account_tax.GetAccountTaxRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[account_tax.ListAccountTaxRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[gsma_account_tax.UpdateAccountTaxRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..faf90a89aa38 --- /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,852 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..98314e11111e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py @@ -0,0 +1,1223 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = AccountsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + AccountsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..6037fc9d2088 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.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. +# +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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..edf844a7f9cb --- /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,425 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..2bca1715b1bd --- /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,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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..a061c830710c --- /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,776 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[accounts.CreateAndConfigureAccountRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[accounts.DeleteAccountRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[accounts.GetAccountRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[accounts.ListAccountsRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[accounts.ListSubAccountsRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[accounts.UpdateAccountRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..dfaf606e984d --- /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,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. +# +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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..68ef500d876e --- /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,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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + AutofeedSettingsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..50ad69088c3d --- /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,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 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 + +import grpc # type: ignore + +from google.shopping.merchant_accounts_v1beta.types import autofeedsettings +from .base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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..05630ed2ec4c --- /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,324 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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..fdab84a4ef27 --- /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,388 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[autofeedsettings.GetAutofeedSettingsRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[autofeedsettings.UpdateAutofeedSettingsRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..8b90bcaca5a0 --- /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,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. +# +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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..417dd9888206 --- /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,811 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + BusinessIdentityServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..ebb5eb52c5cb --- /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,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_accounts_v1beta.types import businessidentity +from .base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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..8d25c39f5f65 --- /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,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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..adbecd00c412 --- /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,386 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[businessidentity.GetBusinessIdentityRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[businessidentity.UpdateBusinessIdentityRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..c00c2f39652f --- /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,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. +# +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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..43a447b9ae4c --- /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,811 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + BusinessInfoServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..a349e040aae9 --- /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,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 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 + +import grpc # type: ignore + +from google.shopping.merchant_accounts_v1beta.types import businessinfo +from .base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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..8d9e9033679a --- /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,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. +# +import inspect +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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..004e8f128d83 --- /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,383 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[businessinfo.GetBusinessInfoRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[businessinfo.UpdateBusinessInfoRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..aa73583a2cc2 --- /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,479 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..b523557c5e94 --- /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,834 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + EmailPreferencesServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..3f350752550c --- /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,314 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_accounts_v1beta.types import emailpreferences +from .base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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..01fd96f5467f --- /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,340 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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..2c5de44d62aa --- /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,394 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[emailpreferences.GetEmailPreferencesRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[emailpreferences.UpdateEmailPreferencesRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..ec74d511cd5c --- /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,622 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..df7e12407870 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py @@ -0,0 +1,977 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = HomepageServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + HomepageServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..a73262d323dc --- /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,363 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..08628e7ebbda --- /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,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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..970a5bde38cd --- /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,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 google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[homepage.ClaimHomepageRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[homepage.GetHomepageRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[homepage.UnclaimHomepageRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[gsma_homepage.UpdateHomepageRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..6da68a5145f7 --- /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,469 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..2bd3afa96ef8 --- /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,824 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + OnlineReturnPolicyServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..9fd3c13bd2b7 --- /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,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..e432f27210a4 --- /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,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_accounts_v1beta.types import online_return_policy +from .base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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..8c14071044b6 --- /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,329 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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..0aee419bb6a2 --- /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,392 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[online_return_policy.GetOnlineReturnPolicyRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..5db2fa88d13b --- /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,702 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..5fd5f217add7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py @@ -0,0 +1,1055 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ProgramsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..d57324925688 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..b01a291b0617 --- /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,361 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_accounts_v1beta.types import programs +from .base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..2b16365bfc5e --- /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,397 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..20bac24f2675 --- /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,633 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[programs.DisableProgramRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[programs.EnableProgramRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[programs.GetProgramRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[programs.ListProgramsRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..7a02c6bb9453 --- /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,806 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..45a0c3fac17c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = RegionsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + RegionsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..e83bfb7f2a9c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..8e3af8236efa --- /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,383 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..e896ab29d57f --- /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,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. +# +import inspect +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..055992213f8a --- /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,698 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[regions.CreateRegionRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[regions.DeleteRegionRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[regions.GetRegionRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[regions.ListRegionsRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[regions.UpdateRegionRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..df4b61a377b1 --- /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,430 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..3a236fd28324 --- /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,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. +# +from collections import OrderedDict +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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ShippingSettingsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..7a42cd6d2a9a --- /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,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_accounts_v1beta.types import shippingsettings +from .base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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..f63a8f4ad5ff --- /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,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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..8355e989f928 --- /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,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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[shippingsettings.GetShippingSettingsRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[shippingsettings.InsertShippingSettingsRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..0eb347e1fbce --- /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,504 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..bc097f3ec698 --- /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,877 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + TermsOfServiceAgreementStateServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..7e36e15daf7c --- /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,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate +from .base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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..c41fe7f7d06c --- /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,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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..21a9829cb18b --- /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,437 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..0edaaacf519d --- /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,509 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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..b3e6c55dc6ae --- /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,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. +# +from collections import OrderedDict +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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + TermsOfServiceServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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..798751c8879e --- /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,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..048b268abe9f --- /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,358 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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..8a73fd10954a --- /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,458 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[termsofservice.AcceptTermsOfServiceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[termsofservice.GetTermsOfServiceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[termsofservice.RetrieveLatestTermsOfServiceRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..abf841495e46 --- /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,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. +# +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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..55400105b84d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py @@ -0,0 +1,1147 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = UserServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + UserServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..ff8061acfe15 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..acc8704ccb00 --- /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,379 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..55fb5c24da67 --- /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,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 inspect +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..52497a33dd97 --- /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,677 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[gsma_user.CreateUserRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[user.DeleteUserRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[user.GetUserRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[user.ListUsersRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[gsma_user.UpdateUserRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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/merchant-accounts-v1beta-py.tar.gz b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/merchant-accounts-v1beta-py.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..9ee91f5d2371277e6fd0aa29d513248732bb848e GIT binary patch literal 360448 zcmbrEQ+F;*7iDAH$%%7f+qP}nc;cMcwr$(CZQHipZ-4z0y2iTOd(?H+T$3OY3g~|a z^s4*QX;UJGgOC5Sc8^lsl#+T8p!Y~SYw6YFJ`#R6a zA;0_jIspF;9{rNeZO!@pIyzoVz2o^lA76TaV0yU6j-3rauzPAaxkRIfSz z2KAn?KKW&ll`oxN9ye%z-wk;8eSbPFt$go|E*<_lH9xn(ATLcN3o1VSJx{DI)&9Q& z^YnL2Q&2@V1Jg_>FaQds;NC1o4Vy!NKA*21`1PG@CEqx5*6>d-iPFhPS7xyBt1`kFC$> zuzt_)e{R>vUEX-H1%G2lc6hMG)77&?cV=jC`w4zZZohda9ynyXN`FvmBf+`8R7+oB z1vHABZh3UvCAHiic|ec=H?l?+Bp*x>X2F=`eyi^`IHBVd4|E3yQ5pLJUO@MV2*kXU zLKJvH@7P|MWyf80ghBV5)Di11Cnv+h!2~D`J{j3|a+>{KkIz3hJDY>u@B(QSUJ@mW zIi8wNzKoP|QHNb) z2Z4Z*SI$XFTf)NpW?j)UK|fUYaYKor`Pj8JNa&R zJDa@jpH{yXzk9S^pUaybpNO};FS|V#p2%?MEU4b;reXYq*oO>a#<-1x6bndcMR56E z7|{okJOMtWrH^+k4|0pMiYWqaU7AVRqnvVP2xrm26D)kOk#%|cRdRyN)`>K{uUMe> z;Gp-FSWpM4X2EVaGY5)y>5H;yo(z(?Ky^4#^+jz|N!ecUQC5P-=n4;P?kuWyc6<~A^ymUH1N7A+ z1@J*!A}69;{;XgOFgm=hx$geLKRx*6(n6JjcP2Tb&{ai*_=B5m8fk>TBd}MGugy?; z7+Ta|iIQ5-2s_OpRd`7_K?RQtIS_q5WQrKTuPtPTh_GGMyQ{>mnii~3ImM^*aGIgO z=Waiqw0yMGt1P)>%2?Bckr5s#V2x-mXpwLTWmBG14>3|p#4e<9tYtF|Pb{#r)r`KQ zzO|wirpFm4jb~`=*r00oXOB>m1TtU-if>4hD+fNH@U)B7T4$3)I}j@HR)nQyWKoEB-5B8^QdUk~ zR`qH1*XUSusQr_+=sy2q`O`&*OVF1+Ftr7c9&+QPE05;Yl7XxncbIIMs!{`h0?MT|Y-y^DVE9{Y2m9&@ zPAqaT3DM0UK6j7#A87?Dg%)avuhgL1tEmJ}r~c8gR8};~wfGa77_ARlV&%g6x5aUZn;e?nSxyUC~*pnwwjqc*ig` z;WH*8O?W6Rjkfx#?s(%R@qI=F0B)u+;E0+U&VFK{FXnQHcQ88=PC zbk(VaRMK~F^d(_pB8UOVfSTwK4(B^)USg;fCsSPEf)%sStEv0dELdBF<{Q{{@3E%y zt0!PueyDU9&MQ@`w;3i6C_L>K+)O>TlE}sHJvt8>-AB-NX%&;gck7Jnxh67R`ni(fVC@yV$IMIWsd z0qx%b;oVR3d8(`SYTnXlYQAVqS0B|VC<)E)+f-F!3s1}Wql>rjVhasXB@9XY)HWeL zOYqEBS83dQrXFD|+9f3lnrc zZkdShn=s7T?=39x_w4Adq(3W+n=U8lKRfH{)>;+Gct0({GJ7=Tz04=sml99$ZgSr? z(|Xl8LEsf~v{XCw-mC8Av(2AjBks!cQOiQn$dx@|2qSe}Yy6kPE{j3Wm3nJ@#tuF6 z)a4H`_nArxs*3lJtq>9RHW{wJR>)zSEn@a-dlUq=Cxp*hA3}%9K8|RoO6;Frl7d>* zI)#f0^-mzb6j^IJ&^5a>O~({Ywy}Ixwi~@?W$fLpnN5G)KGi!D3W5&ZTCX#9I1s9< zcArgkJ)u-E$_$T^NAZp)aa?bjDpKiber(Eto=CjVeXI8i(Sr$!kOe-Cu+f@YH!ya! zJFRoKHoaBW6>Giw3Iv##|qEF*r$)@=HrDStf&)~l7 zZnIwxjxj!92(m@DLfwRs`a?t+24FF>+nnf2bSI5FJ`kG|@K2m*FZJ8RRdm3#etu@9 z-x@l8o&Lo3p4^F_coqNd4m5WBc6a=G8^88`Bd?pMwm)GXaC*&EC({@C6M-|PMfx()q$ zT}t`QsX6N1bhnfKF{b`U`n}zHI&<7xU0r&YtNg1!?#upLb<~^ufzs;wu?A#3M5f- zi#Jtw?XdAWu^V&34CdIB*56Bj;=cPTW=L1>uPJ>N11^00A&gaSkng}C#eB{-<2p{5 zUC$VJ@j>6u!dDL7ml9J2XCLrTx{-lhP3=OJ>AOjXoLX z$-?jE+X7dTEI8Lo>8G*=We^RM2ggNj4p`LMq^s@!YnvEAg3;%h(F$Dn8te7o_0ddk zj&IS)AwBAI7xL2+LALJ&Lw#$TAu?*6MR|*srLLIUQh%+9k&_d;xw8qnC*iy6x!ZI6 zbd)$=>7! zc_^RdlPGrFc5i&ToDN}(bq{9e~WvPmSPQ49P)i2l`J5Atg|<*)?~SK0aw z#PO?hW3k-3o%fX&($M}RE4*fJ#cH2dT^D({ZH%^Y?tDkCrhFxej>N(Iv|4t8JOL|! zk$VUT@dT%wq?}-Dvj@~XWA~s0dGQ(lL5erLaUuC#dObpVk~on# z4Q3DYwu$+}ZAc!43f-$4p2q>D{}lcMfuiE)rs33rl7v^cNezwJ>l;LDWBsuvqCPsR zD(iJcNa-AtU#^y<0xPDVg31w@MU_vixh%+R0ka=f819CH4#SagePfZq%pKz{AP`ov znee*jU?e@JHxa;Ve>h7!>aML8KxvxOMgf$MmR8(IGXkrB{39X(I2bY~=bmoWeaqKY zMadBtQUd=VeQ(%G@A`%w8-|Vu#R2l-7?1tbU?&1f^p`*%vOz?~fe3`k;d; zz!|lM!LVP9DDkDt98oO!hEt74ihNGa2dzSL_j(&)46iY4IZLK+@{@cjJ{u8Da-p7k z;x81o+PQxIca3HIs#Di5NCHahQMwn!ARCZLbTOC@ZOrlHx^rDwrM!hKn|K}|`6gQ9 zAYqi|^fWk3-$eQEq9)7%tXC`_oU~L?LJC2E4x7mPjan}zN<4~jk`-^S;A9acPXkkA z+&yK40gJ*tf}YnF`=$gsY{8ET?Op`=>X&m&`vEd|$pgIhacwqVp8Om$7a9VH@Ktc| zN}M@kxsc;fb(p_W}pCwE=!aHms#PilPgQ^mHzez^nE{<|EJdX zs}$d7_`~;y0B3eb{|=Jx?(Wa;kdK)$ube**s=GSE_pgC*cW=`7Ipr8I8(F}Qhep(l zb4MaNQahh2@N^FA?(0$sGNFXQxfcYr9-fernnCiOLIrvXmXzPXrcD(X)20nhOcZcQ zdNtuz&uV$0HGB+HfQzjgt}O>9L}=(&rvPx+WxHdetyHd|C3MBDV8Vx#y<2Bo39&yR8Ak z*0!Uel&~VYAfGj@k5eOual%O;iGhmXunR*cI&;M^vB6zE9-m|{S7+L(fs~|sQ<$fE6V&lf zP8COdHYktXcP~tZOhypzPL2z|c+O!JBmOvdWC~LoHS>JU~M>@)wf405Jc$<(q z0zyiu-)qq}_dXxe%uly{EJ?&0dDK0T@M80YPccr93it84`Bc#I3zcM*CKE|fNLWXp z=ScbS1ETFS{`YrgP>YRbfz&f#Q4a_2FL<8c*Jv6_(E**6O}-zcwi@l|Z0>t`qDtK;Xzer`d^ z*M|Zv=_4gX_;H9h5u$j9KN8dLhZTU4iN-cXru8aWNspPiHF3_9Jv%lU!i8FO;2ZgW z_}7KL!ZdC|mtyV{-;R}3?Jv(X4EUruJsIi%)z#FmfIV&$y)pAeDq2m&>9 zql%+jRf(|YletL@$$;p?;i&P=>D#@Dq6kCs)9Krrd*tfq`+f4kMp_RuL)fC_XtGv)N zC2Shv;||hVpZkOvDwerk>j0NShubAWMGobZ!YK(2Jb7^|GzV1t%oT?dIj2u{fRank z8mZZ^GPpcDoQPwJZE-%NPXxJ@A@8VWZ3GNrgosQDA(C7!Y3}-}Jx%A2ohL#i<|^8& z557^SFpnpm(xmVo-R@r$!wc=+qly4sZbi2Rr%64FLM>MV33$ZMK6N0}74VROy27k} zz6YOTzf$~vW$1SO!%sW)?I@Vl7iNwOdktX#1oMP$;i0t}19Aw6|5zl$d=f#`r@0}W zyxFzXw%+6kv>IMkgkUd6q_}yCatPbr3!$Y=XyiY(#yKfX&>~J4i@^hp6;R1O3CZmU z6p6=(wyKxjRX?p8?${ahp@)*4WI_{LWoE_8Cp?W6E*#Uo1yE5hn4yfR&h80iwA8j_ z?ikLE>p5~uu4`uAG!`LSayt|I4?C4n@eh{BuA!UDK*U;*LC?PJ`jG1`lldl1cH$|? zO)bB+$x_tY!g^ZVOY>xDSVR{RBUlZaWl5C^te^VNtcwjcV*-{Gic7u65*uMzh6_?Z zvl{U>ge-^bp@xm4TcgC(Y33dEc9Pd?x)48@c=;X3vt$2F=!w%Gg%yl`|L+{VvdCQq zAI5oK-03}X+$Emj%Fg4rsR0@uaT3!TZR2mc=|`+q7*|n0u{sv$h-~OKh~2D=Hn?{; z?Vvhbb$`*ycy;Yzk!t75j4%^=#|3J8bjHC5dylD%s`;WS-#=^BYf+VQQfba%&ToDX z(l}Fg(I90a+4Hi%s@=6}iMw8+6b>@N-nF%5InB6AlaZQP?bs;CeOShk{+o7ptW}#p zE5{tm=&I5aOqeMnnjy+Zj2G+^OdD#du>un&Xz&Bil%DEthFm zq!|w92vP(kiVLg}ZybJ&cD12fpOT3OuYyxU)N)3Bl*&qBQ_uhlL9yOT4N&}o!5*qn zDt2s8C&@aF_6G{O{!K9;&}Gc@H?Rt1Iqn5y3rhwEIVR`zgtd{DA*e97a{>Ohv}wrbI33?rY{G0YT?{ znKOb(8_T=Y(|LgvuZ?TIsu;JD&v6|?B{q-)*wy?#^6>cr%hWZWtUEF)b;+YJvspkF z)S4K-3VWlYW3p3yg{Ij-n)e-q%Yw{XXyu;ZEQkj&?!31sJ~zoLvc!!8q!QK0lV!u+ z4GR-u9^m#K6GNI1u$Ls-5v^2{6Y0(+TBSfr2ErN5$V7d@Qws*|cfQ7S}<3v`=*GYE59w+)@vmDpbh9D$xh2cp6_L7N9 z+9_^rUcfzui(s$UK`X2HHdi>9YUBKYNY1F5{f`HIz zG4hJ&#XzglvyQP|#m9^A#IyqiqyvZZFp5xoMUwd>3G>M&)+4ju0%y!0Mv?_(T8n>9 zn1*`by|b8QPXPdDWv;gepJlwt3hQkU(kq1li&!JRj;Dw->Ecs{#?ehwy6P3(m;4>( z7IOJyQ4iQWP5wx^(?teq!8&)QDYTto{y&^mi}7uWdXnfk#37!w9LD+3;43jTeP1eL z9=LxE7RsJ*oxhhb9X%V_!zLLlfJM|#7S4J1EK$DfJPwkxG)$+N-m0yuAcIe>usCAlkKo9QxQ9k^j9@a&CMq18;iA3q+-;uogz8qyjccYEz}rw2|D9@!v`q`{az-in*{kzsFO z%0u*`DJG1P-?Km{`o)7cJb5t90+`2)&*A|Asv}29R0{&8>oBgeR+VhhY&zan_~%;I zYgK5QB|EV;(Qxc?4+={f|4%AZDZ$*IVwW@QyvXOoFEoaMW17i<8+aE>P%q1yz z2zC~n``Lvq26pa3snz>S$5FhL%pze}z*M2Dbzx6LhoWi{3!-{Ogyv1!$2_^zuWY4; ziKs%6@_w=@WW_2~$J?7`+G5Tg2qdgD9G#jHNn*Q~Ni&uuox2ZsQ%#7P{AdR*0?W7U zqr>-gfeF1Y7-3^mGr55J*KLI8pn3oF1tkxt)|CqW_ljv&NgHI7SL&7CvDFRsr-%*= z`2vi#7zx^lww>P4o!8WyRJOeV_lMU;VD;Rvz%xl1wZ!IR-ZGiVpdcA*U3;7{G%C3( z```{|ToZ=`&;szipP(oHqwixAlqpcE`_)K4jcPdj#SZ9kqi&ogWVr74V?cwFhzDPv zv8%WyR+9r?O#IPSSUG9bBNcB{5Bg~|9{t4wDKnkMse_p#+;3|c1LlyYTI-9%49A3t zKkwz?3v&}gb9l1O(3HV|{9RPw%o~r?X+o=PiKRvu+TT%Ie}gzz1*`$vbj7nmM___` zvXd1jTr4eN^BC>%E9OVC0+$4d7r0yaSmdi~5TZPFzQ_!TVtE=+1lRR*h;I4OO#3!_v8-1Fw4xy620_(t~c1BSM&RCuM&^G&c9&={epQu-_mOT&acS#WTY%fd7^*9NR zTq{is^_qjh-vHk%V^pY)eh|7^jm8hOLzGQ${MDsxbU2p+P>w5=p@Qt|7GhaBLT^1v zsKoG;IuIPL43krq!3Z5hP%gU}i%As!tLQvVhz=cQo9NrmC`;b6NIHR0IYQY>#FsHM z>Kg21plcX!1T*y4zb2Y^8J4WjLhX|6bx0X51hT-VCaN??HvCpg0JxB4;1MVSYJ6b_ z8&15udH?&B2jBZa%p6%l-CfAlzn$9TTD3xB;l}&6zijf3y_{#Mv z9JeKCbgfuW7(ft7wsmdXy_3)$Q+G$l!GPIBhgz!yQJ}Lsro6(s`5uzg@Z7I{tEBkOuhClr|Y@bl0;;P=-v*BX<*T_o|904O8C>GQ|Y?Loh z(2ss2m}Lsi@{f05BwS!oG-%G%U7=V!y*StO>cZ|c81tTe&--20uEmHqC+ilaE&p~H#;Q?`1i6!;XjlV zQPW${mL=uG1FRN}tRom};+`YcNpMZWUw?!IR;Z}R#mQ`S=Wswu*gyaf4eX?(n7&HHMIoOG^h2l_Mk;QQ_InR)?S!=V z-S+)8yG4hI{xfl`*LA`*n=X5K}FGj;_Wt)oa4-dYyXb`a08$3-&eD z=tuwh^@arOszrwr`)Sk8x@J;`I!oMA25@;@ORVA=+$Nuqt<-UvO8P}r%@$&3HgWWL zJ-RDOuM|Zk-q0#Q4g_R1h~i&=b5vfy#Wz-G^0brbqs}^y{rHLH{cO)fr`pP#r#*ai zGSkK%k;~%lPeat^;S@CprOu5$2-B8gyS-{HMQXUE3&d#(ZBjqqR9DT))E>if7fg+H zJNqTqKVT*fhk~MGU908G;mJ*iQcEcCdzhpW&@epSW~4;oYl_Y&F?{LBmL-Z|lIEw- z3X4hi9`zC{PUkIgmnUR7@21-3Xpr{$zkzltg~?E$aA@+wn%|EhJqioOI63VvUC?9*TlpUXX znC`rJxKPa5O!L)Q;_r1=Z2!4`TzSmR?eh9S$*IoG;R!rFmfwlo#PTEX`rd{7`F$E^ zPWT3w-#ye(+nT>n?9+4CHh7 z{5!Vk-sQi8R;J+yhPR#6BAK?8@R>moaA zzL+*3IJSs`Fa(M8yGOWy%9NJ>!mkY_PoOsg3oC?0@D#GPv(?qsb|);fBHy?;O-Y?* z-?Ov3?djRp3Jj&3j5y9R;k4f>7=PxTB;A$D4Np(8GGIAUND2&riJcDnp_d~U5y=n< zG{G_AE=T?-^oPbDkE~P`Mxg-j|H~MQJhGU_gkuqlCo#em<4F`IQ7Z*@r4^?{U^We2@N|BC)fTb&*6a&3HiIXOCLK9FRSy$q-U^ zYT;bQpeIqyUx(fWJC<)|9VZ*p>Z`bFS}J3LR5~4QUZZV~5AACdLQXS4BSCpl5a69E z?WDqD&huxY&>KFq!J7CKa8<-O&82%dyh2Qwr8~WDxSLqeZ{o_OPmO-pO)ml@9r-Iqc7X_i zd9n<@hdXy+Q_^#5V%$RO%1l9`6r1n+L-{)9oCY1Hi72a3vVmvC5Pt{{@k2PT0~$Bz z%~yod*=&%Aow2YH+`ROq4J>=`h29%J6waJiwGiUku-gogRA^BZYYt4*U=!l&U}uG|%>?1l>nuatfe z{tBH4k5U^#DdM{=UYC-Q1(BtO&YF33?bwI1-J1)0LoDux_MhxlGWN;D_-?Wa>e!AlN4O1j$z1BD#ARq zTF#vHl|A5OjHuZPOgRs5$5Jx9jWO%r z_;A1Rac}UuHo333)rR`eLnZw31;nkyK6eojqBA)HwlhONrz!dAT5t7c%{bnhs@L%C#K8B@`0|w3o+-s;GI+h>BFPm9d|=Fc#*~Q5&uQXYaM2 z6)@htD8e+(xTeybQfxL;cdv@kXctEV>@%dtt!z3Jx>UL>(`k)m?C#Sl{i?NwgY{k3 zeI*)pU0z=x<4J?>OiFSryFED5h7jPMYj~H2HB)BfXWPP{BytXe8JhHt#Hffu3zV|8 zpt6grWq1aOJc`a6vPrasvnHD$wqCX7Nxok+!)f~dr4XC{`SMTcR+0%<{*)Wy7a>i5+t08~j`uhz^xnSygTwdYA6ryEoa$MD2`uBFbd&X5Df|`W5)Y~P9B*=3^!TBXjahyV*k+% zEOQr%py%SN02~^9G7HhY+~M4}ck*^w_aOKAe9l~L>cPH2j!xFjC$mu?J`mN^JNeG) zRF;}g*Ty$l%38{F^8P^gt09|un$bjfAGCE4hfS%&un|tACr(i+r&CZXanG&@^+ih- zCv8BWm_^PU1&t{f36D7~tVwXXTT5GMAu^0~#k=LjJKqsq4)oETM{M@ZM#~r~BL8LO zngbVx>{2TrzLi4Nj0hz)5#lu1D_d+fwrRq)Oz5G~>pVP#QE4j+KtD9;i#r^EF;l?m z`@gp5A&4|RF>{?;AL8yL>j@ZJjijXC%GADMc8ksz% zG{pCD)sR;KIcz7naP-MbG}y-&7TCfN>KeV--RxK#11tNkkQgG7F2z+g< zU92-iXQY9%{@^xOd0olC1R(Zu&-TZ`6BG&Vhp~{ohDjou(iz3{4CQTO2QcXcB06k? z=N^D9*0|i+L!x`!AYC*Hp&k?(U14GZQ8(m`Rd;h5M};D0Zj+ zrCJzUV3!Iia4zVA-rn;ptF_pNt~sl58z#0GSzH&aisILqu#Mqhk`el82VC(x z6H4={=ry`o%0z=nAP`7cP8LFEkX+w#Z;22i7txDYUcM{8m)4Y@YBxCJkN-m*hN0f( zSc6H~GjY?svoZolK9+Ab15s;Vtns12Ym)bkJ!n3M@uY?^TxH#pC)^6YpcnQs0*}U< zn)CmP+2RsjsEwjv zc-E)H>KvP)*e++9+h#yHEl*%l9V6)Z)cQCu0J176d$WlQ+F(z$v~^YXY94^kfR68v zv&c+@2`7%&2W+UJGO=|7=$C^@E4ncnIWYyfbl5iNb@hnMO>1ba{l;fu{b3L5Lt6S_ zFKc1sZHV9Fd9zfb{z~@&ej%Ryk!?%tjb=;tX2IYCwe1WnCnMEoM%ij1pKx`aQ=Qg>=i%bq9*06Cww(MhD+zF ze<`0Y`*Fx=@Uzx71x_~;n-y}C73yg=SuTw-lTh{1JT@u8rKkHXuP=R@yl6V@SGIKTt3+ zSJnG_dJ0eZhJ4pQ-p#3hR#y^Lzfw2dZwP-PIsRx5`?N#OZjbtUJY0>Zko>GJ{%@#u zum4}{h<{+Y0aB$F7X?Z@StEiF!G(+;bL|0rb?)@yk?CQG4JtCRlOeYhmC!`(qAtpG zCkjjv2m0EdylCwv&E70_2Nx2|NQZ#+o z;l`wzXby0K%#qKxHSnK9u9&}?7Fy9hq)?35vUyeM4njl7HGxI5Qr75_%aIu><)#x{ zOEn!-I4`slR6$KjXFhwUK4-paU$d%Tr`rE+1b&6Zx)#1~#+_b2b{|W%>Ar7|rG7i3 z&5M7lpL#RrelLg>Be?yU9>`-Ek)shwtcD}d$6 zO}1-;e6Sov=-GWQyo$!kqacgWzq>by@~=y4HMtZL0#WT*Zx4pABLw?E(uuiosF4sQ zD@-G2rYHHC*In3Gzg~EqZ<~c%?{LbwbdM)QAGVqc-gdcRtXhJ0&0m*3JuhrywGmAf zKDid%c!N$8PGtDuZ-$x57tcA=#P_9oVo0wdMq!9VO~?g}a1&K;bJ%D_lG(k)5bfn7 zL%6wSM zW%vuvj4s%XN_4O-C7@_X(^(VkWdId!Jn$>vWtT&6!r0&3V|3WtyJKU#J|nkI(_}}R zcrM(5#IiB#T}Jh9JH76ox@7i9U8`1*8m3KEL0|X=Cc4=JB7TO-ybWM|6iI!h@I$-b zB-s{3-_FDtPghS9nhHBlBT28zwuFpFFGn$ESG`wF7}y$o)f{{;XgE!Hp?L4AVZ~_= za|EMm`s?mLqhdDpo)nXj@z-$W+iia@`%z$vSCuia!L7<{Vr_|Z!`B6Tgj{2gg80`^ zU@bT04z;c|_2dp))U%6lx}DZyrTuHb+^gOf1ef8tUKw18&GjeWdG`DxEFdYdOM5Ua zp}iUt%)sLkEds7^B52oWMY8Der>l(?tiFvdF~^l;Mi^ts#8?=ki=X;KPVC*A-Um=w z*TK8eaC_J9>fq}=!g%98-r$nu9Jz2$MAPThRvAdlxaMDImKjl-@$1y}RN&`o+iEJf zzP)LxQ$A;CYiq3W9zA>dR(>id7JI(7s&a5K9#Pq{1ZSowH(P>(yHodr*40hhS~m%V z*ojppK&q3^nO=uKy9Y_qA3+5^oylmsrsH1h%#ySzr-W8ydGzwM>_s)x$;zT8N5-sKmC{E zK=D*mkp2L4Kif`|4@hk_vn{C_-(%?TZa4|N(ce#ZP#0Q698h^`j{>&Y3w5Y1n% zCIYvQA_zs(G{P*YHx60Bj3cXr!yiJ`YbfU4qlsjH+mmodcomK3MHxy*=evu%PKm_m zM`bLzIMu~-bEF+hh59n_{2&9n@3B*vve^{D-N=Y|d%pr~$)S3X%@hD@7~tHah}e&i z&!jJe#%947>-mY%g^KD;)&aa};y+B5;pGtsd}PNGqb;c#_+UJ#VBer(`FM;O*UsJ7 zr)KaBs1M9Ie|JCY&WI}|a<`(4sQ@o}5pq{yH^f~_fD zg@usURB@9FoR9haHpA9&;+N@h|CmI42&0s#%q>d<9Azmo_U#QJH2tGnXqDez%fOz8 z2RD-dWbNsm;9l0lB6Sp>#Snomz6L$6OaRna&Y&$whXJBhei&rGf~%}{(pu@|##n3e zU{01Xu%Qdx`Ah2=olFmUulheI#tUaa6b_hW$zo^HU@Xysm5IUJAoAG9iJG!_*G@S19U?e9sO4{p zCg1gin_=Q}QLEK_WE*6&Nk=L{rU@GDfD$xXCDeHY%K;rW3xz;tKV&`xuCh{@`?wb{ zoKs7wawDY(pUEZ#rrwS#6z3Tr7^2}+5ErxmI)-|g|2hUaW7HpxW5B;L?J<1EIeg(b zK86Vukc$xtrN#R`d|=}5j%pE5GF(KF?=38T+WxX_1A8+)pCx{3QZ zqejGVVN@0G%XDBZuM&eJKGE9^{%*@T6HaS6d}Fa)zd_v^8cPk4m;DV%tjR!&IHkTDvbE%Hm#uL>ySL8>pA(a7GR8weX z-$)oUG})#m{A{?f-Y4;hR$O*QM=P5DsQ$=?1uA5FfNWxTKWXx`0Wm)R@Z9C_dmOB- zLD8bZH&CJ!j{_&#Nt&rA&o!+8SEcc!wTZb}(rm6v&b5^Aa}zzmEukS={OYDrdJC}D z<~6eINab!m1$aDAO48?P;mVG3CZ6eZ0~q40ZqY+B5kz79Gfqxi?KRXqoP^u8zo(-Y zrGmA~9X6cgRXK3yfM;&EE!^Ps0_Yn)P5-W{Ae^h8A3w1c*^qC3I68xc-D^ZuCuDTyO$KTE5Er8Z}ITOA_z|`C5Tn-zIu-)gJ*8K>@3lMpZ%b?Vwi*HoP~lJNyQkd>_b8w>!(!qi3S@*+Dlz1RF#*Vz)>bPu0*VE1+{;3J|*dAlfIT& zY~|s;?X#xRUsgS&Szufh*a??Cm~uJ2jk2o)&#SXFaJ$uyvQ%B>z8Z;RS|Js0QXp6E z^q9wE!=){M2qmOg?S@O~$Moby8Y1Nhv z|0!ji)MSk`_Jk>qpG(IxzK@>&GiaDeYM?9k2RdSM^e{ zbGgSZ8V}=7@s7Oi4)Xuv-R!yW;;gDKg7B=}Nc^V%?6L>xef@8JXXgq2s#rWXSrx+j z+47Hyd6<~D_l$G425L*NHVk<{pO zEr$s#972H?r!-?8p?G1VSY0}Mp2h|nym9ISRB&nP1U@lDl-E?v3q#ntr4UIt zv_Zf@ED)(7+d-{b*#tWBBcZFi(oeo-n9XHUt-CCjzQFR$8{GD5m&fG@^iYs z>AYsxRoD}3;!2qqMZ+uqp`*~yT3T0QL135`SEoKOXp#Md1G;wL2Fevbrhn55et}KP z^*j0P;=v(~^o{dN9Th=;3Db%)GYJLnexpeFL}BF#;|eA++;3lY+`qasW7UAHw;Am) zs_WXo+lb-Vj#7I5qcd~CeA*uz+SRbM;Y~VjVZqXjWgQmC>X{Q8=T36j#uZo7rH&VW zbK~PFbuNQbd%zMyp@Cu!a@JLWB0X{YjJ~@PD2h@H4aEK+iB=*UQjXHgU@&+X=8*Lix(FJ;K-8YtaED9DiQ~W>2uxz7q;~|t z;l_0}qsaK-CK&JymieIrnAXO7G6XU%4Num6!Bg>7?(G|Wip#+pD}AX?;XEQtvF83! zR}KA-&E$hsA30iIJstBwgMLF+ZX(U)xA2bg?UV>M4|8BfHE^RiR(EV-XC244%EPIv zuTuoH$5{&`Fq@|*mM|&X%T7mkCNrEebklr?%c z@AEp2-znB-p;>@8iZ#c=R$QLuc1tMK+e_DGn&fqO#U!waf`%%fSnxxK!Kv4hl&(a*5m0KmXq8DOl!Up|DD!&56H@M9?-yhln8P@;4Iz~cD%()f#ds- zo9Kr$43%sU%DUqDK*={C`&R_~PRv9zBk;4f;-CY=`o)}lm~Ub-z^HNH>1(_vz1i`T z^&4&G3$@eUK{U=}`VW^DVC9O)ddGIiKlLi@SsFbUyH=ju|%z2X>o2EO_x ztmIDT*jmP&!l9{@Jrcv`A7D2wxLPsa>EbkWG&XMv%k(SDNosra+L6vPnlz@W@J9vpWtScD7>kH1UUH;V68he+FnYu6Ebz#+JMfIwo`=2D@50*i?$)+}rHTlQML7Rr zYO#kxoqL+apM&*mqMk&y2&!kUqp!l;D*Hj}u69R}yw=erQ=Yn`(h#>H25Ja$8fPkZ zhb0Vs#FUD5-dA82Yjsr-CJ9g5*2t49QMUwXj2Tkcp(w;01Z_1zu~dJ%uT8H`3AR_Z z8RFxf8t{0aBt{YrpxG3CX>N-x^rY(3&SGwrceVFd#F?IRGC}TIwE@$I4Axso79=MIs|JyuDpWb*fM}m>K+qIw~07Se^ zzj|AN#0P$XCtI|!T0GCp5Vc-SJ?Px_@C!=vm`}mBFG|arfHeDpF$Xt{JYyR2M|b_2 z+kO?7+7@RFb{;N7t5wg-z7bfYkv*G+&c_!wRD%dVVEx$dX^P6%R4=x1<};1@!-oy` z@OU;%SRRzIT!B?RAnv6;9fql61vgRY7{q1^`+F`m{?A;h^hpR{M-RT@xUL%K18X|L z&;@RK@lOIEPN9`2M51L92|+I$RCX7|?2s5&kRIjFSy*d0DP283DVS0cSBe7(oygHG zxGD5s{bPti*fIB1-*~@JP=l_YcRrOY13J|4GyK*@q_0@k;Q9Zj5P;+Yb~x5>KZhHT z0iMnTnQ}DC#q`sS&;(+oo2u5FwT+0%BwasljJ+t@7+YtaUJr zuW@%Uw@*ceWCX3Um;j*CTwag>7pXH~G5%JBXFv{B&g&-tosUmz3(ymF0)GuqYL($u z(FFr;eLuOr0oZoAy&kTee*tiLD&7I#FE%#-zR~)Uo)??V$qYX={H+xNvvW(wNKI0H z#3=bgSP4PzpL3lZFc)1dClLh8+60<6RjWTM_S;nbeNDQn=;&8k5L4Rw%{&2*jfa~P z+HJlWXmiaT4Y<4n`0O!)$=kYa!7&DVQQ>F(emQ@ zQDg8Pz&XEuCr_ItUJ2jb9zKhZWz`%7`u@4T7Y)*D0{%1#NxH;Y_yh@1?Dr~7^V}#r z(lIg@H<-7-)W|>_uh8%h*!|r0^C0fkeG?B02- z^K1JPTXaHcSgT|pdhTc00WO%iK$k<0_&?uYmn=WZTFIPc(aOA2F z+=aZ>C8h-MqANZZ08cgoo~|Drew%)^01ilQxdYg#`5@gEHE?KbDAmO`g z&*#jINYVW?l!02&1Fy;_G-gg|YKx2Tl41f_gg0gC3%>k$7}BY>h`+;EdX=xDN$^mf zpN=N(1P09Rh@oSTKnSgAb5m+(Cl4MOYt1280rxcSo_XDuZDBfPzSYs;iqnShg6(3?gJcfcr}0UWmkUieg9*B_5J5M3n1pky28;qhpv;J&KqTo-QkxF zN9p56wPTM#AMh$jBU{Fa2F8Fb`wDETka_A&HRD6f3CLYZ{FDC}3Jmhs^{ZKnv->i$ z*8=YDL#N%7LEc%HeqK(f?U7n%QoIxtbK^s0=i-!5HB0bWlWSAS*@$8B1q zXR-?puqhYMinUb7W^)KA)!$#J1Kw8S;RwpXc}Gqp$eidNrXFC3_^H|*>=wgijlyst z9r0-<-9$fRTN-QxwMtkQb5_dOSR>9)=WuA7CvXd_W2lz2MhD)*uP}Z)&&osSi)~`B zJiOG2)=Z&d{W)0_q>w|;FJo-je6EZ<)D#K23W--zTDdfKB!5(j72B>rQA#R+1PaGS z-?5vnVlZL9;buUwUc5x>fQGdQBP}D`5je)lj21IfH-E~_Q(@KH-*6=64h z)p_fCiY&5n2`@~w;2lk2GaAM#Z}!SyS*>a=-m1ht(S;kSVl||wD;Hla2q!J5prH_5 zTWjZ7ha3$h%)U;X06l6;ZDBmU5-AFv0Ez`7-_{MctZu9 zpNIOvCew+Mljd~bFjF3lE;BIJ3!4LBHE zUPzI%2E~{n^gATDZ_z=ML^3fLL-=Td zvt{K=8%|wi%#QA&^3xoxB5bJKfAS3%QFAGnuz731DMcA_YsUDSY+(Yica4t`6;!1O zQ>vbsTy zwL-EC^ULN0Aw}3M1lS~?TpYsp1x)2_#QApu894_W_^wbNzk6JVe3%XSdcGQ4k^;7d z9kuT9?T7r*NL8nMo=@65UvGvQs>tcp?sl$EHC_SLAHKHzfE43y18Fik@=&iBWjNlk`e5qO7Rk#Zk?OF}3q2Z!FPl#b? z;wryvfUf3yIr#UgRkd=e%E{1eE&NfFy0<=1-P5Pc7QySA@`{KNLQe0B!7)*~;SQ@s zKk5-LPMKe)NsU}c0`)3kfBq<;3j!94{WUstdQ}Xp9|8GnfA&-5e1G+`fktNDo$lj+ zVgmHd5r{o!#WW6U2<4{B`|0{y!idYp&jK@pofPbw+s<&UagF{vo*N0d5b&$?Cd5{C zHn)?*!@HH6q6!Ur!QwK*PgQM+(ATX40q4*T$}b;0LsF}C`2F*=p+uXp26}Hypu>Pc zu1F*GC>nG^s!_BklHauN z5|m8j?z3w;?)o!tHE!|m3)!-;gVq2_jk~jp=Y&Pmo0u_1K3x2!5J^z>FQ15{i3QYq zr=))36w^-Pw1cEBj{JUu3dTQnU04nAJf8}cB!2iH?*57+D9z^qqZg%NO4U_ zW8&K2HuW4y6SR~^QD{{J3SrR64Mi}>f(U%QfRz(q0HU=-DJAqSV9(9-gi&85V^J0-L0kQQ`kcMNs6H!O6DtWWQu!3qF(k^$N15IshV4b^n;zQlR%ttg0IdN=hxf1)|VU7lPuoWtvFE}o#b zX^K@)EwYD%lYu}jC|53ug5VFNbCgx(`R9E>(LjBuIw`&H^mC8^{(M--X0bHoRVuH6 z7^LHHMcefp3&qkhbTkWCmiSsgFrK;EUs1E)(a*^z1nK#CDD=-@!K?P-VRzkLmh5p?z{{l*)!V+bNecx9No@7H5c(NNxR* z-wbj}^!Wxn*W4D;-|3Rx?#-mr628lZjmk9>H!EGrm6z7RLqBqxVx9!i6qW0b`S>in*L?v;d^y9Q?PhNBzn+3jBE zp3ZR(ydx?dgO2gYx=rRfZaqp2sqN)dlYcCr(hx6f)<-55pF2#o2MUr!$?{|DDMgZ@ zzF;0ab2)RVlvye+J^H~^)rU(ML)4KujlWxpF%ka~Rw&HTGM?C=qGS{`ja z%8^k-e@$9WW-+npAF0)@;VM$Aq>)L#r#2^fEfFpE%=VL|SUF2doe0{ib|tf z-|X>vGqCD*YhGJ&Mn@1|EI1Pff?)T%cmQs{|$i1y%?tySVZBagGI{gTr~+`*=i4NVF>IsT0HL z(I&~-Axnyi5@P24H2DiCwgJ1f16JkOtwKB^79t(Em^A*^tgq-e3r_o7Qzy+Rtg`Mn z-E&U7&D5EoMlca5%-|$YPSz-8#q*KyZ!6aDFsXLjh)<3t+)tYeUY?-P7)40g0wLL* z(}oO$Ma#j@I}dJ;W7t_D1d(}E&i*OW`rqv;Z?C?xJw~So#{vF1h}BblfVsdu4Rf@YXiW&lpQ0{{3WicQV+GrIU&^21bPgu- zoiAHchF-}B!;BY$5I^>fSw}=lr{I_JLD5S8Q?5F#G#Hc+cRt?h3rW(?PFsCWp8cvk z%uE@b-)Jfd7R%HhbFy5>#M=XbjB!rB!GuOxBSph#?)^jO4QaPg2@6VNo+b%bS{r_V zj~UN12_s5t@Xp>+8+>3-S09?|2xWFq+I*l3^HE;Y+eh?M-+}<&o)7Vq-AkZZgDRo{ z$s^LzY_14%Au{{5t~^)ChfCG7X(DFlB{kWY77Dcm%;$@^CA)zFM{JGWqGs5Lb$2|8 z+{-x0Uu~Ce36<}$lh3_9k=pqQRuthTpjP#R2<{X^WASpm-##U9Usf+eNJ&qv+j0;> znglO`1TI+19~CPZ;m%BV#0l~Ayw8;Q*wVN`LTWb{-bH8elpzWBRIdcrxEIiVg$;U_ zXGowM2Vtc8W(`TB(s@>dat0@*Y+X1kg;ii-#7bur<1na`WX%R)>eSr(9-$_Ms{iJ# z1W@}3FH7)sdqDr5yE6E?+q$^6whnQiwUi^8dr@XSG{n-~{@IMD5H0lbA6rcXYE^c7;4D^Xxnhq1gbKioAOsKyNrmZxmjjsK^WDVNHv8n%=g^qdw`{>loU zicc#|^``50lPdUcTb(L&xSQEt3mB%TWz~-HUhsnEyzAYl*`RV^ zJZmY7*-^ehSh+__Jj&K&-hwHLs)iHZy<^v1&QO*-Prs|uS4@?eT;$7)mRxgo^*-Ou za6>qtGaN8^dB1`Uc&$G3cxv>lP60%uDv7*^nEL2{08Y^9sUCcH&9VS|pRa2ZIi2V& zj6i(sfFAT$Jze&DK$rTFZ(G#K@k);tnKsY!L0iD_M9|-JX`(y z-23njpgP&{_OUVgvRnZyFO^MPcd&!n z2Ek3?-ZOVBeE8GUX|$LL`phZnF2jtYOu zBRrg4lQJp~XM#Eg&)I<4g*}EYVKmDmy18;7-)MLU6ZX8ozlyN1{}IVNQXA_i1?nMV zXl%THU}zag@pJ*pa zF%I$vMw4D0in|x$D89eewwY{nHNH}j5*SZp{1?9O#US`_`(LQAs)Ih&O zhN+O@8=Ikhs@jgoFJ&P|d+!WYma13A@Z2<=e&Xr(@!2xqN&K+Afen3efwg?IS6;HY zlzeP-h2<*#1v52)jxODru&uZenk0-x2H_y|U?{8Xw$AOzRjg}0cV$F;MY;?`{6V+; z*-!Sp=jsW!Q6f>4x8VbB`7F2@CDkGOBT}xqo|CT=+WQ0*DhX9F{IBw3p2UhY!S1`? zbIhquOSN^PM6E2qYxpgU`& zTB6k-{^O}PvvO!ltf{0&c=c1bi@en6xN+W3&1*@P1rx-}zj}N$l-gl+QCeZ65}?Pr zT3?gEQ7KQDnjV673r-5gW`{5f>Pk+SC%;Mt&YS@E*L<<~U#|y%w-Mj-J+(@}2_Wz8 z@)OK=7ZjoAPVUl-b$Rj%Ydc8@z_+S?LvP}XLVn`d>0n84niDc~DqX^*;ZK@4K;<37 z_8<6gRPn#?;e55av{_X@vJj@6a7I)TKX``BfP(S+j4Ksn%Z>B-spfN*9&=l6!&P(v z+)4jwSmOHkt)zpv6|M2+(o_Zd(t=LKl&lejj8T5tc%$>6iKG6PQ&0HhQeVX%Hm-Nu z9%m;YNh&L5nrAAN%RdsRT6M4VDV9o2FmTclA?Z@ZoDx>(0LnIui>r}nkTheLl^@CZ zS}P=JD(R~?v@)08xhr9$vZ0i1gdp9L-K(rnf6JTZGGwaM7Ho_Zc_PA7#OqB>R~)IJ z%W;uX)KUPw>>wZGyo-go1C5diuTJf&FFo$;MVZR!M=?jnx47mmIE41E5T&iJs9&$k zcWXNG{wa{ni(*w)K!E3=?3-(RsVAE!WI$fF!bl+$Bq~T%#7!;dU->JfI>Poo{Dr6O z2TY2#RBs~AqM(|mr_8YvY4B-I0QGw$6D#1}3?S!wR;DxJdYj?{aE-lJx9~7}X;tSo z{Y#S=+GP$Mzqw-T4BFqYoinJ^$xba6EIRZOcLOao-344|^W{E=D*-OLRRq+uhibX;|sIn^v(9yRvyOL{hTKCoK(|#ez0R=DzCI_lf)+6;x^+&ow*@@l;2C;v_7hv zo@1llmyLOAoPU@4?kc=+cfNU}5C)>Fgy~n!m0&^15{j91yWy8)-Jy!fpeS)WF(}uO zZGuK0ipX)Pvg6{tF8pXP`(fNZlx3KfYlNuHYHE?~>7*S+{|to&oYdBG*oM{> zWaWF}FWbN+Cu8A7q2{oU`1xP~11^dzvoJsQdx!r6z8BK+e}nHOi^xYk9O6NGy45gr z5dA9s9?s}q9ZEp-*)!;OIFnACxRj8 z7)Rj%GS7QD6NDtNjBtP{5-U{!4zGBUEETb$}n z^Pf@7Ae2wo>ilmk=NT^OsF1iT^%v0_*a8(y3G^fMJ;2#Ph)s$8gMHT9ZNbdFUE`$c zB!YJ&iMnBfKkrB1`U?CJZ2y6DWimSi{ER{tQIca1$2bnDh`N*r!KmpCbI$|nCy?&Ignw1gApW;$KPdc)d;En8o^PyiuSrs9x*NAeG zA&d93qG~ri!l`e|^ljz(E3%7OkDK-A>!r!K7>WY}ytk;mfzJMU42uJ3UsyTQ{z>^G z>U(I~(t6k#)b?}bHe?W>bP*Wen*r9igkib-N`L+lWyeZ2ACKwtj^w1AR=AR^*597~ zFQs=v_yLC=-iFjwD|%ZR%~G0F4=&ENyb?TAR|#Q4<&axwBLemPIfhSI06gJJkGdan zwFGEv&vl>#msx-PY?9saH>uK+2dCkYA1vXol%U=3NRwQu3w9ha_{Te&Fe-J~&HHjo#W4N0g=@JwErr&##R=L*eZ_u#e>V7TZUr;)_PRgc zFSHf93WBEPjGROj?0d;;-QGO43K2y*-oDaFxgr0g9{>LW=rR9)1A5&^-+&&h`#*qQ zl=vsr7Z7wS6aV_%DRpoRUY#@rx*3wxU4mrOvQ2r|!_R#7rp7)sjg)e+;UVw!2)q20 zZH4_+z)xn4)%*O>%b9I=>I!J2t;9>{*HVoxKOWBkBE8>qp3RA*Ps*`- zq!!rBRUol?`j4UMAKHIxWo5L3JL_l#)uSu)yJ3?$*Qv-XinLaQNj&2cu3MiQCWI_A zva86HSbm@HfU|mKm@JJ!B)}uV;Y<3wMrc$jJSK`Whv#WK=v9&Ryk_Zc{ZM{-4yV#M zV9>-H-VdCL#fKPf)x2DHQK&IkG*x$!B^sU?mZ2>XHcl+#NOu~t)k}8nxNEF2Ze?Gk zkRda6#PG~HkWUg0tuQ!}m*MQmb2u-Tj?#%>2(N3u z-(SgH_>!u$H|rAVv%(0*O%w8|6s=-Y|Kr$0|IYeIA=9NLiXF1Ng~1+D89noFKJo0Z z{%+=v(|XK0IN3Yp;)f3tH}S0529gQ+yVK=JAoPvI`NXJ5XL{LWhOjyIt^A8xS<*2|khEwQzc&Yrd!8UC#zcfoko^*tyXYl+qDi{13UyD3}#;z__nl^X3Mh!46Y<& zz(PE!oLGr&;i~PHIOg^)n;EP}OBv-wnb=?pp(SKNf0LzF;z2m#9W@pz&9vV?=3!GG zzjF zxuSwtoqdWDVI`%6Q!23N3qN$G^MwO+m3 zt0g61ZPl@aVPGDlM?x?9Q4}`u1Z|ek(ok4jH%a%+N)k7( z3!Bc_<;c42y*FZ-U8^twq}dODukR>){b#uxTO zR_6t(5=D-^@^mFKyEQR$dGe{il5a}Qi6R!eA88BikdfL!vi58=sZura?5CX5jL<2P z)93OY{UyBbey;=>*2%JHn<@n*rzy{myd1c??g$;3maFO%{1Ve8&Z!L|?xNgf) zPpI?i(JgJ(smMU%T9~7HgFK1Dq#^A<(EaLZ38%b4(>knN0t#dltH_dGVf~)4SG#O| z#wlv=lD^CLH*tu9;jw{ZI%5iG&ePL}L;NUay) zay+xi4&@z9aScrPBOpaX6BsOL$)ZF}JZHw7!PJdwsS;M3fJpJ1#@w?hoj`Zg4_>|K zdC#FanX}Z1cNJHh@@gxX#99g{Bd#LMqc(l#7(G+57IJOPjE+m8E-_2FZ19MCH2wx3 zw5;h81JwY11+7%5jtE~?2lYH+d(Vz|Di&eb7HxZ0!Jk+LhNpUizoQ>8#Ci)A&Nxor z%IFL4OzGiM!e&51=|+nh+Ql)iZ~dHWa68b;a@iv>EMtDO-5iAe-mA)t5dJ>zWBCsE z>ezwVnsCp7kB02nUI7hk5xTXa!QdUS%g&Q2<0!pI*OCc!c2c=A8F`Bvtd_)5S*cOu zNY62<;zV`!R{t}gK6MRz=aNJ|B)#h05m+j4PwoSfK_3$mK9KfTQeq5p}~FqwbMhcY#4GS1!^9H)g@vPv*e6Pa;0{$D04$`{PL~Q5e&v z$eYQ!aP%cXJXh5YO~56_`Mw2!BeReODN@QSPxLSkV?g|!Kbh&bvfujJItt2g*lIuI zBXg7OcN;IkK$zG);g&g{1cAF=DmRdpD8DM75QhANtocjO19r$N7e=|7Gu=1-XX%1_ zr}u*j-JuF%f9ENy{~4Dh^|I(fAuuTlbFpXaN|fXU&15A=lI3jsgOc9snw^(}#pdQ# z)%>#33D!9t_ZD9fvR#l?k|hHU-i){FjZ9)PdxJw(4(D-|DaO=r6tht#&kd4XNHkQR z0QZF>K2&?^H;9*8b`*yW9l@;8JR(zMZ*eqLT?h6Ru4TIhx&KC~`D3!9D2$b>(@ku) zu-@ERJeaU~EcM#%aCnsG_%~wtLZqJI^fP_Izari?AcO?LY!gFekZ7q@sKzT$K>y$e zBz8*#%o%n`%8e(vqda1uGF(2oQmU2BXDMtD3F!WQ+ja_(y&?5O!Ty<8kvqg>d=|NO!0vL}Iy~UANz&zQm zZZWc4(szKG!8cdEm$RR&s5aISS5aL~OqxT7QMDF-gdox1%H%Cg*-Flb7o=}G&q||| z%idxIA60ExR|K7l^zZU}wh<^T_5qh(7F1*HSVf@mEiY)NZ}M?aTO6iJd$isLp1k^Z zbZV=g(RCd+{Eg~dRas%48@`Onltb)%B#~l)tx6*fL?DhMs3Z|LNw?y3f5pr|wsYqj zdP>01t}GONad5A+s2kS4{eU*tfvd`ncILn_AKy5xd(AMEqBm+xp9U;k~CaY4kRl|bsZlr-_0&q#gQW~1f7 zW+2CGv8NVM)d@_w=Xy26Fm2$~75VDQcL!0-K)5|#QNa8`n;v0Ir}-DeQzGRV?L?M{ z!hJo9Ct`+HKQWf1{r2!E&Hy|W@}9D$nUwXRDNh2Im~^SxgOZ4bri6PV7QN|6RT{lG&fD`<)K|)|42@~TYiAr(WY+%tPuAk6<;(< z@3=Y`13QB;I!5i%_W{k1R01h-@Kk-rA>S>(9JX2Q)-agn97xZhLz0{t3B1oK5})+8i_x# z?Duw4;wC5PeU$(Nz@%Sseo z560jR`GphYbl0wSLPro>U6JM8Jo!_(MNB!hS;R9^%!q>YFYapJZ{<=60tZXBJ>F8Z z&1Y`H96d6!Jk);pdj^Pj4Ivi7sBLa%S(fIIObiNpLY(P3SQc&^L#Y8mDIOCQsi8iU z8^-Kkc7#bESdHjyE)Iw63A@~BT)#lyx)~!{e`}T?JTgmFFKztQ72!CgncU8j)pyc| zFhr7nD{Li!3CS(K1Y;K*9s}C(?V`Kt+%!`A7?tgua3b?isk`vl8rMPJ#hu3#n=Vl_ zJV=!{9=sovDE(=>HM#zt!!i<~jq zXd{wp;zIOrz@Bb2z!Lo(cx(jyIx=63c_IHl#kx>bw?qg3Hhcq|Z?SIuKp0`&t4)?tHjJ7*!%3Q+LB7VX)wM;`5>t0uLswr$6mQ*JQF<+?Vp|AMk7`fW)loXVb-SNChhG{oW#J1HB7C|Gx!7`*_A zoRIhoY0Hv6=~~+Ei|n(n^P2AYsyJMyjkNp;-~OCL4=$ruvRGyy_CDKw*@~a)ogt%+ zU#rbJq^PUtemi2GG)EG?G=MY9*I4|9f$(PM>fU5}i@N`g9sQN%?wZ;xzf^f&gbfz8 z?4M(m-4OzqTLx7I$Xk&P>%iYnR$2yjaR!|g_PuSBVhw(TN#<$gE^W-X_+#-7q_jlu zNASAwLpdUQ?BhNPcla@Dh@RqqNXP5Pd#UZ%PQ&p%wsT;A#xGvgC&sUURigHYgGxS- zS-4m;)=2H^l+;Wmm+esQG@(*%9_W~f9s4U3t#tV`BHv9+f9LFkMNbu1n%r>4AN{_Z zEyh8=R;qvz{-f3HhD%B^eQR~P(&5GP6pT?17qya|;0$U^Qn@AGie5LtP{~<~7*(z> z1vZ(zAVt3glT^g-vT{bbZzqq0kOW3!4&YME{1{2VbQezyBWawKgV9LP2?G>46Zd6& zZ@hSE`GJ>zNntwbhT&^eCUE%c9LiwqJg9-kB?%mA!V#gByz$Z!$;zIyhB0JwoYwZN zSfL51qW1duhgi-t8BX;%r-`mo?R8jWmR4;vNS|&c(-zs7X>F$lfQC+^QX$l^1tFTD z>7L`%Px#6?75F!Gz!Gs*xYoK=D1uF_kcEcUXIY0Pq0(*l<~y{snIsCLi}ow#!{*$4 zO76FA#b%k9VJaaDS(!+`5k^TkpB;a)#%qUxn_0QtNwo2bPUeOKnqz0J@Z@_U*Xo_E zBvs-w-2TF#bc}l5I1Z9$Zg7b^XtJw8813xOD`m^_6|_kghYuh%qWjzPokFnWF=jU~ zK0?iTbRqFa4#txHyFl z#E`U%fH9NK>cJgW$Bgo=4-|{acKdk<2 zrf7%2&~BXz`2K)Uooc-nSW2T>_VG!c<`RH^w%WK^xwi}nYchG9byMEGXL{fx0VMbZ z;S*z0Hv6q-e}(P#>b)Ui88+1h!$e8d8Y?MyI_b&Y#Jf}WqTtViSI*xN=wkB;^pzv) zBaAhO6FZfj1R7g1V$k7=G!D=i=M^-DCIua~ ztnJNIxuNY&>tUoUpY55#q_|q@w}CDR?ma4+{;Ocos~KgIG;`1 z>v9z*o?ag^z7I7u0!MDR zh)+y2@03yt`PJGB?+|a0Iq*? zb9?Rm%X$kQICvLJyD|%D3ISK$6(j z>CU+J0=P~2H7hp1Mie181ATLrP%_iC6N=HfQscUU*SE34&?F)2j`kh-BHRMD2mQKb z^S-%}UcSwKlM|17{_l?1-r9Hyj=M`AX{`c&Rhn&L5fO=hTt6azi3kjceb7)}JH#`n z-?9`K(`fsH(J2r80f@s8a(|lH*y!o#K4N2^7A~C}$DxliYM#Gyb$Hj-K>f-`LQGK( zzkBmz2e{ohg6-0R(NP>OSPl#rf&WBAl8kkylq7(VtbH$nHGwbYxK-N{`ngc5hgQ)Js{GB|uzEP|7f7X#k5df#?4=4A z&d;2`B8lj3`D2>~VHkb}O(%GYEE0&O;Qw~t+cqwnJ?>KQ@hp7oUJ(jhEQ) z2S55Jv+;A)pPOB{PjAwG;XIi`_3s@foCftiZzlfDyRU*9lq4V8~QJ3jk)XP%gYq-32JBFFmD_1j(K@OKcxUm z`!rG~C1%@p<{o}VK=dvcY6n%CqRx+%48)Kcg3K_DUGoVNR=6k^`6-g| zVJ0zs;EnJ|X!Zp9{WiVO4%{>cdxH}ddI{kf6Bye4Zl@1Q6F^@e;oghnFd2st3r?Qh zySF%IX8G-7!LYVjWca4cx(VEdAPbKZ8K*QD5;jCbTR8#B!Hf1mAu123@&$OHYI<`= z@qb_Z-#E{jo4tv}sfp7#TYhvu8Uu0rTv9IcW{reUa1EB&3+hT<`tXnOErw)SQRNwq zNM|0nu@}4jo(W*ho_oQW%R{uE8-EZ;GOmtGF(aSE@5PZS8#O-g87Tl@?uSi>O87#%Q(fqXF;AHd|rKPtO@|~}Pi{&1Z zov%(hCWnUTy4ETIpd5-s%~>{&%?iY7iBSL}$>r@|VXKO=q{z>#@zr^&xnQXsM|-UX zNN$2OEaJ3mfB|Lhw zcwVp%L$&lYH4pVZ)_pGCY7EwPoEvzP0gs9b9Oyhv_U&?3yA_C>ijeI0J;1~KUx0hv zJ>Z{c!6#o~h*7uuN|p}KvLp6GOvKwip@bDaAJz}wY##Togy;SL+#H_+0DzDFV*tI{ z2Y@wO>j>cF9ymD7uEPYa2M{Dwgp#uoH`4T#$J=x=9q%MHQu|LW{TIq*>~_7hiPidrQ%9C1kQRzNiqlE&lPz8> z#Dl<`Fd4$OM4S19D}RL&lxSJGqp0~te1+blhkAp;e5zf z4qSP&RN9v#>BFV_L``3jJ^Pa1?8nd1SC*B7>csiZ+OLzDIknt1x-|JgR|QenMm6%g z;s3=u8L*I^&|F(!<$93Vr_@sLuaD$eveEEDbPAa_w|)3HJz8EHpJDjC#O}kte*h1j zdAb}CEp9Kvror!k>bT8{5iZf#qOCxb{3{lAO!QVSI#Y8FHwL}d>f-fB-QeGnAlkpE zqnaH~{{$PMsS5aAM{BQ{z5W?9IwJwouZ{=hJ(Yu5+p)%?h15d0;aJxu5wG}TtH z(FUy8zriXYlo(P%M^8Nl%4r{{t+h2N&|!QLgYO%#^~7T4E;)g@G+ilz$OxS|2@lL2 z#djOlAS->-!AAiRK&9uNP!fLnv9|^M&X`gdj5yI%n=3h(t1Muz@SBZZc|==g4M1)8ZtRj z9S@#E|3>y?LY&hGVI7Dbgyw`F`7gf3I->}|J_$XPK%McOu~F4dMUa4Bu9@~D3CKSM z6Ql;@`X( z>30=LcRf6b+&osG@jI_OQXjc{yEsx?yLkuO$)W(yIKppa|IgO*P8|_=b>j&L?2(EX zfneds=kDyS2J)ruS83LEIj?c?%+k@{t&24)`i22rQ>~=@s5Fhr!nJO9wIVNPZD3Rt z4rxC6pIa>gJF<#3|KUQhu0|3>{G&4;OQ7SpbHay^l%-)U3_H1|8VvI=fTZ%Pb#YfF zLVroxC0rH9k^}YTxncff>w-jg2kK;fIRQHhRH$~j`aTH^9jjpwj^;o(F@mnx0(VC4 zdGu3_e&;As)jgp*MX9rTl^fMg3_x~!rwGz8>yS!uOuSl8+O{N4F7wo1O7Hn;KwBQS zhQAH$%q?S}w{e|TVht!*%&e-8OJka?5hkvA?$>U%w z8wR-w``eSDU)Q;=NCOR4o)l|@vllP@t>M7jg%IZ1rY_a{Pf|ZRCx|E^%q@HaQ@q1F zAyPwf9eVx)dk$q*sB#&Ye#1#W`;LKu6*Po~++L<8;UE8~7Y1FK=`yiCe=74LbsIwW z2&|neUCpoOM#GHy#gs0n8Yl91#bApa_onM#n3G>nXt}>tQr6f1sHD}=yz5Ua!N(YE z5vuCBhb@|$3SLygoHbg6V|g(xywkER3WYfJy#J3XX&Ot~V2NWV#-TcWXX8{U)(9dQ z5PP_%=~L*MtEG%QiRHVf@ShJIdx$@BSpFyjk)n1OR4?h)fh8}TC6>_RU_UZQwy&rI z_IQJFMuwPi?!|`!&g6v*L3_cizuvIjIpskND*famMyz{4aFf zV{j$kyFUEb&Lk7twv&l%+nCt4ZQGvMwr$(CCi?I14|UF|dY-CP)h~AU>)w5@b$u>G z?)h{}3`#VnlC0gXtYLDEG)zp6EXh!H9&rfix{}s5jv>(MygXVn2>2l8o zUqMS1-z+9rt0Jrs*u-=H9DZ;fLBOO(xf;~QI+n$h9PVLx9%yBX!Oc$gM3I?!*YGlh zUPv!qZx4J~l(Z95SNqIr}^>8-rq84&SQgIfO;}>9lj6iNL9-sVy=(C4Gqn|EQr~DCkht#?Udx zh9?0C$ogY<<;RBTb=)o?Q~6Kb0{qq$rYcrU2E3UMlh|1Fsii^guWJUp3eZskH6+Z- zqlA}!vI_sQI6P^>f~&N6>u-%(4me$Of0*)%raR26(>`eZxOvV;N}A?~4BRe{o92OR z@*1t~K1}EfHOs^Ha&pMF3FX-0eA6UPb0wO&+rMIwl#OIY>S1g4V3RH+gQyMrB}Pk) zeMijFEk?<~fl35&8x>?YV=w#ubx_JdEnpNkFA41A#CuX)Ymi z%ByFPh{A$o=nl3lUPK1cR$s}Z101YG;j$JzcbBCMu(*pcCJ(q}J-|=wWEef+&Ezg@ z?1D;QA0eS=Fa%~?sbZ6i!3nRzjTPh4#Ux&RSjxV{uJWsRYDe^l;){;GkwIj z#$)ot>X@2T<<5c2D;f^v!pvZ;i+o;pa~0k+hO}i9ley#u%}}R$T2SgcRtIty)9~%( zb14JRiLp)uqV(esGLcKECOW(7`hIy?h@ghh(`w^s*ox3{d(tXGnnT5tKt@t^lx9|m zs$LaTzm>FdM8tAv)6tt%vadLDb4OtfCgm$ysS=(Z;7dttQyt)v-{M6mSr<6}Dxm&w z=Mej;qyDD~o;aU2bkU5`iH;#qNBfTwk;^ckQf<%SdL6!|wH_gu`vDS!aE))iK#`$J*6zVr~nf{mOs3bE9 zn=#2$IozGmn)Rpk>rct%4pKUk#ODOBap2u%&SVMWD>s!5w053}3XS&EBb90e)sLdB zieC>Is_;M=csE@WM4hQTC*wRd^fu{F!8=%T<2^WO=8>C zo?55AN)&oSiF4czo!u`OH$NUHCX6?zRva;pD;kEvLIwVg0(ucf_ShZI*fj6jZAd13 z>Tohhj5$y<&i|;GZVoCozXnh&L-t;j0n2d3L}gr5Ro_+b82C)RBY&Gs#C$(Ep?#kK zK0~6viDg;T>U^)K9AEByb9lVp?%Qy`PmZX*W~_NCUw;7>d&;+cl58pRN}>B}Vjvuh zn9-vzz$Y-g^NB%cM#e8Oc}zY6tx7@*0#ehOOImaLgfq%iTk=GtPpz(vJ$5SkW&!m_ zN!@#c`zZqD;;FRam8

d)$YG#M!%ioDNIaR2_YX|k>*|*3RM57 z$9L}javbT95}p1N=+M>2w?SSv1B(n*-bOGh{Uhh#YEZRKu1WDn=&do|U6MWg>XN$d zY*qom>!d34=v@A!baJHL5SRgnIM;c^CZR4PYYOHjS{JHjkQ*!UC|}TPzGcMx&$0-s zTlUv^Nj+st&izgOhF;QV5VhMmR_SUnkKpu~4Dh5~;W0(Hmnv=dKJ35m5xAmHfCTCt zmf18nQ6gavk)|`uVueXON1|pe=umYV7vFCfxWOb|-LUwxJc}}~DvX68aWyow2~>^@ zsk?_FV%2`Vo(#)LHghnTO<(&<1I@tb~;4C>}Cm7h~Nsdry9Wkne47!^v1x`5&pEieb zPCaS%6#m>QMh04vICY*$7--&zattJh_c-eV2VmvV*V*Kq2m9T8I#-A4Q*x`5j6X4v zPldD2SLk*5#JXb>RQ^{>7rOG9_}Ffb#-(B;y0A&e6@L%J8-|(*Wjcm&x%=%?05chQKPSe5Cr6^@d+w2HXuvD=?P8Dr87l!*?Uc9@zTPj)v}x9#WKWOk9vKj~Yo+7E%MS%oV~uka$3c8z^5 zQ`Lh;1i$tWLY$XyhN81XW?(PdVP3o8mXM-!WC#^tU(|AC+3$Vm4u{TWgkqORz>cV?wL_}bMW4=}t@YNFJ8z`OLJ5%7W|ku=@_iFE3C~tFZ5o%K z_};gzcMBLR4UR_0bLB9HHX#Ml$NHUVI)js&~RS5@b{FO}J6z?y)x zt}&rTq#kcaPj9yV{Zu^+?zt$!ThMOHYGKesgVGcqj139{8q?uH0t~Gdj`K(4T_qr6 z-$f0XWbImQ;_FZU>-dRH|0~LX+o`?RlH|GW_`n?FT=XYJHm6;yNuE1mbMqyR*rZ^A z5Vw7)+&O|u2y}nBu%`&1Bv>sJXK%91LJX%yqFNhM-Xe#h#bC%>GlNnj20<6s>8E+U zy${SlILiB@<6wcGoBCoQk}gAw&!HpPqS-{=jmXd_JO5l1$v#J{^+YSyVCy4KL_Ijs zYaB3ky`4#{!Q#TmVtLu_$|l+@m8aRs^8FD!giYt%YdEP2{CF&_5Y4#a5hG}i|CEk9 zM00yZY$UF<{7j(8&62P>yg;Os!sZ;@$atzJP^7okapj*N(`UIR9XJ-L5UFC;!R2b` zDr+RJ5+jIpWO3}`%~B@KCZDE0fi<|aepmEkGwnTQHW-_OUXU$WPz22fTvE4PJx66R zF-bawHI^I-C{RfyB9607{mXuZW+;psh8u^I;*LV;rR%EuFG@$mA$FIb>V!Xkaj=K=%caBki+6IAs~7meRbTc~mz1hJ*q$A)v zUj=@WFQZ|4p?dc&N0*xn#8k5ZwNcbpV=%^8&U7DazePOUUr{^VXpNZhVQ(co?fC&E zhU3uv!Rrj%~pe8^m*9zKb2>eAqfhWlv3DSge$!?~63?v=|6)u8T zQM}Ws#%|V=9oTjql3fMru;@8tG?2p|7TfmiM<<;W8|>#CsoA`)2`hu4>iw*yGTQ4IStw*s=%Kf5-=C&1&1J4%+k@^6*-PGV<~o-b}Kt$>cfwxr#Nq40M8{IghZGz+q>}0mOH&=rU&(lC#sw{ui8ohRiLLpCoigtozFiB@c?3T36%$|d2VgdIZN*C)P)z0e$#;P$!j=J9qvn zhLLPC7@nMn(coX6ErKkCeZ#pu?1a%jo-OtVxb>Lf3QX4>5%i3JThNnIJrJ!3HY?%mnhm#nP-Rz94EvaPHbex+)SvV6hj;IR@MDPd}tU^?{khruK2gB&D6 z6jiR(=(Asb8~UELLyk${rUXARS|SETNi3Lv1roZ^|1h_n3Dc5cH)VS*#+#n>=O|14Eiu8g&Ud##+F~K;z3)RZ9A?1W0IhL!*FwP!HQs`OP*U}Tzu4SF zkIbAtt(w;^;~tpK!9*5>Q1|N#*_=&Ws6y$S;+4cUEVb9V#&usJyt+_AsQm1>wouaG z_MR?xluqt?QWM-1hvFy5?Pu0I?0Pa=TWbS||b&VZ3tMY}Mdo-SUIVCGL2d>yH zc9ZQQoQE7gxeOua2^3I64_;(~oBR!0kfmb4bMzWK20}(ZxiIM3NCzd|_fPK-xx(0) zc%T5zZ_EKErPMfo(1aG%0O&X&lu0v;$W9^)eC~Skfr?dOv?oD!oyl;JH?EZ!H(+4~|N%a^8#_;R5_Hw>M^&Rb~% zu~QDQAClJ*9&m<7`8xdgQ^I=g{|8xSN~&^dFc1+F1j1#EwepbIHWhlmq_zwy0gLoB zARknhS|Q%GIGkZ95d1F*Bpi-&yGud^n~=<-`rUf>cws@m2-+VEa?lW*pQ<4I4nW`B z7aMNtsGI1XpZvueM!X8G3!0AHPx0j8NBaOp_vscziPZmB9w)Q*`Dt7!&rcwm-XxCW zyb|0TgMKI`>Ljh9DR4Dbmtp_6zzJ!-UEtrAq>KJ<1JRd8#X=nJlRMCy^)nH%si zd{NRL-$}&oeR~oLgs@<0^xbmxE~6&*Uh+4`h$0xkI>8tb*uWCzbP9LPE?41cyvBE(1sI)(7(f^&QK~g< zGWCeuU01pX%ww9_&vK*9r=R4dAg(Q?YBRmwdUAqtS3&Uo(@W%d&o61ru%(YhS~`RY zrH`!@vk@dZ6=mXLrLlI)wEVh_ufg#k%&%udj3yRqgyEc%Jt{Ccmx|HIEu?INP5xTr zG+C(~MAoBi%_u-S;&prCV3s=W$UBl|<5wlel6=AxnmO*6UdVdn{_%=R0aeP`(O4n= zus(;DN-mYjIJ)RGPwP(Hfz^J=nZnbYFiZ~|hbgw6CGmN2Eth-ilz;yUT}6PN7lgig zKO%?F;L~_`w*bmRXLt-JzgqCmS!c*EGeR|AapOOf=Y@?UXQd*>hWpP*SsEj%Q>DqI z&%+WV3qLg6)g^6Ibc0q%y2IREuxh0|A*Y*-K3ZFuI<-28jnE{iF_M5Y-)er_$D1D9 z$CcEKlADZVnU#9=!FnpM6+F~83>WC5XKR-YC%M#2YTUz`RaBJb5$dyvK(s-78%jWn zAByhwV_NNhO@|il1P*Kkx_X9Isi4sgfq*D5)0~P79h+3Z$H2x$d?@N-R&3rRd6on; z4s9he~F5@pH}cSmN0 z4uzTjW=J_uH~vUe(fOHDjeX#hZMHvIkf3? zEsK4ioZ3by0hh(~PY$9R>+v4}3|n1j$<1F1^u5sv{}{H%jJX)$X0k~r{`@Lzuv8!I z0!tT-)WhMXzg;y{?uNuFpX*wQtLP|vbAr~0@_en)JiQyDeW}`@weXrUu>?4sV3BDA zqI8qsGg68HvGLxz$Tk5^dGm^R;xIV_HcL_LSfT5myf`rCZtKvpeE01GEB%_l=^&!>~+Z|maW*j3u zfUVuP`iHG$20d=0vIuc`s-m+P?h5<9eNf{58fZ}Y2;FeAVf_LXQ5K>1Q$Y%QzX$wz z2rZS%>2fn1@^!m+K>OZf%K_X5SlChDeskCtp!gVbn5G8y=)2*UKj^O;BM$PC3oZ`+ zE!Pf+>57#B>&iI^BL1%XN3KlY<2_6#}dv9M$b3a64Byk*apJnVCJwiEL~_j*2twiac@nyYr-<3P+z!;1 zMan&WjBrbxoQb=}NPj!$O83Z#KHSdICzU5FSNDAuU?Q6SlGK0=)!KF&{)8Ju#bAUD zN4U#Eh~$<^)>!BJaaKZU1+{5)etS?n*8 zR()bm$Y7RlPmXLcr}t{^GcR%ePH<5OC6fPQxtEOp2g@Zn{s+sAKK?hB+d=~8^szvb zJwrhmv%fTP10}?JnNYL01miVn0+w2)%2M6Imu{Q&$?J^V$EFH`=%CBD2a(KYMA%SQ8Dj$wS- zN!9!$^yW_b`HfIKJs~hd=`bQnx!xLs{FTDJ=?lFfn;ycN#n5wN1EWd-$)oX{Hx=dh z+YAM~l8i6m-hM}t&Ltqau33&mT7daUX|4bKRXas`Zi5wa$l`XT@TwWP&=u;bxzgpz zEqGIMPCTlR_ezYhe?$sb!VR3MN6!Lsw|xx zqOUTO206H{#ZAadfv`hWn&)1lH$_R&9srajfmk#89Bz?f^upER3Xeg!;Si+ixm%pT zza6MEJNa{|K&-Mzfpwef7eKY^)D`Ct%_NYWMQCcYog4u~-8oqu>Icw+u#yZeBuWdUP zFg)D(9q1h;l*dwfnPiW+I?~tlj*AreXf~?)C!vS21SCJi;1w{X_j6Jn{yiR&x$q%# ze_Ph|L{m6w`&dJXBQyNU%Hk=$^~c9@5!cnD+V4lgKQV0gwfFd+`joE16lp3%IsYt@ z#(Q&A=qd43r3q2ha(KWRY-l8}K!1o*(CRfBhwrSxeU>uI>^b+umKn0c&#d1E zO))s-#6>GxB8k^8)!>>iWYvm;8_ltFeV*c2N-4|7t{Zb+Li(;0+;!%@AZv8C5c+h_ z_AqKFi@}>(Gwk?Ch`Q3L^oa3rEAPZ5u0p`N2D%LMJn_K$wS3ytCTMiqsR?!DFTuiU zn(|JV8oyatR{JUMU~!(2ZFL>wQ~NOLnM`&89uAZT;&2ClvI(OU@h}Z4G%p&RrEaDv zFGV8(|AxSHvg^ddl?YPM#t@BQ^k^N7yY|#k(MUPZIC?Wr-fl)?(x5~#r2HVz-HFNk zEH81qQPgMC#Cm1A#qnanh0ug7gsUn7Q1)psbxZ^p$ETO4=4>#`$)o7-P@c0UH`*N4 zktd&0viyR6Tzl5MPDc^S%SU^EeWb4p!J38g5+>}|J8X*dic@Sb-9n#*H!I$f&x*GI zAGiC{y$sWDon6gh0Unyk4}PPdPL#cfsh?`5VO@T1W+J$$hpI|;tiHNk-_Ob89457M ziMHGIZer&pcF8KBskh)0+#{e0*uo~T3ZZ)bBI1jkcUM4$?q0$LA!g!gvJG);m&TXI zXxWD5{ySmPZXndw6ys$XrV>~;a`&QbN+70XkP{=1hm~658VYmsP6RpM+--^|zkV!` zHxA_Om8eM9(a-1US5IH-?A=hJO38wMV|Q(Br%os+nj?GnMzNZpdb`7-q3&f`kTx+? z#g%t81rct-DQ#Umh1oG$0%|VueOjIWu8CV&H=cqYfgLNiX2`Iaf4q($Ez&r2fm5^* zDWS%w$y!%)9#T%%zvUbwrxR7l^_!MRw`$Xy?r9VDJ2y9X_3M`w^>;4dRlW3m^0_@- z$?oZs;u}l+#*o|b^6g&#^myjT{k0OA{0-RNvW%d}@q@x`z?r(I;=Szrm%ZyjU1B_a zi1pZ_lkyjR3HX26yJ6fpF}&DG=pzoJR=XIDp&-pEWv&`tcqvsm_cD{{1G-YL+)(!4 zy}!wo9*OGr?N-Y#Z4@WfQKXmBj91>2Z6fRxc`3cF3F3D!B?+V z+#t}D&Cu2&K}GrN^T8eviFD>k`Cc5}_7^l17^V9+0~zJdF!o%q-VyV@2!45Ajiy~vFyJg zwkBTxyPeTv1yadmd$-v2H8U;^$tx{!YW_plBXVU>lUH-nW;1*9sEJm){Pjo=IEqsR zxA7Lb2j149WI{Vo?(HahylLc-0aC@e?{dg6WG4~z!w-9abD8hV@v*`dcLCh?l>S%6 zbzIBR zbjP&C_yzRqi`sA4#>ht)4@Q$wM4ObV5nQ?nP8q~G9gl-zPf9}}u`c?20|G1=Enx+2 zI|!PKQ9L%Cl8d{dEx6M@Ot(Ne2gh&@Sqa{g2iP=6S6{+j{4%@LNcv2|nT_YB(81!d z&LUtji0P!(QcFx`-aGyRZet0ww-pSAYF?#=MP!#C%fvik+HtQr+!HqftCstor6AUg z!JM(m(^jvGd)3!d_?-ztMU=dYF%lm)EjXaCi~UCT2Inf-z7V+t+){oCbcd#5$=C7m zuN@|VraN1}5{6n}Wp&ZO$E^!K#=Zfyd;v`+Q!=!{A2=s;m44RMx&cm(20X{e%wUab z+%`J!1)WR*h_eSC8IWr&T3A}pZit|WPu9joDDewa8q>G|x&^f2l0wK-KP?r#fuDzu z40|nK*#BGF53Dmm-{XQVh-nmokQmt2Qw-W@q;6GtYLoj?A@p**c6 z$9|#kll(Aq=+~?Z)}ci1wfk6I?7;0vqc%fpQ zu2|k6FuufGMz)LvBKB+S!7u}osKOhG>;UKn2|`*$Kd4$uAPKfKgHTwTcL_STRF!q$ zq=A})r%5u147?;GuWaUe)Qte0nz?FIMQI|jbH)}d+T>Zb{J!XSGu7RhO}y0mZA)O_ zj_wV(pZx8fog77Qhv!Y~v+vdpc)WYrcH|>psD^a2kk8Lj&_-0}zw4w@>^2;Dq~^}K z^~XIasXMt8tnOKX zwl$2Cm28`Ri+}YM!0Pp(Fm5guiLKY!Poc#w$JFsziG(i)Q)6YJdgHc8cPW$E!K47n$@SH8PUp)jZwl# z2WzA*=xP)Stesm}$e%yIcr{YlOUaJLA!5(%JnIP0NiQ&k*2gnml1?y7E(h5r?PiRg z|52YgFL(*nMbchNusX*nk4Hfmz~BT!LviM5PdMPQ`y}x6MQE};IEs5VDC7eIItD$& zXd?KH=r|nOhOWSiv-AueLpKB`vDOd1*(4QJ*uXMkdE$r!&^yBGFtZrdiViI%&zJ(N zaxasn*BoJ6pC!>}&}j*5%V1j-<8+|Tbb_1&a^v98lM=gwRS8-w%k|E%7s0n@@ez)I z5ESH^^72D)y!)20eiDQL;9jcOwmB)Hac2tv+`FstKX9*Pc?1CNRZ#-Ky-JI6*Gb?u z{wQ3!_`@U+(=H(^=XV7>u7*_3+cRmObN~(EcZP0iC{NkanTL12WW@jW5b~C`1ti4? zZq0~8(YR39`Xno6kr;m{J@N>45Xw-P)PDwtp41^L#~1zwL@*R%vAB~h-cVh0SkfMF z8=EZ#ZC{Dmid2@z`CGL{EC4}+Q+Gel`Z(Gq?lg`jl}S7=fdU%Juv-f0s*f@Occ=&)SAe$SDd{jF7$-TjZ6J zXdQPCJ+>cg4GO1~o5F)-=5~EBiBstK0aKP8@y)3^lfL|w%46k8_@+I;*(gJ6IeLCm zyILa^YSef}0z>ZYN1+Co&u|oqY_yEZQUw|V@1=0%Vjjwr|A%tv6da(ydLe3D@xv~q z99?A&%_%P{i6*$3aykGhZc~8fspj&qiu0NDP25In+P5T>aAiEo-}H{Bxvg^7I3pzZ z7Jt#A2zUj--?2N4C>mD!U%W)X$!u%|`^4UJ-xCp2>VYcvHE_PrR=?pRO|8Xyj$#?>^s zcuYu03jJ_H(q-sac6H`*BnO0a``DzbRjBTcPB|GGZ%_yZt%UH?t= z?ydq7;21~dw!(!xnbcnw5FefXnUiEOCc0KwT;m${d`mzbJgmWLM#%#uvOh^1fVL2S z^D?-H82$1*tP^seR8zt1giIEHbsnkO%Au_ULJM!BT_A_XZOnZ617p%$CW)h6IgaZT zJMZFryW>|@Z8Y-NZvO)!2%U8=5mXAD1iXR3uofv_ETf_K0?}BITFj_tAR{~C7(+c& zKKR)LkODVzLjhIK7i)2XtKQs_BqPnY$vqy~r>0 zfBC3~PV_E^sUj-DD|m0v5NaeHqC5`!!gNA_{9EV2s>US(7rKf9ReI=bqaqdDKF|@P zNYlcYI4A8HZ}~S&X#L0wTVxBB>Ev~IaDUihtZ5t#d}ye<<*F-!p$s3jg5R>c7d{e~ z>4~yYufA3-u-$oAA9J64r@D*IdU5kgIrO1)55(Rr? zlV~Spzd0p~cGAR1CKOt#8ag#dUQxbCfdj#v!adD8#3;|p7V@_eSO@AmcDm8XNu71q zgyIyv1X>8GYp6NE*2Pl|$?4=V_#^XwY~A3zP9J}@EPX%@9AN8~9x@`G88MAh{F4I* z2}X_E_$301gg9K$gPfRVYG|!t4AL*dkX|sy5k71p%IUZK88&g-x=FiVFDCh_imW#u zun)ug?z)NOMkZ&29ABvd>md`tMQIMr&hMO+8STXdMGfJOgw9RHH^`mjPw^A8`Yr}N z)FF`P95ynu!UoI9oFQ_#?m!p)Bo~PsWg1;@KRj^_M=gMjTRGC|SzZnSS&057p3)Nl z>^}Y71&&De%S~TJ$XJA@Ui!Upc&+0(;58_bNaN4ud}fd4H>lpi5viJ&G^&)g3L+=* zIK98Ei1|ZZo;Ddv-T-an7ZZtH8gNu>-!d!vYVbe4Zem^!@JU7)tYL`o?z}g^vq%R5 zg_!f}fZ!k5gLNoZK+t+oO{g1CJPww0YHw>TsszL1&58-r80Z4*t)Jiew1Cro5<%m=} zto5Lx$gv{z5C@BEFvt^-FU&PYIry$mc@4;pJaroRq=$j7aHh*X%@Pw1*q}3hKOWhT&c8=P+ndkaza5 zx5oX8C9y-PhT7x@uO;Zn}Y&T+}ek2gqnvRr1* zl!E`BZ+93cd{Q~-GR(e25w-$~#3<^i|MQ22nq6O`E^XP>O4Hs!wZ%I4ZdM@lv&-}y zroI};1(^p06Y3y>6?w%($3SU11%Ag>pg_USjzshRx}QR+op-8$$PPHp=1zrj9rkY}5#jct_;3{zJgDAbhnB69sAB<1U(T5B z7wWNR7a>Cr_MUsWos>EW#z9q8%CC=F)$;aJG#|^en!(@)KBpBWZTxU4WyW)K#q24Z z^A&cjnV79g$#v8jAO8ZZt-v>&JB^cN)P!dA>7{;-PP?TEK&v!M_t?7wN7Qox!{(X~ ze<03*0CnP~H`^HJP_QZ+XA6#7s3>Q*KYPZJTN`lA?W~Mr$>_Vz`thnV{g^gbzn9u#fM;ASH(uqBnOGHmMlY?=+QO#d(@(b)h zJ*EDmy7gDh>l3`!`C z?o9evs|-k9=xG7Dnu9492Z&1LX{s~ZR3I%?)gl*Yy5*^QpQ?&#>3-5(MNv6pfB79( zCST2^WoEWSfeVP|81bMZXsB>GOB#=)H*AAHN1_;z|7C)K8FvBB)o15a;2^@5&8Tv) zuN~Z-)euw1T&g|nR^42>H-w8S!tf#B1NW!SwDta0d-JlrZHxbqYm@#Gw$@K6&DHBH zoBR&Refp4-%jNUE`%fHj=G%!Lz!SSQkAJ(0&A`|ABEMKCzux5V0ixD2Z@Ia@+zpPu ziNAUPKR?V+eeY0x<8z~R`hWOd3#+!}4235vHw>yKsX2jY1*^M)=-qJZQN=C$+FkAY zjQVN;d}8B&jRywaf3ZVU74^LT-5mZ{srFU>n8~sE2Pg*22B>EwzqH1D*~z|}Ccd+d zT{EHEZ=(CP4M7`H;&P|0k3&m^dA>(jEx$E8ujq^)()Vp8Ei#)38Tq)Vy!vXc)UnhkmL#-%W*?3RC*lhP7;FXJs9s(FEZl*CILw4 z{=7+brk;IVLyNPiS*bL$J7f^PflP+0J@gJ3Flcp}P8OzxTev=Wlwa$qkVri`&lm6T zB6xJN)L~`nj?YG~nK5yj@Ip^5#{&YTeF+rQ?hIIQzdY%cm7AyU#>~#Gm*Hvlp_{MY z8{zveGAskB@tM>Z{=9XUvPA<4s7jnL zs~epoC6M*atNuny!5DWVTDSTGrZ{bd6+^UPQlli$>RqEGw$gsFoiXN`W$lV%&G8c= z^d(Hu&`L@|k*p~nt}5*sgr4v9PzdM06Cb4vBqXbXxc7IhT8LRWI$@#rX`2Wx57TS` z_*5z-a;^DB3<}hERuckCE~C8nr-2RcSr3Gl05wQkm**Xyi&LOMOGz9vr|7#Km1d8- z&3EnHzabskD0WLAObpJRtgO1u!++_%lNgNKixjN*?w1~!jRl2zI4M_AvzsnAO1+nMT zT9Z+%S>n2dsv!H0F~(*36~%in>U?wN`rCwkhRK?LTJUn339_LYH%xzz#ZbMH9142K2%u&rEkbTvOSZ~SXt{Kn!D(J=n*gxV0nxrPHv4{~MVQ7$3kH$mGg z^9N+7d@AEe{08z7@Ca>3^JA1Exs9pH{r3LMVsd7ha_dC|u zccm8l)*mow=6CsNx_3T(-;{JIv=@`oxC77PbX4AcOru;|yMp;k7HPLuyk(Q8)Crjk zn0%Y_MF$4|^A!iIB|XUVRFjg$>!W(q%BM5Qg~}H!a*fX;h*B(NaGsQdPcuC__P$Ps zt<8HPhN=%G&ccsS;O~w}o^u^_2N>{WwG7@h`YevGBZw2Lj2PvDB{G@Lj!m41^$D5% zk}`;%@K{!6>Ik^OP!qC^)Axi1+ILsxg(^6(Zj_yBaTq#o^o;N)rC8jWE@n{P!{g> zBNL5}AL{j!c)10k{QsqocRf#~W9SUUDWK=1I^t1VTGkD0UMMZMq2Nx$OR6E+P|DAW zo#Si{Mo{5_?cFW_)l>m%dVf_TJVBHoj_Do=Q{twse>)b)oFADEU?9)}w_(K$@ghCn z>KeFk?>!P}AL6bhv39P9SEmJ8xJiJW+l~AOKc*CzC!dfm3Q3|)4JdS9se8;!Vv6{g zcXmWH@&Q)#S@#oN6i)b8l-UnZWZoCHTw8128dfQ6yd2eD+CT^vvW1OjmlOB+9M1x- z7mIo;@6Fl^ToRhzs8X{Av$iupBbAn*(QN5lT?Vnck6mTu5!6}ur-erwRrn~~U& zO|+MTv4Svtse&<9y^y_{TlOmHJOqAp z+*TpGLDFjJ7=DC!IMwMLEO6E;KDyCt21K5*nmUrwX)aA2>i3!;AF!;Gc!q`2S?FLHT9rZiohNW|;YVBVssC!z({wAtM%L;ztduQK9J-C&Ds5Y7#(dAK6V`ai z0E7lB@Q4sr{86hD)m1Y;bgb^{-G|?)To1dqhPo}gvAyGQJ96ZGm+&<_9|w%Fa@yU@ zqAB{(awMI_b=rH!sA^!%5-7gaZqzky|u}@cDt&017mo_Yg%5G5W;!J`E9! z5qA3;<+d{F3AwPng?V62J)KHyROEZ(&ply!+PW#$3R)3TwWSX9>8PRlqTl@C6KHDz zIQe%DHV~gq&{)eLjx_z_!TIHzQgje#j7xX2fs`<_OK3jC!a=kn|HhElSkVL%>7>O^ z1e_j7iCJ3^85&~u#YRAoetrPBx&Naf@0YUue`&~v?f?xLSs^DH5xhc_*yLKv=#y^h z0iy*bCmT$xmIXQ@8@d%@Co7{BZp)z-%7C*vz&~E)-l8(CEZIf}HU3gWw%ys&I(1}% z^>auj<+tKu54_bW+dxGk0vRq5CSTk~0#buo;Vz|u>7ydQ%1!0cA$!k4CAN>NZB1DW zD_s6j1O4IRd-Vn0SMp%Bn$1bWbKWm>kITr{m z9K^JQ51khB#_Eq7U#=0okibP~ZYd@>v{;)dC_8%@N^g|>7~!qRL{e!3mY5?z-9%yE zuKU$ttbGAn7nqX%*jg0Xu=$`WEMSu-foaF2a)rQ=BDzdpKNB{R=z^+70Ea~tTs(vf zBEo&$RET1%b=^{P^n)#ufIM;jGK(@%_N8*}xkdNNZpF`Vq%WXRnd$TVe6l6y1}M;7 zp8)~AD zy}uwTT#E*HY7K?vOow71ATfP1v3eaH&5*XuQfNBEbPcslwfGi| zjWW-3U6tv4hb$G=bm{T>nTb5v4CodcG@ddU0=gjLcBcuUs>7u4`S^P!K-R8wEWoo* zeo`c$T5tO^7`$H`hhwa>b+eJ;C-l+nkhC$u8EU{=*on78J36I!-E7d`^2!@BD{4$i z6czLn4U0BZbf zOe0;ef{HzJxJ#|5ZM!li>ul)xJntgRB28>@&vm^9=1HSEDCU6#Pl}@#MdtgT6r5>{ zWQ+dV2)2*eQ9#DkM`_N=Gf@rA-wQ{!;SFyJ>;0{^*D?~eC;^wTy(XHh+LF zv61}N+OBC=l5>{P$_siEUtOdGCYYHl<9=pxY~$UVFWWT1KgU(`yq{G|Y5~f4YB+V` zgKt0qgY_7sS zVdu7Ny>v(Ce`KNao)`Jj4lS(oyjtxN2Ok>yv9~TBm&zBDh8{chzX$(zs>8_EeqOJi z%RY3Q7ye@0^}7ngb0pS+LyW;QV3tfIkVXDC-PsQVYIFl0h?!5JX%) z-HCak52tiVL+ij{o5~c4Hb$)GTTKu`y^g}%^Fo}k7z94iNfko0%yX?UDVe@VP|DD< zMB?&|vNz9vi7hyh5t&vXCXIGJ3Z@P6#Pu~WXlb`#ySmquXt&Uf#fE1AfQ5U?VI{^_ zPPs%bZvMcZO%~8fikt1{OvwFtL8{Sle+3QXPIHnfV~#@(!OkC%ZFjtqOWn|d80gz& z^#4w;N4U>58uCLA*_`1WIv37!MT-C7Kay;?K3G%(a7CF}l58&)l?>O5Z@%rJvaW*V zKw5j8M_5pyN{%~Qj;Q&|p-R<8iX%}=aC!fauzL)y1l$5O9ox2@bZpzUZQJVDwrzE6 zJL%ZAZD-Qw+_`gS?o3V9uG)Wh)&BRbwVrpi(ScrCq7DDHXeg}{9i)NREg&ybExa@= zP1Dvazl=R`!*hcQt5mgn9jjrxw)He6nxH1PK%{p=Eu*Y{Akqzlg=#`2)ObZZ^Wq3j z&IZQQ1n)f$>MuK~sp%JE#+1`Z@zs`}c!K@#FF6q!MG&rsF)@r{c3J;2hr-slDLc>C zZnpr7!C-D!L3E{LYu?YYC?Yaq)_uVL3qn5pfsmJYejsGV&wmgyxQvOoYB?0F@=}$) zT5*bHgVDfz=|Ox=a>(L%jm_-7Oc^q0mlK`YAx6NR1VK8I}H1Qkiq^z$oFMbrXD55SPWT5QhYUHj6<7kk{of(v_VuH1?6bh!mX^s0Z=b(GM^M|ke<)teJ2Y5D zxcH%eR=T&_qlQsL{ZmXPu9R!$a{8|K61!OB2!_3lL*&n#fw5H&l@yi zgEK9cw3ZjcqsYAsn2Zp+ILSp%q9hr=2h6eL8t=~wzITWkhGa9egxp^dpZ4vI4PDX5 zp+#j}+~x#92ABM@Q|KG};-S{``Y^#ku8*sGQfV+ATF1CN%sHgq-&u z2w61!AB3F8EB?6KERFD}&{h@Wjy!V40e5^LerrI5={yV<$nXmyQ9^`*k&~YYdjuPg zZ*4u;BYNCMElBOrmF$K|lEgfGU_-TNc7}WhY2O?Rl?FImBN@*0=8Si(&0oh`bUw-r zkKBoyi94JOV-;YXcZgV+f*4RZ5fUcb(CXG_5*pnmOL~5`^wP$z+5fln63mh)hteHM z&ffwcH#YMDZbLv#VQ54u<5tikvs3Sgc1+Fc0T>MeWoX#emB!FgXC-B-nX-eQIoc~E z%JlTn&!&oLBT1m(e=+5x&L2!UCbo=4k_ly(b>EnHKmn2Vx{Uco#Sq6Z-CdnvwQnDY z9KwlPURkdX%<1Z0WQi2-A}!YxOW#Br7y}2R9vUXo`e~RcKq0OTB~YQRZLi0+cN*K= zX=CuuWTZ@BZWijX5^Npybi8zrO8k|0Df9uq2Sg$|C>60|7(*;K8ipp;3Uw>ZRzvxC z8Mh2a!T9$yTlU4Vl8Uphq>}_qp|+n|iX+ECldTUBL)Qbl24)2SymfxusdjuX_^}TW-`R`&kU5 z4-C_AAHGo7AM-n+VR5$(gd1nPm-Gn6VOgcJ{FxiP$j;;daWb152V?%ZOYgM(H>@dp zBXBuf=u;Mg66sXXK2Hi^Z>W$p)=lYynQD`Amiw(jpAZZ!Vq#^`6VY-^5l$#>mYmb^ z2{&UFusSXOxq6_lDdg6_tR)5bVi@L}K`-siLWqd`X`*iu4US`eJ>QN$*8CuwZ>^LT z@AC&LU;Qa9^81O(kn6Pzb&Hq3n|LTW2j4~V3cIqj@zhgz;18Dyo z2oC+Y$>9IoWM-*V*Z;*$J~by4j`?wuv;XTRuP6KuH+jryP-0a4uZY`{)Fl^kR)=Ob zJ>8!PpXPQ+wJQV5zhYTLW0V7A6$#;r%Sv0=Q&h0xq+1P`&{@grC2EFW$)tfq?T4(fPR^OAr3IaY@w0ZJ!D8E@FDc^k=`*BDq}x|}l7P7?aFyd#}1nRBP3 z^}GLc(?!}i2Ug{6?!1%&v8UDAfm@_Gkk&;e3_-Q@1Cc`X#8HrK3 z%i~Y0gzKP^jc+yXxU+UVQQH%qv8nM%ir}YkYU7%>6PAL)-*$cJ6E5mRyFW2{k--Vp zE;z-)aOB?$$3*hr4c8-TjE$_;a&Rje9vPNG;C;}_+DGeU*s6%;9UTkL)+z`K2}t#W zm^bP(_MI4Q@y&5;A|j?{gb3~EUL?eXDU_6Wsa?emzDoYqri@#zMM`>rA)Uh zYd=xCq&>k1)}dM3ZW~-?%G6npRMgj9K48k~SXp?KtXgInT+n~EGn+>qN3we{B@rwcgZL_#DVs{r;wX?lFo_Ec7V~^g7j4pfL@LEmXy`(S>SBKK_uw4k1S20jab} zc2$(p^Ah{v8h2*2k}TzsFGlI0?Z!B-3RK1sAzf(6l~grB1uB^3W2ou(Tyg*P+!twU zqXD>*Uw7(L-StSJ8I)kghAy3vnh>SjNj~37bttAeRXQ)w^$q#vU~ug{qc~>+yMiuP zcUxgwSZVlJqyJzMw6L`l&4IJ{5{fSZb#t(H%xRNTe`%4k^5bt@nLWzlWurUhxHq1c z{+wPu_NKjPN6g^gEpBfUnB#G|pmin&aZDD}^I{L}(k4+muQhOviF1uSWY{?qY(dsLyFQeZTLD)q5LPaW)&ZR z-k;E^B04Z4->CZM5g5FfCNRR;B>2_d*AX;3UC!aDYdcUuTpqIy3N>>>anf4LaSYVzJoCDi8X>WK~!+L>T) z&TQGcr&#m%($VgSd;#_IhSh8#>IrH^W7@tex-G^4ZA(RFhXL`8W}9La44ewskLh12 zTrhl;r~D1~7Y@FUT$tuA8Gp2k6=c;*nM*59Xs;E&o4|42>ad+q3f_1K+~Tidapm=# zozP^=UIU@8=BpJq&3;Z>)A#687eStSk^sLePrZOk)|#=|I!FjAGr!(mz`*G|XbCS9 zg?w|4f-_Q#^09^F5}>6QT>m)tZxv>f^*DX%a}G$hH1XlqDrZDfNR-W`^s^uB`a4gY z%v@fefTDnof}4bWfT$uOC-P(mVg=FKx?Np_h{9=8|IFyiZVS&@#ya642S!L*eBH;# zzO__nd57>^1bOU73{RVkajs$8MVSdhrO3}IvA`n))`xH5iI^OCxAWtX|CMz0(5&;7 z)Aj^!N>5o#8(DcOd z^eG+p(KfjjUGst2n~&8w>Bp_^HUjS&6L>lOeP?bx^RKgUmM*`%Sb5pvOW#1sQtSp$ zHXU0i5!VLE_)V0Ei<0tD+q+HM=GJrH8ocKp3|Ft`E7yj{@AY0zYueBE?(S5|-5;IX z>*-=_Np34~9m5~r`!jIr%N5hXz38Ub17Od@Tb+xr$2no+i zS5J?UP$${+uCK4UcsAAng38B3gKGNknMmc)(2MLxh{u=MVd*FeuPlb0Hi5y=H6{}p z4^N8#Ug?1-jN%>|UW|3k14-+Mb64v5BgiNa?BKdS2V$OEvIjl~cza)rzE7S5;l;M_ zxvsabJ9*Z&xgOxQygI<`^e*?y3BBJJ*FE0huX~=hyU)B7q=|GMOj2f5zF^>EN{rn^ zRDR7NAPfuQt=k`juXk@zVgW1kKbk7I;vI9~p5;GY$FoIG?+4)DYh(wQE-l5hqCNpvLU{T+1~mU%A8x^Qo0LqWEOcf^BD8}rX_+!z zP6Xa}i@6?lbN{{eGLhj#*BBV^MUwps?B{CT?_e16(Cy-n--|xP)W11EE7M zy(HH|GlRyhXU+v$%2!WrTS&z=(LaB0kL`?{SO0T}XSdB@;82W)kd#93JcnBW-f_f9 zYr~$7)JUKkkRkA@+6BeNCm-gT_9SaXmcn}ff5PEquS&3?f-2~q#9R;stTS`WI&r(d ziR^FoZK#@MM4Cg@?o>_Q9_3>)>DMaT=0b}f1+y{{@e6ZA>h&D@qVNtqQrT`wDW(NZcvi%|M z*;hCidlZEGw1O@pFbJ%}+!4fCR~tNHv@X(K4H_ti<^;6^#*-GtaWrZ0Gp}UR+H8tDPlHQDT?UNAK`4l%)@D6&gG4 zv33XriZHqTAnm{#^O(d46Fbx9>DEER$phw?P$R?C7?9bE;K*r2Txi6^DsDt&i^B+W z`<5^=Zg(wP;TqQr+onmm<({5-XNA6c_Pa#9yVqGFi9an9oMxF#6M>NPm7+=d+yP%$ z*Mt6WgEMPsk@Ez%3M>k_{dT<}#mO1Ls-@D8*nXm?3yhBUSUR{Ks)^XU-%ws$;%7sG ztitQ|7V_vwR*SHTQ?(P#t8G17Mc$D2e9=*b=Eqt}_7yc=+>il!E2)*PHh^PM-!}T=X+o<9x%@2Ls*Cwo4e5!eInxim z|7qO$D=>ZP`e|;8h4*>?>zL{N>v(?gbNc6a>g6lu(!Rt*sFYQjnDqsQ~J z$NlYN3_9|g&*xA3w;%TO+1K~aM`q*uIJI&gWEX9Z8a_Rl>-wPMYP%=mcB8!0*=}>h z%Reu`2qn!Cz$z?q{#^j{D^)| z)CnmXz81`b@~@X(12x~^u=_%+oX^+YxN?5#>e zzw2THPvM(#=?3QI8)V>^6a32eFW4XZ1GaTm6t5Vm>Prke0-Ry-9 zoH(A`IN5G7V_0%Tu8hGWYKO06KKi$u@ec{+?a{_p*Y$K4F1nL)cQ$*57ve(ptlYux zZ_$}E7LCck;Ee|L^36cbZpKR7Lrii2@bt?=k^s&7)R2(+#5zB6xjhPLZTOU> zcd%aTe0D1!SZiU+SV{pmhxLAZLaNT;MiDzTetpkB$ls_)g>cw zS3OU_%)Nb&L2B7~eJ9E}|@mGG(1D(wj zhIHk8t3(l|TxC9BKuCW903{@!1Rn~>-Y8$*PnL4txNjerDLlOQ{$`bEysd@r4}e14 znY`&un1`uCpZMq@un^zC7eB@kG1~GnkZ>|eRoWmRpXk^zyA<*POLC#OvX$I8T%w!= z%3=tVoWk!B4e>1D!6$cn13NE9Ing=zpeHkLT=QSRISU{1BQd|AK*@a+5L_w!#8wmH zdTu2l#mhDf2C^~ur6FW!Vfj2m=-J@oX^K&VC_vm4rsD3!`AEQXxXtSS6doI)MUMVI z5%WP$PW*6q8Wo_LmXW3QIjCu=-Op6a0xb}rB`#C2V=}=#sbrHhg@#4;d(bj&FtR_W z*zsHlynBsHNCrMe=zm^hdn^HAlBSb`!=%BF;6K-1ankrshBy>JqU^!zE?>FuV|?M^ z+~Bt^ai4Ih4ST;@`}FZ4!{YXQ`PiAcO+h+R`7FW1E3OkxZ=KqFo;_LDCobwzS5=G6 zjY^cMEt>7Nf+_TH)%ZoSPdWh>L?laCPwv_KN3Vg=Vl~Q16<*wb9xGzWBZ0cWPvuaF zJa|zfiObS3lr7xdGR%eq830m*b-FlfQW33^RwmYE5Yqwug_aq}Y&{Wa?*QCwZl4MrbbZkyI{{qd`~%`aa#B#ADgE%{!$vQ-sQ%%-OS*7{QqF) z9?bt6W?q48N{ErTjrAYQoFj1oN8pi z!Iv%J%wbY5fPckZfGVtwgg{_NqSLHYuOC5v=^J6SAYX58VaIxG zzM3!3V`La@&}bT9UT;~p<=m7boOapO10`XNgb{}A`9sS?A z{~Kpcj_xt^x=9x9_8y_%8rw$fa0?U4&6TCkxe&JkP$!Vt^Cc?VGJjei7uwp`MIO&z zt?$a0Chgt^S41Df`!g;(!V;y3_efJqeRjmkH8wCU!gQs=9hXj+15|n)(GWh)X}x!M zp8%wPo92so2?k8{{@Go1$QQ{%IMr@x+|obdajO?g5FAJ5|As~Uo@G9U2^Cu^Iahbo zXuW@MpR+xX5sU+U6{!SC#13uCd0!!601Z@gYR(rXttB3UaL5aWftJw`27?pd(S#&R zg+tY-y21oVRDS}iZrM{_`wzC1vP0Olfy3p~rqs{> z-FIf$hKrjL(f)+P<&g=th?aa2LQJ?qRZ!KZiRbY?=-?uPkY0;o-M^7xESo+q+{N-J zz{(Vrjh*P3^!G1K$h&FeEIP?*D}bxwxZS9{q0p$)+=@7dyOorsCVYW~t+X=J>5kA+ z@Nb>Dzkih10dRw)H4x2|d)>P0Dsq zDsAPy2nR;}Q3nH3021(YSk3&n&<04=6#UvVq-%$I31rc z(m;5n+q*t7^5s+4u=(szJ)ngupd2xtG|@2&2e7^6Vb$pni-o~n$lK#G6BA;`-^0%o z%Z%VctlrWZ6S(oi2Y3vWtrd5QKm=9Xm={JBvqfUzd4A(_KtHuB12% zPc?|f{`kbm5KmImrCA4v`ueOOL}$_xbCWmMRN57c6tQdJcXOtJ*U@JvOfjw9rMYWy zL>X4H_AfJGP$d3<(Nje6=2{sz^s$#T1>zvaLx*GpE1PRzhv0%ecw~_v6ZTaK>!%lf!zv_waGHaqFI1{y zdMv=kRvUQMY~2m~$d>mt3_^@B>pKGXE^5B+zdg0+;8g@>c$1tvHXl6KBi1M_A*!DO zpLC?JP}vjjM|q+3Evy=LMAq~>X+b5n)DGSKNH`ghrm0>dPID=Fs6m!7sud#)EPHg9Jp=`Ri(j@KP9!`=dG`K}Wm zjd9ShO?&w9J~aae{_eY_jZsN)C^4sKT~xFEJ8XG=g1=)E4V=vq7ysr0`@mMPg5me*Gbv85(aGHzas#*z<{f?jHDa~HRW3-h^WKuBw|*D2i->a&%rw)3KN)} zA@SZK&YBJ~?}lS~LUY#|WI}YXMaOQ&7SAnD==-TnXD!mAPlt6m`|JZRw&cr;#E;gV zw=S;o($c2o2D{X91J>UnO)VL^=Et+i?J;9dijwLsA%;ZnB9w%CqZF-y&yWJ_Y6#%!nC6-bXtIWXPLTc5FmGbg zo}S9Pk05;pD!jXN^ouS^Ie4LU)Xtf}rkVLhUC==5u*Jl)gEK@`BM*K?(*6Wq>~OG1 z%U=$uW(r~!>Q(W0HDSL&+Nc~tSQBbXu(k{IJFPU7_%c!M*7+(%Tuk_w5Q%dmFU}ZH zAL?tAj=RK6BbHNP`gSB=vznM31=sAY*f&{`)=e?4A{CY2$i)-bA1Ce7c1h=kkDSHa zS4VUMhcgQ58_<9-!4)20qBG8Skn#;Pv+_SD$w4C-i4W&8-6O1~x&RE-T~aJkMKYJT zx%48x4+zqFl@-udErHA99{c=50WfUNS?azbeFviNfv+jcOG&K>a9Oz&M+MF+)eRi_tYW=)3wuV>wcsQ!qqZ3{a4z!+T< zF2GcE3y5JURtIUWtm|Qb$O$@aonpu#P3M7DD>c7^lMK+wS%*db8^R>?K8ZqldcQUtT#ue8$ovQaRZ0j z$_&34NH>zlkpQ)L@U*>lIpLIMHcSuLpF2H_RpT{th$r z0Sb-5QfO^xZbkzk*arb5V=t&bAAY)kY6aJNa7+4Y@OrE}`0e{T7xVr3Lzum@=B!74 z|FSixGW6RnJ-*uaX<}AgU z>MJk~s1TMQxCnP4+6hhyH_JfE68w@AW=f)j;_Xov>nbS=5qhgDNS=kh+z!4q4*fck zkDm^{qZn;#jKAL>H`+dW9uH0vb6ZsJzHxb|U;TdC06`ymso|nQgo$_b@K)H-@Whrw zl5hRcUrcVD9mYploD|EM7p06pN15z&!XHmZ0sKq~?lHEQ)sFa!rt5tUufVbM{KnZ|Im5iXy*ke}Wkp&H)cUQXS88n@D& ztgw;FN=_ZiMaBt@Uah)$zUqHffC$B@Bu?Eh#O?o41?UpT|EU5b@?=Q-s{)+7*Xqeg zelH1JRuL5@=8ujg$&A~vyrw59($LpKJiFtO-CFaCgyR2})q4Yu{J8PKV^3>yr*C1{ zKyFBE?M;io6a6;WV)fD!oNN~ExPqWyIL_(#2pBTDcJcJ2!s*7_=f#s7HIQ%w)rQ1$ z8W%UY5k6UgD5A`}=H?tBxGc;P>Xo8zobgZIV?`*w&jOMm8p-DmjXH+dD94J#*Vzl( zB&K8Q%ykX;(-$8(Q-eb;ZXwwj%4kn9l(zq`2T;XuO@rv5(VDXGON&?Nrw5?;zw`i7 z6fq3~1pFFSil1QI$1gG@x?$=W3LbY2PNIh9D|^uCEDGqt`w^9#$B&jmdp0GGc_KBL z&{SG@1a7xEU1#WhZ!B3FOo_AlJuQP7GVe_gOjsb4p8lYzs1E)%2+>tq8d~vU3G*+& zJU-Oj4NbfdyrDf_=vH>T4w;PJ%ZAT54D#Uvp9(+Hfy>z^I_ko1gTk@%TKV#O+G=dG zA(6nintnr7_aqkfq!_(he6L8IFN|N@Tx z-Yc+K|2xc9iG-?>ikh05i5fn6?9W=%w#=dfySaVd(*i~-b{BANc$^ML!0(TsJ)C9~ z-ogp|)=Wi~vcI_bs+LNYocQXRZtb}SpzJe;;XZ93JBs$9ArqG!+!}?Ej8YWU88w=H zJcze)PiT~i>53J2wP10iHc$lI6KI{TeMqEx5w`#wR;yGzyOnHxCI<*Mq_6zyRGjBh z$oVrPm-`941dl%^T$>5p5z248_ zmJs|E)RsVw_|Oi(3S)5_fh-z>R9#s3B5K-T*00bGxW)Rrrn~IQy>r02bSO$ap<;6O zyE)^_U>A{oR@2)$i4Mt9N*zR6U#z4nuR_dKJ={$A;F}2+7U)G==GEkrZSX73W`EvX zJAG_r^D>olrDkmIpKW@=ny7W~I?4)Wd)WPM8p_lycwc?B4cH@LyeHK%W)AJjPA6FP zj#A<7JGM(vmZaPXyWFSaNaB#jGJUtx%&SMvcb$}4Q$I`b&8lblU%38^y9-;vPY0hX z@7bS$0F{ddI!q6h+5ym`%b{N6ef1~7;v%eyH#tNnZGgXD-_F+PJ8{ZpgT( z8)CqBaaV1L^GT#rjDfN}6+1VJI8VGC0^-=bVj50j3WrYZ!by#ZM+)gTS>Y~CmYpLHimRz$4nqt0Bso{9$iHej@8k&rUKT&v4aWi@&;QT9~Pt3?id z5T*3@O`od8g_r&*Ge#=a0BDMVvoY>KZ^|C3ONP$Qo-KY>^NY9`7q65E?C>PjnY4QS zCDA_}w#=T9@I_?kHarHTN>ZwIcOS+(m&$@)(;kke*TC$-H`#~20|DdKSf>RYcgXZp z57twKzuYxqWc)tA5UU)r0NOK&@faP(sG{Bs@}~1q4@OM`{!?x6LJQhgV|n+=`F35a z896x<1Gfm^!8_dnWaM4N!zQ433|%v^Oh?~Un;qwI?24)-90UL?$#V!JQbBSJWR8q^ zvf(8G85q9GqfHlB8SDt4T2O_~*_zF-dkL2Y|!b>HnvDA6Mx8nsZVOUt;spl(@bUY*v zDvGMo%AB?-DNMFBa;XI`*Wo#T!(i`kmL7vk$E3JAC1CXLbUoCNo6>={?AA3R|C*=> zG1X@I*6g4H@cCOn&fn{qTvwmfxi-mBQ2`lZ0L>e4AT=xq z6XPJ&x}qHB&LI=}46^-@jVu$e(wp#XcU<9hL^|EB*wawkWH9(*rU1t7O3j-&<7TeR zz1esO(kWpsjS4TRm{?aBP5n$I_BJj?6xV$DNNi~{LVTknlEt7pvEV#N(}_`ceM5Uj z$EW?ywZ?1@)8nxzTA)Z%Bo7fUUdK&Y^*c7;+y6NTGAahkmoYhlbeUBf*L;8Xs<5W^ zGKG;a&(pan?0_*#6-FzPt6tVvC+1ozev&+7){#qTEnBe{{*K$wji1_Kd_v*(Orlvs zmUOo&j_D{+l0d`oeCXb?@=nQOa4QtE8xOq-!#qOp8t4fw{nk!x;LcA`A%{3D!~{NY z(qH%-$!2bPEvG^iXQeFw1sWpKjEN~yV=|^70exT<(Z$xKD%dOJdQTgh@Jz?4{b7&) zePa~uR|$UUDhIPv;#jLbP^w)O9<9oGz(j~SP~u%$z6NGaj!Y9};q0ZQyy$ZE(t@ST zu#;R!83KiXQP3K8;jl>W=+9lQ^6m`@- z7%Jp63~f30M%m33<`FK`Mb7L-T-?`Z__6kavH^|Eq4eUOYq0d99koF-Qpv4%C{hXe z$30VYuyY6O|JGa+dTrOa13QWVG=O6vG$6CCuCqBQrE0H`0M-iEqFRfNtj+M8gB zc~)SpaHg2AD(7}#9%3Hh%($!140zlMJ>AnJm@WtAZ*nLJ(DckJf-u5QGAal}3)fZn zqiVDs3sv}{j&myT-B2VhpXu^g#osz@LvT2Ii|+QfN^LS zq8XT|b_t;NGX-jeUpzi|Z5Md(2z3f24@K6oT0ZNR{eoW}7&l;U;vCzyFHZEHQcTaE zRMPSeEdomCnE}}De4EWrhMN#9Pw{z2sN$=DIA;&B>2EHU8Ynq&Dq-_4aLwC){nSTw{DtO`WD(pIj{1@&I|6l`XJWTTe46)HiW-orNM7o&fYSYO!V3r)~qF;{>a2Q_K+<&YLwSWBfYoN7aL^&sawMLnuz4Gk8G~#ag z^R@W?{W@Vrm-}6J`!PaJm)jj=wjWA9z2osEbaTLpaFc!gE!MZT&q5;s3f+lGb2MW0 z9kN};4b|MRDw30vH5K@8KLr{qEx05}p* z*!K}ZJuww2(!e_bg6YVcmjHJu;C>)j_ut3I`=9N~lD-fP-+EpHI<)gzw-&dptLv&h z|MIcxdB_x`9YX?CfPJ@Of*Y{J7aXPV5poVXTL5DAX(j3DSeC+=<6{O0r`Q082(?Ip z8mv*I!a$C5I)HXVgoEa%z|BwDo9F7!&Ch>pI?p>TUEA;he9c=u+n!!^9S!&wUGUA% zTit6sE1O=>exFFzU7y!Gd~QFBI^YtL9IuJf>f#l>0*07W?T~_APKGf28@jhpfW&Fb z55~WrHObxQSw$>7LWr0lqd<@DKq(R*Xiz~bvLpo9sAq_mdVp{Uf((O`9oqPLk#4qw z&Sv0si;3f+h7JoW3PzyA9}Gxma3=lLTTFql@aXosTi!%`si{KBP+cI$@uURVdX2c? zBx`vP0xJwqMk<1lDu6`Em5*WoH|faMQRP(|Upx5DeB>D-3Wxpx(EN2wCPv=iquKu= zWc>vqe@h&QsK^2Nl~}AO?ox0~ZL6YcbfuP7Qo*1GrkI?<bcOp6|#dN>`faZai5sGTUA;<)6 zmnK_!FuH+)9trh+Na2q}N0ts^WVYW*O4ae-Nk>Vw-)2NA2{|`r?u3v25^Tyn8~HM6Y0wC z?nZ(RPX+tK3V4ggZ9$%FiVyh$JwL+dc5hA~ugSFXT3f<*#O zYXVN)m71RzT4&;&2D{B-$e-jAauA^T!XxJ(mL-SGrB2Ed0Kk z25fOC`1__T;D`l)W?PFW1kHa}Q7e`k)aqj0#5Kp9|I+kYAV(m_$sAU0(o6wKL@~uC zf%wY3iH;o;ApncZ$K!zAy6l8(O^ww!LV9Wkw}Y#$3rKAxreQru?GCUFp9#jxBFo9% z3O@B$mh-cjl42;UU@TPA8XrHrr_DAi-xw%$J|)SGCzbJe5AN}SB!hg~m z(tdS*#HR43(&`pVl@x-W0j2vpaR(dEE6;1jc5vMmF22nAlQOA_p9TDRrFMW3#KzX+ z?(!dsjI_q`^h5_KiQZWZz$Fjgb1v%J!7#@jV4ZJ?V*w+v+lM9Nhm)Ys9THJc)lc4R zPmET?NsxwbxIUC>eaMUQTfdZ&`30~yq1I$Ns)RG(&!A<{4tp!qvJXXS-ku_6R7y83 z!T*3?Wg|m6GycVW?4Ahsh&L}tKYk@X+Vo~&=8z)RN6VnCWFoXheTWrzaG`QkR9?NH zrRB6wi$6)a?2XRjcqy>LLzWwFI?rK`OxjJzC-Dn&TIwg@a6IIwS%^7`HZ};iQbUgC zJ&HhYzpd@C<&8qGrzWPp03s2HB;7XyTpM3DTB<0Pw%3RLuVun*L-Tx9Qby)U^ST;c zIUo9yGORu9*Y1Adua-@+~J=#>$(+mdnivL?fF(=5L(Z5OBiquohF(}1UI zSWa>S-e{U4g|k^%<^{O(Gh8#`H67+b*@;a@T~Kgva;d9MbkO(PWlDs1ufCClbkX;7 z$OLVbs)1rY$w5J_=eH-7vS-HULw61XK%FQ}L1(%G zG+)KR!p8wwD7O4tJUifv&V4tsb7%}i1a0~;X2dfKIa$qdb!vrufLBi zbJ;d|Sn{NOWGUl?$M*#R)h{8SrrOSIr>$dC*+0L*!D-62nZQ=Be`Rw0=b$N>*%#7( zl6~$#_H4SN$ESZicT%}H9BD45q(JSMXH>@g+vy)8JQ1WptC}mW6v<%f5!7KT#|evf=;kE6_*n(k|=& zZ_NaLO4+59ORBd@YTgO?Z7=}|p;Uo3_V<>2kX8@=2im3Gb=Uf;T~!4HeGxk$!tUzr z`c`+cwFr)G^V&{0*x~^?>Z6k9mIcGGG@J6F=O{`Za3u`umG*A0PwBuq~fr6Rq}mA2BwS@8$HdtQTf3i9sI zoaR$0n{IiZSdDsIAp?;PR%EVGF9u#E#OLuj%0jXC#9%NdxN=Bq5JkV4I3QjLt+7A3 z?v_ESZ*t4bcO)v^;t&&I(h{R_%mj+k{DVr`Wnu$WY%;6n5Hn?AE4!wJBl*1PHSr>x zVc(`;(C68E!cM+xYP#EXk0vVb4(#=GC&*oO5aY!75Ggf4`V+k6ySs#5Q{WLIyQ5L= zT-1r^LY^wC$*9D!uI~)4^NY&MjvR=Kx6IWh9;IWW;nj8hpNWh*(PXSu$#*f9i*Mbt z9REl^j27kUTXCBr15V6?~_9Nsp8q1E_j`Us~7?+H-Ne(PzwfqXVx^1kwLQ~gS zwAD;_Rtad=F;$mzkh&Y@9Pi>%)rh|EO6Dxd5U3|)F$lLt2*v{r=A^SrBPVy@Eup8E zZ&m6v>Ep*Vkxa5~#P3|)5}d77#|hUTj}tI+B>3c&*mE$jN|9DKw)l$cy2)YY7s0sj zmKB8t5<%)rCQTmsxm#|kmx4LMqR2;weqqH#mwuPiNW!`1k0uq01hSUj#UVB18mnOH zf?&KOMSKxpb;L4)h6KbiJjR$5RUjt}J~gn8Y(>R@Ge{rpi=B%#2m$k_1%zl3&NyKt z7X=u zYtyN~bQif&i~QZ7fMNNe()MKHeu?B=0k}0dFIm~rTQ2>km!PB(ZI`Nqnbb&9dZ)0v zDUrj9b!}7MY}u@$n>@d#xgwRnWh_l1BLBe%C$R5ITCLd=z!7;|s5G33golq@3K4kB zgHXX5=2Z&FL6c*yTXJFzWW*y&?v(KNFRGRy#11>+j)Z~77@CbJ44@oN9 z`W9{C@~N=|-ZkL}b)CB%;)vAUPca#u0N)sRSWlDb@4!d616EWr5SDtQfqiq@q|&Z7 z;i2MG6>6y97kq6Zonfzcx+6ysQ>S=_$+3iQXBvBx=b}e{1d6>M6|4E$avjG05QPF_ zG(R3aO@vuvI(MKh#m#u(EqkVPy_2y-l!%>W^qp~k!e~~>&)jbL^~(Lm1nrpqzP4}a zXKn{HD}w1ev%0pm_5OJ&(D-;>d+p}C+5f6Vu_AGTtht;!M#XHY{aRFUZwcQdlMsWQoER*8xi3!0CTfk5)P_1gm(#H{hOtyi z)tvqu{eCUX{JtMy{XVwgZb|)4gmN_4kjw;mz~gbt{k~sKJf7bC$dz0F$Zff6eC7N3 zW=s1Xco@AY;h&3}wkgB$vTU1iKQ#FJ#<(#iR716s}J)VHshH_RE_4^3*k=X-kI0t((;LX{akx{^DRDChWj&;0}77B7zs z@x4VZto`$n3lQR$GODp}pl@}=mcypd=`uY}wwKUsfq1?*w^k%-sz|IE8k(~xZdc?4 zi?g~H6guq6I%$6(^>Mk3qlcl&Hq|@9#A^`>t)bi{Z5MFK(Dw|0h zy)r>FaE(4WBiSD#U65AJj)ssKn*c#B{yf&Z>2H2&)NnAQ{>tV zAt4_m|6x|JI}Tjem_(*BD$hXzR!aFOTggBR2R6$6td-q_B1 zCK9J^`Yhbdlf6X)FE?u_vu~Xz&j0(*y{^WWNs9s$7oL)f`T(Tdoi#%tyB$TU6G!Pt4`l0d`O0U ze63o)?bT%`69)mZ7a}by$c8Lt07p#>y?TJA&_xPSnfPU`;zj@>BY_}gvp+t(19bRo zfpUZJyidEpXI;JFXQFsWsIFe(Iru}5VO#0E?p0BlG2^0ks>RI*NS7@#b7s60QQ`jI z@On5QP2-$epcWujW1cnqs^}gOd{ULOoNVObJ#1od2Cu#PJcdE{D{r@zugCfDk8c-P zg_RDF*2syn{Wo8xr^`T8YT^o+q}+S zEIE^0qklNV+H>uBt?b+5U!4GyE?-jAz;|(cLk8TucACJqO8yVh-XTh`aE+oX+qP}n zuIh4^ZQHhuF59+k+qP{h_1;UevQ`EeWd7gj9eih>vmw0Ijz>QNfNDBxb$vgd1haqD z6QSVFK24i#3EbGwUb>w1P`tKl_7gGelz06vBavGmFto(qE*NzhTOZ@W&b9}hy`lIh z;0ZoS@bP!A25=h7j__(TRkprUN3VExekw=>ef%VRucARgr}L}FLGjChrU`iHKgn|2 zzF*a&UoAY^h3j<0EW>9 zG6I9v*`px02yGqgP5puUS693`p6}XckIc=zU7Q~xwYz?yP|LE%8L{Y{_;BY2C!6o>ZY>1+=cO_F*Bn$5{bPCXW5e)G&xhr1crEDMMBc&XbuHo>82Aw@YyrjMGaw+JeiN5)o^9mFH zXk~hTw+vl^!_0FvH3WOOPtk&AImA@s0V-f9W{?M^-aQ=c+%+4w6u_wLUdGCKbzJ`i zRtQ5q1yPJ}IfcbU!USW$IBkLlyNjC*Dg=iMh=qH7tz;NrBLXjlI3^pp3O?e6w76^` zd*V#Tv^%YfR*8!Om_}}MnmvtwIw8f9l{*oOwq1$4-xB)SC&UM8g79aYXNAq5(Hr4>8!EaeJb zu?m`lk=Sqn^tjJ5rinj`@LVR=+@GL-Yt4Z|T(Ur<1V6)1+#4a(>D8hzA18(Oc^K|l z==^35c@_l74eGPHmATRU8EdaSGXRN{GA-XB)Dv_&`-Q z{Mzo)8RzfMpYVFKfug!k?hFHUF0dC>>??zEZ5R^5o9cPc(rRm{8a+#EIjJ~Vov$R9 z<@!6#-BCKniz^(F00pWJ_A@Bv4REGguRDb(aTiC!Wr{(o29sI9b_9=cvZBOG6a^aD zi&^z)fNScATf9|M*y;=qY%$Td8k*~QDH9CF-w1ZLqcFisU+)d)4O)h?pBrqnJ{lz? zV}kdvv(%`n>5!g9im<0orF2o$o}XSl8Iq1#iPOnS&g6gO3}y+Bfjo&OeFlk(0fLwy5bossowHHAzN-z!UWWe}qH zHY`M8jY%mR&YOQ7ZLh@_p?mKvBHYu-%>uRUuEW{VI)JWmsPw8+<@q0_^e5z&8w922 zk2*3CgKTde4Z1j{#78juW@nSG8Sve%DA@kv&s}j1)ltT|WO6JEaJ@)mwmi}@;UWvt z%<)qfIAB6%Al!ThiHf>S!R!ItwF#*q7wvvTaUy78i>_hC%oGG%8@`#_)$%(ILfsR9 z7!#w=iCy}|;)qZ}03k%(;%m+E06j}P?}ARLUU*X68$Znnny>PxKotWhKNM;zgCH`D z5G(D~7=^?T2?c+IrFd*QU+F_ENcot@woiK1bV@(SB6JsmN5D;$jX$dDd8z1C_*QSy zs~ti;^aGE`y~&pxZnza~YGF*q7OR--m6=%&ZEJlty>%b3sl}Dq?R9CB#nf(9 zaNAw}ZR(9BlcnCFaGOQp=$6G^49Y2+2U3|e1;f!DHM;SC{^+!R`_gOt^!&DNW`1tI zrk5+&x%G9tBF(&NXSP0mc-P$8?-uWVHr$rqf3}7j^3T-&&c-U%N0u*U*qtl!QBx1p z8=8fsV{?LiduO1s3(Lqc1=$(Xrqafcol#(975`oYfSI6PVAixT$zF@gl`K}ZlP5f* zsJ0P)H`p5@^=l9xX@goiOr4R~&q?!F=B1y0M~i3a16)Av3-P35X4CO?~(;w{6i+HJd-!*m603wWbrk zavEu?pQKq}A3) z5{kjiIbLJYMCtFseB;4uuwx=2w4H*gfh4)^^nS9jeYpb6l2r49$xpacvq|0l%vHkO^tabjhBhhi$5C zVpNISIiQRk)$kdVwVY|CUlV49F@)yL5PE)9?`Uf*d`% z8UpRiI)%O2rQGd9;u{l;IdU`9&orDDz+?9HK_oSA8;l1>rV{nHqclA?rJC6i6ok$JrbjYk^XiQCM3$&I^!bt&?(!vG3i1W0c`@?UhPT2n5mf18tn|Z&FivP@B=#x-4ZC)I2t@sJ zvay~MPS`4k3>vN26a(4WLV>UN_JRE~AbI#k*5!STrx(eSy}3Xq)^J?^MaHpdb$?j| z{zbQTY?N=NPiNbkl@)G87>ajqU-8ns4elFw7vHrlup|A_5qa>OeIC*c!q|-qfGv`& zZp64NeC&PUc;y$$i|xS@1}1Z}5^6V8lCjB3EOCHRe)~{MNG*^953mF;*+}=i-7r;1 zm^Rg%l27ugrXVZ15jA8(1^N~&G_KiEQUbWUU<;Af)2{w=7qv^3-x6`|3(TmZtQw6F zXQ%l+%T{ZPX?iUJ2;RxnZ}&5q5Z;;mKf0n2oio9Yy*TV9ejM#d#{G)pKCs6(vh84}wZGh_CjoWRUEbpiu1xjc*EYRHHTEK4Md3UddAmGpuNXv8`e!gw; zCD1?DgT&k)3|#sw5f^+^1Ry+9f@gws@v~L0GNl5>c$9*j=(bOhDlh6v6{8I?ii>Ls zYErBYKoaRHF|~duBSI3YY}ta2xZ!yW=1iNrhvwp1|ITW588W1phT3=;ny@rdTJH2a zen913u~{DA@Qp^9@Kgaifvbb^{a=W|jwjOS9 zUD48VIh+(683miE22-K3Lowai!zJ5*SU)~$yzQQ(Eovd)1Y&%Iba~Gas7F$hD*{h| zVTS#|KkDSv+si}u)%#5YSk>oGmD~P~Od_nsGdW9i!(W;;VCI9%c|i=}lrYBflZkW? z^K2?a5jgspUgAaI(K%Z}(zOZLaCLh(0~4zD(md8{(PV5Q-?}9X zIqrSBuA)GEqQxG#cT#St@SBD3$5*#*Je+#EL;%y~XQol!qcp>4qeoD4&5N0}bnaby z_p#9!CrlK7PBE-~v{1MOF*(=5m^=omr0X?EurQ**j~B`K`rVB;Px7 z@n>N8dDE5kV>e7PFBL)$g$fh}!J?jBjyg*4L9ITuqb!fZ90$$=1|6j|ZDmt`1AK)k zD<>@kDQ?hu$O0=*vGf zrJRqRScBJxWt9}{=w--?sKOMA3;cn^`e;)%?nX+bo*TpF;!VMqBo#_IP0oVU@6`+k zidA&SheI_&AQ<|J>oO2@O@yh+5avJ+$>!U6NJS-6{fk^}5&`TdZE>jw5vW`GmZ{VI{%G0!e%pIMiT{X&J_Mw0|8X?wj)QNF; zLR60tvOKyIaSbw~eH3)uy0HeUL6W8!C*kPb;w*={yf2qK6D`U1`txod(Atz7GXW`> zLIQFvLELRb5{DL`GFdFd1<_tK57@gwUe>jX2F8gMTO87ksNO$*VD1jI_LQFjX{hvJnFj-|+QIiJrw`F_`UqDp6-=bf@2WJRtA5N8+_osis z1tY?&Vg0mOoL%(;CloS4udg)SE(iX_wx|S->7Dd!S3?j%l*kBjBeq;(9TgztY&*VP zBn}l`PC2IeS(fOxI(P&<>l1%m;zNJOCJT{kLOel8DvY2t3GgVp*Z~5^y=aYEqDCP;UAazRdC-*)P?XOJ})O@l2dCm{Y}nX_A1W z5i-FI(y$R&3`H^72S;I?f=1s(;r*aR^P0dO>i7rvoJg#CxDEQX3t^fU`**Df%3-rL zevXVvpm#KY)oUxeyVN7S2zxXqbN~$YufS~~iYg|=PVcPMk7UUSgjNU8HFN)V2{ zm|O=9I{ofwbG!v+YtF&VbdZ)=-E|JliltxHaX1ViPBalMYA+MA<7P3da-GrMe>YhZ z<;f@8293RA2q2Iz-_2$VV&PAJbc{WFf1ar4fba4^5Nk$_X;sl*4gS5io{3XBX|P4F zqon@9;yh2#r!#zbb+N{rzr!>HE;dBbN7@J=6xABA!lbUztJ9GV6!X=0p^Q0}v;XI7 zgnop@Dscu;MRCAvM51LjLM>0((?}M%Y-ImM7Aa-(z+jDGkg^<`tGTWQCh2fjRPZwe zi&bPTnjaYU48_9MjZj5z=vj7flZKtO;P56!1g;q_=*pP^RsB%449TMb;0~FQH}ZAZ zJ&|ZM=^v;q@js`eldHpc`KUAr9c7>{WVtRXm0X{6++!Wk=^S$$> z^8J&)D$8mqyz5sLwZ%LD1ut~g)9rijyNx#t(Wt6QYi9cd{qX|!{rxQdJkp|>DrDkI znU*M}&ajcqZyC%Em<=G(l2;nLm)#5ScLeczsHj1d1O6qw?R>GTo^}vG#{e2}k$Q?S zrQ_2|Pf&6iSmB0%`R|ar;T_0x@`ktpXNRXA(VP(`c%D!n{Deq`1&V>B`XF}7eJqmh zD%HgfI;M7vfc4}HaClXgB=*V6{_HIRjV2S0@&;2?(Z#k#yO+3SSJ4FZ{bpX#pUj!2 zVLH-~b@uVII(vpCp?O`rQyKhr#HoK+J(9%fdNaw4GC%Kp*h}3CEBTNRw)d4?QTA{} z{CUGZrv5mUh5!5kk$$%KUW)5rb|{r(g-kl6C|_{oR`C8#A))2vm3#tqvv8q;qy9NZ zOVke0eTxXpSMzHXTUwVzL8qTp1n|1x$eJA6I`%8dBVzlQ5oIiSI+<0bo@xvGj2Y!G z!^hbp3?Bm=vR&^rHcSUtUs}acU+bMS5*&ebL;%tw01&Q-)u5sTY^)jSq6o^vrGsWj zHGWBjGfI!o_8pbLVI3O8VG7RS)4{@DA`xL;KNN!1<0SgqSy`+ojYuVU&vkU zWjNu4*D~LAAY(VOM#M2nb+jb7v?kN2nb;gwiM;~wxeg2}g6-Aj!`iFTJfn))p~gOQ zS|w#`Una_ren_SzDk7yH2nh(s0wcH20C57aA@jYvoW3(FIQaV8KR2~x$CX7Vk!QM5 zd|S*Myi*TpR-pkxEt^-%Jgd`Sd?L6G$AjIy?X+t+z9S_NVGq!VNb$)S;+bo+Fa`nV z3BCNJMbqpvI3!(xNa^(^MiJEn8=?U6_s=~AR=(6dWm@qlPZqL}uo&r|^YsQG3Sfau zRaD%61aZ!+2>5upSa2RINy>L$LvyH&_T8IrEqLbz3I!pxR7Y7Ty26abMkO>8o_1j3 znp91wd(#ejM_w_}Q~j@+bnqL@lc<~%(}|yMjP`}}TUwzQjL$5%4Ye)@Lt%{E<23Yg zoBay&n2$op*M)=m2~NzYo_{U>ks}vtW*0Y9=O%64?M~1P|Lf5WtoogFqgxSubNYXU zd0f9x+{W3HllX(mm`&2pSC-@6R;I$g`lM{igc*J+sC3eL#i>U8YLJMHq5Bk}tt zvs0{BBvS3lw*-IDsIrQK%VVPOK>$s9`0qxxXsQgc=+R;^Mg8SjJ+Hvz=+NB;qTj)s z5{DXVnd`Hq$<0GVnd@0qQ9S=9I`-97V~Z+YI` zJ>sWW^9~)uPSH(kpzK;z&|OAd()8-+9%EeX@Q_(X+Rt|&+4#DhxxRaKKSeXxGrnH` zoke5wal5xVcuPFt2cfqC2852gxhHrfoT+zT@^tRupC#9VU-@~)Vp&}|dpv-B@`wJs ze|wmJ3T+X=P;Zu7bHu*TZTMl&?()*V z`!U6)XY+x`-UI{ce)#&KQ1k2zdGV_4&FC}m>3p_*oq{s!Ub`fclaoE^TOgOq0q;R# z1gX)rt>FpK)g6G6V^rQV;F3+ z&Fk|&Vh7Pa=LqIggOpXu5nEfcN*Hz`q=Bi#k$@oh&IlZhkq{rjK3og7`#Qb>y~_lP zg5O@SuCDo2xQ8;rvQ6G6K0$icsrhzwbUnEEn!f$eez5r`!UJZC7;h3*bw}Qit(yig2u!`7F67UcX{FN+i7`r zefa=5h}{a@dG_Il_+It+@wvF_yPo!`ec@Z(_WZCwzlqwb(G93-`N91>x!zFCjVwHr z$o3ir>H&pg5@pH9#C5(J#PDPIxQEFu5CF*oCpTNp%C|NTVXch}sCJr*`JhNGG(F4I zz2`~{uu(aEWBWqaD*mLMugRZxW#t`Gwot*%t?)hphwZnhIK!BMz4x^N zPS;kt|A{`4%js-9`Z1Nu`C7gIJ^X5X@7(`jAN&+pF-eMD(oV0uIJj|Q_DG38pnfZ> zgvt5QTd?=cW@+DU`P9OC;ooh;Zx0T}><$>j?5z4mW^8poc3*&>bGKgy`;Jp*|$ zp`bgk)LL+y7#I(o`2F=@rv|fBJ5?J@(=TN1i@0!{TYrQk+F?1!FiXHw29jTzC}aFY zDyyN=gjz5>`tu1?viow6HVAqt&xoiTj-$&TPW*-aOJ0uIv0M?AHesXAC;>s=FJuTWf#X{c`35Rr&(iGw;MfVuKsATL(DK+3$v4 z#tY5$S{b-27MH={5TAH-T2v8I$)8u{)BDKNaP1}<$oS6;5D>HrNz*gs-re2m^=vjn zdo*#V)O7?=Hx%@6aUgyK+ehG;u3%`f9W|^}-91al@tp{Fgd%lGOQb{B7b?HQL%cl} zA9&pg6>93kvm+`Jfj7ps<9p9c*^)rrx|SiyvL>W%ugmPPYtSK7U4iIjvau4Qe)?UE zumVvo%!Yn2!)bAT$eRNLMniET>nNgAvOP(R(X%HBsD94}%*;yYvkodH^6LtLT#hjL z$-r;rm2E_>Av7yn3sZ-dl4hjusn7h|+RxpB(18J_T70h7Ox#CC`Xaya;s7Ks0vsla z;Gjc2;aW4mjr}dWWLRYav#0g~N&Riz0Eh(X^Ut5N>N*_L^9Y3Gqpq<2?0l;<(*~X* zY8UtOIe~sEQ)xaj?hVda0?DfLPQ$*v1(I90FZH{tpmD)7sB0Z#*}@U7i-BRKkbIn`e(M2Qo1_ zlE;nSiCq+1WG$FvVLLo7lIHEJkXDk%?HwqTM{$jIg?7l1tA29)JP9<&lXp6(=>6Di z!OM-)&A0;QU7Don*VPZqQK@_A=v=qJ+y@RCKW#kY9O0=Eyv6}Idxh7vZ;grwpq_nz z3xZkhXWLV4KP(sqd)mjot-$w8)*3S-_%0a@SI==`wx(K-2LL~rJE}|L{zSO3p5WG( zbUun3lUZGP33e4^3HVpdYyvKm+)T}B_N?ofn{V8=&G7DR+@EO$rCr6n-^%>Wv&#-%oH}vZ(OB3#R)VkT|06931xX<}&X$F%1e{ES zZk_FMP0ydgUd8tqaG*mKo4YgMipZ}n;D!)c16H3yP-n!nY}NJg?SPh=`<8vQxS3kM z-l)Mv_It(LSo>@EnWEM<5UMz7@Pw!D3wwhk5zj+m&rl397*{$I5+ZOU*|(;1qq8Tj6X;I`z=+=&dkFR z=Z9?B5^Z}wy}=nQLW8h?OpPjc$SnJa3?d}x4?x-R!nEK-F*zZ@d~12GzOK)5G%>K| z6+G*Jh+6mUEB{c>Di6OC%P0x>N3v|Vn0AI*GO1wW4inO#TqPY|8A6Lh@TwyzYD6BW zHU<{?pnBBtku*H$BhnFnq}92d+3)qf?CGD!Wf+11qfMAoS3$2Rh+h%$p;GKQ#;7)W z!eNm>wU(4OR<>$i2DSwPm8@IN?%Z~Yn!r*)k#XBDZo2Z;TeA9t|I%X|Rj|M=JiB7b zPv0}&9wexG%{Dd;Jy~L8(~ssLa)Y0dprBfwsS=TTKAOS`q&klOsroT9I(W11Yy*b& ze01KykJ%=Rl{v7WV1!oV38?`+bu|ztOH!3I$-Bi$mEGk+*$W zQT`u;*Npc{HI8?0fgjt(2n&lp^n^0|Cd;uiXg$Scn}hlNYBTlbPX83KfD<#T=-hC{LF4g-4VB`Ab{yeI@W?m`3Vs+IHEG<=8%dpWZMm`unV}2uvS|-stsn4L?Ow zZ@bmP`i;7_@-tCG;d{vMSE=Hm2mj48%fT z$tcomunM<0BgRGW^!?`6jqh2E&<0*6aFlw=QXHWNbxSqh=%?Ecs zww~w7SKl>#$A%_2w=l+O3Cm3JKZV~-p^`(E5#UMg2b_fq4Eyu%x-Qo0=XN>u7nN(0 z?~-OJmHb4|8F~V1aTJ~O^rfglJ-v_HEeB6dAe{K?ziT#hAd29GB)7vq!c4-mCZf;o)^}Bs7=Z9?cG+x-GqrVF70IMefre6B^exc z>HvPF?*Y~#5zq7>Rk$O@UU z!&!s@1Bb%6z@X0vl&q61rxAwIQMq(S(=oAQtb5I-YEeMXC@+_I20g-^8F-2_!mh2y zpGSV?Hr_+ZpdHU}TYqL?P4)GZW%ML);Xis+^+>FstRRG$$!F=$#(>l)-`l6Y0wS-3 z4;_Bxe9Be-mGfO>&y#t^hV2zE-pAyk#Q>6}*^LAu{N)PIuxyE^w=Zb%3{VCw0Xd`5 z4ZmuvuSEh^hQK>&3yNyN0l|zx0n^~w@F0N1pe)n82b=FCqq}&xS%Rs8=&A-??~V9X z)*;k4Ri&L;zh^6`a2Xu+&J)XcMGR)M)O%{MEAZJ@+-hO7a_7a?Tg}58LGeD2R2$nK zn=1{8zc)sFMqjOX_Vh&1+(7*dTEsXG<)777<1&z2n*#4s=HP_tJ+;q>vH(g6s zU#eWIQp!&jklfDB2 zWx9O@h#$s)=NmS}S!~D!#Ug8)`Ln|01n^%u-z|{W_(VhzY}NxqX!?;=t8>LO5Z^M; z>1eG3-EyEq3=1w z;5Z3|EZHvBr(O90)8WrGLcfC+XoK{{;nMFj?5%b(qP0k^NB@gy$JhpzTB?_nUJtmDb;f3AEg`<_)g$kiA?gi>{ebiD%p4K7nbW&P4 z8ZEBLHCVt>y$KgSC0T^!6_vs?)$h9PvevLiQXB1Lg^!W5kj~fFC5jBZ#9)0KFDXOq zYlLxMRC1EF@A@yL3qYN!I!4R-4qF0Pwpk%>%cO)zCkM6+-LOc*9yHUcX@^STHD@c1 zqRfS>S@=GKf^1NoeCQmy+$sG8>5gS;LL%$stEV_@{<6P^KIp5yLt{{_1k@3F^a0`( zb;sI6aJPy$(~{v8{U%_OL%njiCMwi;t-PB~Wlu%&2jS3=;q&Vc)!g(nTLb%D|k z;3b|P#;xK>b`2yAvm88`k4z^e?%}(MDqhtiWv)i<{0IajX_Rm zNy*5!drfCPp=4R+;@Yg+p z|D8!SQkSq{`-dHPuB>lO5O;3wHx#zweb)|a9%%4(K8d|FD>o_I#6x02Ps>hplyL7> z&TXp+BQ;1V8Ax{kZ>(f*J&9HcvgyZOUoe4U-~BJNP?-%@vrxNAlnDG)_e zL2xW7eyK+#cBRQAh9ff9qsZZ_(6LQT%<0Q(9=h>gDc^CTEP1xMl&=O~O}VDDH$Hc6 zkh#R_Xc+@~O{@vmInzT+$L_quuavJGSHbfhNwxC^pmF15Y|H@Z1PbJj?EuY;_NQr; zUl%7*-*u6aKFr{KF{&z7V=knM;HRWkzniTth;+ZyjPQz_FrmQ;x9+QzGn~L9jtbv# zK40;O{ZfzXrn*tUzLB~XF!G^uECzGE_5U-}230lQoCO`7!)JTe+|z;Ksfh-TJ^z+z zXwP#?zD?7UNj`K_zBVEkjd!q-Xfs`PXM14~g|B{Ph~Shp#`Bf_mGZfz7iX!Atg22L?)$}^-5y*$-O>ssN7!FgljrmHEtx4B( z(&4!g!`H5}<&chUx@YQYwP-d+Br1F?lV341K5)pAdxhT>LwD2Fn$7SSje|ISiRFcHPz7ilGZRybuIFMWm4(N@~=yWBEgR$!BgM^@l20-|3qE& zv9#OWYkPXAlmVH$v@Da-Ck=R`(3qIn3=(A#L_M_;1B=SZ0LxUeoL82=Kkz-kw73+f z{XMDg&wPQ#Yb-~`x%j1`l#^?U2H||Wh$-YZ^2tahk~K`>U)(eeHHbf`z?F@Maq9ps zPUeghdTC_Pzq}KC9Bq`-OY&Jt#eKbkI87EP5t#AdPUiimyn66)^Z|7Vg#&Yk7Ku~X z`4!#sjk>iv|9$Yt6^nZOlU3w6##ATh(2+(5WqKzH##B!cry46(@&)7KUKTs~D;%9< zub(z?H@YZf*kf>^amL~1?O(q+0pQFGTf{_krAwa5WDB1q@!cDkBjZmyxQUs0W7Fp@ zvZRjoQ4#Hv8L$dEpLhkP=l~Er1R=s6%XI{^#a(RjFgG&(PMu~T9=-k6b;3!cZ2D>S zut9%9CrOEcR?+|vTB6R_0#8{Xx$mxXs6@wuz(Hg?e)e&7dGUDU(l?95EvK{Kr+qtzX>L7L%bxH^+eNe!qm?X>;AYzk0p=er&NTddGd z?1?5Pmvl=|l}#m?$B^u>fM;@L7$TEy2iw80G9p^uJPrKS-gPd@g$5Q42agWNl2~%$8m8lgpAQ zu|;X)#MDsbd*;B2yY#pQDq@**ms6JmO{8o^M_Ds;V^Z@uG4)T1|MJ5TSmP{CYWjsT z&M-!M!_F{PHSTOzb}v{P=c|b6BH!AZH04fAk%4P#_#!K{loX4H3ZXZ5L}4ORL>w|a zNdm+HC(@~}=15^+2BgQw2U?4OJ*xFrW@CoxBP!Z$_V5<>vm#<-_zqLn;}2lCUVX{h zowRJuaj!C74f_rGAlgm6>rKc zj1v3Xd}6Z02I`JZZ3i>rER(|G!fgew8B?)}RZNN?L@Z}v0o&7RrPj^d(;!hD(7ME+ zhtS+T+PQ_eiuQ&ZD***Hd1c-02mF~hMAHA1$5@fihKBQ*w+lTXs>=jaBjh-t3hXvn>hj3wt0)9e4#%AF zhnl`C4lx!yOYCOpx*d&PhYY1Qox?*%44{Jq-^@_;8iPLWN!h5`ey&7qTq z^68@%KTzPjbBkZ0;u`1+M$cMux20{{lG*zOIi}f3u5ew3AV+RW+|EEc#S)veBAsU$ zrW3uq56*s*l;1?ATz4kj*!|T#aSu&uc3WEVOHG+Avc;@wIp9a5upqYYlm$=$!d82_ zu8~A<%tFLPFy?kdz%};FLpv~NHGKvd%@hQSc9g=9my|1EMV$wE<5!ajv(A&9n=-?K zDULD}GR`7!;nSPtY_@t|2v7io6eN2iP{!C^ecxf-26$A8$feyjue|ZE1F2F)b6Euu zE##s9TeO0#4j2~E0(!4mo7Jk>l1Vf!+>6&KIil%!j7pYgbYY)3CY)ptn$V?a0aL>Q z+R(WaH8u_Af1Jk~VKfJ%`cXQCgZ9~T8^;t6S0wHLoiXf8hqimvg$$lO7Rd>0N>tPV zpm}(7PJ=3R0uE(+LA;~nUb^)e3Qe@-oC)H52Czjg{W?CUB5Ur~SBJF^k)tm(hXs_v zKV(BSPGS*W)EO1&x6-~o)foShfY1H~1wf=-c;Xm{KQC=y!>2qWoyrGcs`VdwJp>{Y z1wqSfuK5QPNAPI7LA7)y6FL-XL+Y5T>xX~HwmZowpXRpyl!mGMu;E<^e zrgZkk9xAB(58xr=^$U1duKofZM&~sY-1#chGEp;So@7U6=DT`P2I|d&#fzMf!6jy}anBFlDV&G8`IIf;l@0&5z7ASf;YM%Shp@>8wM ztMrRlE46C$MNR2<(yfQ|y?q{_3>^aDK3WzB1K{%^Vb5^C_lB<+-|u-i5~bJX9E~fY zfV2!!_5Z9*vH*wa$qKhei`iLRCXxd<^~S-9a(yhs4bLYZG`YN1vL3O)v4wx=ALX{W z(B~DbDw*|Uy1 z#H)1^I<(huD>f$*VLLB0aWnF&1h9yxlPzS03H6*Zr!XM{sSmm#OLiif=(=a9CC5>0|(<|V4$so zgLaNF(5VDSqJY&YP!oRQsN#S*72hbKj+2+@OihXU0H+6+I0$2=>(VP0;H~`M$m{C# zD^e8o`fKsJZ2~n50ryr8cgai}+%*r6920~xuund_)lGSg-Q+t7Ti|y~E1W`>Anmqd zxll#5{=gB`%vV@rqEK1B0Dw5?R{!m`l zv+v}!1zVpj4?FBw(db+it0fP@y0Li!p*>He?E6(G^)?E@_fW(rgcHSq z6-XT0yu^w67PZ_9e|Y_kmG@c>+HV*}$@ygpS^}$}NzJ>YB{k5c=G&`DsvM8GJN`Eu zigA;&TgsP4>v*C4?n5yT|YB!4C*RgBUuAbaViEM$ubZW&~TYCB}+W z->^nf#Ko_;aUviDaJPda;v$kjmJQkfy_Y<=1HI1)i-FJbVe|hH|I0GO(zDC|eUsO5 z!5AnYyW>P%;T&@h=f>!Bmkkx?r>H;R#L|GDdQ zB6II9<{nljf}D?N%|*dWHVhCX8GtT^*VkE04$Y#HnY#xVyQ3EZsuUSu12H>)`#%I= z2b1GJ2!NAeE5qNhbE?nHalS-Fb=G0bg~T7QXMm>Y}>{v&JundOhlu}|23@%H~^Er3{Sit!XYoJ2Bbu6TJ1JKm4qEM+ukX~s#2#T#4Wdhj#P{BGr{GBD2lMURHFYCoP9c2L{ z9A_F}5)^kvf3#inE7ig5AuL#7J4>3{JGy$6UdESFg3QR(A+#=aqR`JFUlw(gI*gj< z{M(hG;L59^j6vx>H$FZf+Lub8+KJ~9}p*s-W zmZ4eTN23Q)8V*Euix3*R;k6XI&ka=79Ncits}yT%T~}eyY0}JOO4XdZFnM$EgT#!|zw#KUDcswmdKqu&QB+nR=RY68D1B$fu%Pyw$8Bs!` zL`E)@BxAqEDOBr}_jqjb6ftasFnx($uKW8VCE9na=i8apD1{qGuF}K+rH_1k8tJKO z>`ALF+34I>tu@+Kr`@^TY-qz)s51%7k7?OMjznA7)<!lBn{%~ zB`X;(K3%V7E|0lc6Ls+BJ-g--a%JGDrwa`4g)7UaGmo$Q#y5v&&F#D3Q+mhtcWLi_ zKXmsAHhRRZ`{82;yYnYyn`Y=;d#2udJbOdUcXN@y+fAYU=dR)C=MLr@Qs;m8lrR13 z&qNB{kMG)lARU{~pTrbaNIi43{|xNSUlHeQ?Ef774(vUkW6$7z{~R8a*Wk<*11)x3n1{xbANJmM} zGL;j6XxAr+7VEy4iOnoRLrX|Cz&ipn;#Ly@si_zrXN*o;fiWrf$U062IJ?Sd?D#h5 zzRY=yryooOA*k)6uhd&{W`t+A`d}3TKJniTBs8ZNGGtq*N}JLQb%FEr z+HAkge{aS-q$L>uPp=wk9-I%=;!J+`P@5Jsw~m0fr>QSPD7x?U0sIY6i~@*7lE07_ zH1i{z55@h9xSEtY<7bB`V+1h{;+IN2a~s>n|J|HAS(g+HF|-zq_LPsWG3H8sKJ8tN z^V-Y&;CS&tNufW*5E<_Y@rI*DriOwr$(CZJQI@nHUq> zwv&l%+n#7*+n6{{|L5NK-uL@fJ^SQ2=(?)wI_R!G=&I|t*7|-nT?x@d2`Ar$sVA!v zpd>_ku(2`_AYo$au?;dWbSPvyGqfb#G0=PZJ7g7O*KK)JrrU1 zX0V5pMQr0BB_Xp$qfVu~?B@bv1tleBnH0|aEMsHsVC>|MO7rK<-Z>}OL*HXKGXte2 z@#){SWrhOh_E28ui-OuM!qwzu>>>l97jrY>v~L30<-PB{FpMgW z#<%yg0x3Me(Do*iqI6S!WPQ|k*E|l~AAx;YS)e2JPaO?i_<)E>`BXN%Yk1YrIozS- zjP{Xm7?a+C4M=WG@vt~p=8zz4pQhRU2zY9LASYQ2_z>@P=7)U3JUY*&B9UkV<$4;Z z-bVC`dTRZ%b$RiJpBG@D-3Ik@qaYF2f3&nZy!1o4G4`@CpnT6GU5`63*$3qtoDf4R$FO&ggfE`;PE>gmeu>QokIt6baOtePUkEAy8k@iWV#wg$XvMjg`#%aM93u1?Wf8ck#KWaL6(owv(!4xwo2#_b) z9*GuJ5e!>!OUK=DwI*hJry$soOP~HIdEaL%h*IJ61c^5Jf&4K_2+2p*N0~Q%L(0%J zHW37|qP~nP2X{8hC#w?P!2-99bW11)Gvnw%g8);MxIU2goi5(3Xom|zJ04O>p1Ije zFFj+$4rNi|#=0LNS?rcaCE5|LDZ!}dG;0h86s7GJB1twZlTHJjx?nrX@o~nhC|VJ5 zf~#$_XM71pU`!p)JBV4=DFz>~yJ8ew_C~{yAU3Cmj~aO1zph2%OgpZmutIQFdaGEp zTay0eObV(clgg(4pF*RPo+`4~5iNLDn#cVr0k%x@3kDC_Tm#2OF@X!>J_8D`OMrB}@{&%7A?p%`WBc3tz4h6`(FPW>O zi-{guOD#kW?JQqws!q>_YWg`=+0l_VjR>6+U3M$ZvTz^J+U}F#z46nvFTy|Z_fTEA z8`@@IZBfipTf$2y1Ymho!aN8~{q+ek!ug7A=RAaO-BRT8xxIp#~17)}&JK`Zoy5WFIU4G}0QIeXMlR&bWfM{p>$Q8zW zUbO2!1xU#=Tv1_Lr{qbV2sAJ8>ptW3L5PfZtpA@>qx#S!uUL|)7mFbHt&LsL@j#P~ z@j%dn>Ox(8ig(|RcQRRS5HYSm>E=jQA<$$A~rL@Sm*ooqV|dn)@mx+)fYD zKl7(?wsAM9&9fbSXS3U~8h_iVD$i)#-gwo$oCizWzb(+&JtF|ApuXbPW|Nfw^()8TSd zcjP*Df_?BurzIcF&lQ}_Cv!-6w9g8x7_GIxGy^-;8Dks~6 zy7L{R^NuH`oDX?R`34Qm6pENqY|;hU{KPq)L70zR5L-HqGC9$pZ144#UCqLx*ugyWv z@7+`PoM^ed1-b-wIg7EQ#EJW?C|ojk0Ty4ucNTV{A)JIcq7bv=fD}6iBf_5|&zw-sc7pIE;oq(c$%yHGz$o8A?)@4s%OT@=V zcf#qG4~9jhr8aJGS+A{{R|I-A9=gCpvb_Nziy*_*$12Zv>8 zH#fLi|M^PxMS!nlUleYseL6zi+nHz&H`EJP77?~OBDm*dJtR8v+j;=bC3|8f75L^=# zs}70LZLaql$*oNOgC*d&+11gm$uUg?%q+q-?Gv|Hf-`$LCi2RrYs0cxqE+CV{EeN! zx9a(7L@i#9EJQ6E*K<$}+{PCV^{jQAE6o^-lYNtHkTqXHk7(jZU-YaR4+*b}?qgcU zH*x}qQ_xQMWH`dFh7A47l5Z=5QtXTxU&%vM4$M0D*$GQ3xAdA!gTxwTZkH#32Z&tj zpOx(8oEn7IcE8>dzOKu&zOJnRFMt#^{zZvb@q5Gn&t?1DyT4*?kH^*c*K61GmpiUv z)>kdyYVrt>a!nH**Fk5UTG9q5$FYi-e58T2dwPSSGR6=!v-IpT_^i*=iO*Bm>W6u^ zSVpb!?W6wOJfhTI6_UeK^9^=1w$0C&OFc0w{f1ruAvN;!3Z+eWCrzw{b5(Qmrcum= zaTI3ryVwfKOc0`@J&9V zgjl70LURRUobxoz*Co0n=!7Bt=M4&}UWeRRrMBy1YLPp)qyVWIvCHjL{)IvsV6fkOxmDSxO5l`+`Ab2R4d?tR34j zXHKr1sp$=;yu;{bpRZ8#TUy_{2h$vWw8k){s26WYY|5kS68vI%Fi_+LqRPquPK%(` zUpp7_6PX9rg~sgG3GKyJ6N{$aaDX^8Tby?Z_0@*1KHwR)Z&F$WkPp^VqA<=&>1BDl3O4}HDfKcJ^6_2;n$AJwplaet@#e3xK3*5 zWWHX4PqUMt+#NkS3)kLs-IJ`*CWMoCa@4MXoR8+1Jl=kyJl!~PO>mm`48cS&Z!F9D z`j?978Av-xL4~lOo(g@6j{cO(uAEBEy(%k956SWsH*s3zW@!F5$bNl;Z}&esNYrgu zJ=#q5YxMN8`rOp{Hbq4YUb4(D5f3eTm0kRMxQx>yVcbR=PYvGcw#`z=p2|YUr>zxf z97bhWE7{5`X)>VQs5Tarn{b8ZDc{hhR0v_gOax%Q4-H~yiOBdB^wNiuzM8mf(~Y;#EogP~4E zVgX;3j*`SjbSZd#2gKL;Jlb@JV!>iLYlRu4vi4VT%LR0Ff)lHId-E%Wggi?10|

8^_DY#-Pfdt%V{&jqC==4&;8$wg?MK9Tm-ih|{v5|9QL68rdYeS%9U&WP;ij zg|Hn?;K=Cg{eKyYy0Kg#)aKx|e*7ulpa z7HLVpQ)*VY2MtcB^VC|b+wqrB%7&_|r_ywH$UItG|R#tN1l7M+gok=?~ zs+f9U3T2J`_&V?DTlUEBoDUsEMSCqvPyp8tB9r36o`%$N7-OXqI{{i*`6xeL2dY^I zTIVK>)H4}Df>dd=c^&NuJsGv~QbDk_ke|VoRj#q>8_ib-xJe7iY;`;UHwjGxN8Sn} zy~wcmj7Ih=8ld zG4z>3wlV$q-M;bA9F47D%%jX0AM4IDvDSfa)8pj;upITp6HQ{{vG7Dq5R7}vLeeLa z#uF{d^T!oRKWj~k6Ndyhj=?RsMKS(-QQc)i-+qH3yG8)rb9@O9f0BE0#*b`rfFd3U zsyavLKf6%AA-u`0W1kP`n~hW1-E}ruBxWO67qFiD-9p8iHW{{87(S__<4H38w$6k6 zUAc`>oForRtnw(@-(ALjWo$e=qCe4uT+V1^vQb+>LzOm}!ju_shHKACXdaa2Y2-{~ zBQ*mKR;wi4DqQ3cM9dw_;bukn=6xJ>R$F+mAxt=xjYKWZ(|{1Nd$W0 zoAR=KF24BI$^d{Cq~A-{`bBd!Z-U$LbM|p>i6UGn5F~IYZ*g=h9nViH17p%09$CxmSh;@V%cp$2;x$#LQni&*MnjgcEoeL>2pr&u8}mh$nyU zU;gqR4%7y`d3)aQ{a881#l@Yye65`|5O6r}-5Ob3_O}CE#XdAU^~%a{e(FOtwSZZE zFHx-;UoG~kpo^gST$UM4<>xeXUapGw7U4d?p8GIv&<8dX&+2{K=TstHqIat}MN`Q; zd23L8OC0!u@lcW8_03mfcux9r-D1Y@d``pHgb*Vd&{`AL?_hRIGCr(EhcQhEZ*nVQ6^AGTbnug%eZZE4o(ce5Zt(KR{aYEUS zwm7OwFiJ>r3k`PhM9=;MoB|Y>0a!wz6US^Gt@ji=et70~FstVTUEECr6>2-Nb*u4) zuP`0tBABn&86Iw4m`@N3njhfo48!>q)LaCd1Zu*%Ws^lNCO`z4kqYY1M_&D>F~l84$<*p7LZ z=z%6?cTZ%qHK%yl*w}CM265|WUKh@m@I!Tu9AsGUKn@;!^>9sCF= zi#hCBM_Uq$BNyyUP<#Eq4?Cw}WBv|16#&CdHO(jD)Tlp^X3K-JbSYq;KbEJQ{fc9jFPEUDZMPomkXqO04sc5B%IQJhRE%ErR2=>*p};z zBqo^?f@!i%y{liwc7ca~dU3w%h&JDY0%OLMi_&=5#*wT&wvWfdQXjomv|_7h_7&YH zUV%BeOse?5Mx4O5c7v#ER?T40^ng_jcwAkEK8Wo%(l`r}EtOTN;iY}7x*6GW?{Myy z>_9h*hza@1`j40z&t@)HdRKAur28sJe+GB=a{d*Um{Z8rX9-nr2AB47{F&6oRl;doeva|oyqEUeRUo0A&&2P$ekp>KEMlzk6M|3Zc78M<3 zx#ZuL$<5oLeT}7|rGDie4q)T$?Ji$K_KLr)dtbXf;a1W}KkQTBS33>Zb(gw;GyC_WbhXHk21*l-;tz8iS^L$iL>(L^F-~*Zv-oN% z<3uZZ6rpzQqG;9SeCtbLvs0a=UGmo61!>FdtL&Q5fg^A8)|q%Xfh0XvKe(GVZs=jxkDE0zZoz9 zEhZT z{t8{CCQb0m>V<+71$f@J*^>xCAEjvoai30wlU-w+V@%|aZFOJGmC1J_(OpDbXMe5f zX4f3lXvrDOavHGMM4z2C>Vo$*$bjKe37B~hs6)89o)&aEaFO*#gw!i(D1UZZs!C29 zC(vbYdPXQW0m`Cby)=$+cjqy_WT3w2S*C9RQxcO*@jPVVWrxI^)1qu728l8Mj7^iM zCagx}XgId+EnH?U{jSO`3x{RoVf#1HLeiP=Sw`ixBDOA2m z%oca>^v)Jfm_ad)6m^(nMYk~t?LAn-o+N06Q)PB^Q*>5WV@+-73dJxn>fYuyDHjd& z(1|!KeTkG9lD$LkKD@j|7w4Xop+lJ7Oc?@vWDglp#SsHJJ1X5#;7tG}&|{-!#*4L>v;PrP7JScFUnB~@u`izHGcSe7@`2+OyS+v0R>uL)XaJD>h_K$>K3 zfY-*g12v#l6G`Zt;NINX^7MkC$fS<*1q|gR7o_P+dn1SEaRT}y099R-I6{@Z(!bR6 zL4>yf8*yi}U;%20#cwE1u)AxLa+Hfq?>sb%1jRxSg~&#+nar~;E!3{t4eq^a?_3_p zv?lo&)#I!Uh?cB?%O(Uw{s#TO8c6=|KN<*(K0pKU0-t4#R|PVeA>tWw;h|IKXAcE0 zJhkBY#`FYWL@Oy6_LH)JAvSEvBiUKRn@|PjrgFycj75T!vXm<0bbZ8s4vP z%BbK4AlEqFUPa*F3mqE4eL}P z_;I_L%Z>v{e7aLVxe751hJsS!cnyCA`iGp}DTpiOfq#gGb+2(3?`Q-Te%tz%eYhFS zJJIST;i;Vblx(4F=Baf38{4#hYMBV(3MPRXn-$~~N{eQ<*o*v^O_;>|Th7<3@1KvE z%9FIsoR!)qQew?_lk>-G-Z!s6Fot$8!)PPd_@%2@-hK+(ik@eU$-Eu0ka6gwMY5j? zRbbfGSzUc7;t>%*El|*Nh76CBqtiR6^`UXT&p$d?nMyjiL&V}Y2~^G`otlf>OA&iI zS}L?nW>A!ywmGC3U-KQQ_j(0lX?RztC@)jnp2;?E56h8F_8 zN7M3u%<4~sDY-jeffDy)MF z*3O^tz-p}i)Gt5W_cX?HU$dSC?gq17`nPVdH#^Ju_OFW-Ck}h;o7VmxhXY%h7*!x9 z1bm1iWrL|l@_IgEMQ>@f)${uND@LxPvXvzsY`3kU&Md-S&!z61s~5uc_sb7k1RiMu zH)xmJS*WuNLWbN?9JZ$hLtjmg+t(NEInQ|<563+M?u1{BxBHVZgqzQKgzL|F>mI)W zcRr6H_Wk#Y5;zTx_(G4+XcvoNy2{?Y?S>-JDTb^PtZ$Wot#6kiTM@bdf1%w2zRk3Q zNooW77ij(wzci;ovMLNf);N2G#<)wU>Fx6=d_%wG!f<6*!m{~Cr5tJU1(5wb)AT-Y zhljz{IzX4$Q$>69c|1{fMY~9G{D<)%vOb5x5{+iYVId1=Z!Ib?eUD9z&^oduq7Q!` zC2%nvGP;>h76rz7;#9jwjSme!8wgXd6@9)PQuT z3~D{Z{4Hj1;L-6aB_r%w$Rh`?Z>|-cu=?RVY#Qt~(<6R8?)O7+IX|EHKu} zX)*$AJ@cO4v|3$X_ECkqVo-}*de7o; zJ-(Z)&gOjwf}-Mq)wM^-YMw0y{`7KhA&i-%c=0D#Dsp`SH7z=VlGCh5dI43xWQQ?7 z!5(Bv-KLF?MKff%!wTt^lQ*p}AyS#0B4^p~H4b0f3%E}np7{C>Og%N7&gi~BMEhKW$?=RC~pc3Dp3|6n6pTM)s^2gA8 zL+4(Xup^c5okesdbNh9!`C>2)yJPu%IjrU`&%pek;;|b3-9|oDgN`v`yQn`EJz2uV zHX%l-1Fv!&K2DenPCVmHJ_+=y;A(&st1|lXeQad`D&SW`SSA==V(E!!w|TL9ois*2 zP8d3=DIYQF!&#AB|47uAu_eYHE2^!peZV36WKAssmOg5mx|JD*gL}py{}AL$;;FgY z&*NzWKW9$W)1Rif<`Z`n<2oUbH7+A727V=`4H~y$6>Go2^=e!?I90Ls1Q>7FEh=k& zH!5&k{)WFW59ysL*Cd~*3Dn4tc#HL&zY6)neDzuVG{mj`S^-c#`(KZK7UxS@IZTW_ z;%EXV$5$V{j;+0}@4W^spN6e>RhC`@Xa{e}Q#v$3INACsvlA0@?&!{F_~FW0#$z>HOoFs2g35!J4Qf>;YVx6K`yOu07fT{r zB3hl^8jwy!1SDSc(`t&Iuh6v(o|-8=M^#0n83!7VqSjhGIf-t=ce5-?4sHm3>)z~a zkcGz!wHdW#{+Sj*pW-VfL=lPuDsts;)G#h7dYM|}Xs-B85OjT9pvNXXHWdzpxBo?P zj4uAAI3NHNM=Ek7X7kL~pNIdVH~?n`JnM}B6o?4mVyL9xV@~HF zAOSbojq-XhH3p! zuHpbeBFd0FIgmSb&d8~kghy+baQe!zeNPYpYZGe+__&ePk!XN)*=o=ufKeovs6Nlk z66z}=TLY7o{jJ))lLjYvax1IHeidSn)qsbM2A`0ZZ@ST{g(}#EmH^d5X0SgoxQm^( zmlUbx{%NVRd$SeNwb%$7$JGq4F_JgoL&df3{%G^OItX9g3et$D4&rK6^o_jeFe_-~ zZ8{UzfyE~!ZUOS=`*+me*ADIhE*C36$PV=-yRHOAZb+_KODJlt`b4kmQ}m7)$04Sb z@C9vlSaf^X(?VmKkIHoOTh@K~Kaf09sqd%KHiaL!G-R0x}iqCEj&B`1^MHaor| z0~lj%S(9iYj8RpBvW5+*oYdS~0}!w8-X<3VqHg6z=P`Vw1_swUZ5t!AF@IMsZl z`Y6_(x=yh67PA9Uj?RBtOgZo3j3XMgkk-?|o=2y$w1>jA36u{`0(r!V@T@bQQYTz2 zl$GS0R1Yg0xbgtck|D)vAqn+k7^yQ+1FE)hMn*GV|BiQ=*Rd0n@f}ErL83S00@gDY z&W_TFuuvF)#Y8+62`ZL{WP-sl0!jObj#dlb^jp)`4Dw{(2H5W3mbml?|oScj3tws(#r4d~SxpNt+MpFqs9;8;w zOC;;50H)TaOknZc{Jt^*&VU?D-D`-C5~AsH1TN(sRs z(?{kmHp&Yt8>~9Nytz-P_6XJruA;VYjDc^nlE>d#c-s`sh$n7QnwaJRACwdu@|F*Y z8aMcZJ||@V09AJ7#>Zse^YGSW4L8TpAPNF*1f*=~sW9EbBEWLSZiw9Aj@U(P^aVlQ zSfrHo!H)AvCxc>YFCT$IBgbxVz>*pKU=WgAdua*4Jn@kc;J2=WQ z#R{#-P$oTYwj5D(GBUGC^=#d-XRTGt<@vZ9t7ewyz&B3xA(D?}hjFe!riWe^DQO3u z4)Cshd9y_&pYAm_u4ZjZEEAITcD3;n9Jvz;^)TBk!lTl=K}&^ng1yHDd(s8^an-^O z6H2c<`=>+u9chc;qlv)2kar}=#eLmyCKalb45YeSwkK zl*z;p*bqc_!FJ@})+ko;&i!2kHnHqJJ0Ti%L|NXE0KcWchqq5T?b!irL zY6(-S$9RhfaA7C`qH65;mOl?D@|+w>UE+(u=@_)iHe|>lCzg!$$R0-O3NkixM#Zt; z1-64!vL57AtI(p+~XIJq23!c`nK?(Ne!sgu|VrxWgqH=MG5Jt z936g%YR?e6|9IVjqUA@_7laoViPjO{sO0R_(Jau_!@|UV{l)dQ~+ z50(ig&wat|A5JUaxua)OO+pLjb}|j;($a3=pu@$EaA*_8RZmrlJ0^)oPT302C`D$V zJtNLo2JCVxy*@fA8P~$7)R0~T1ifV3@p%=$QUYEq%H533L*gB7byZ76xK82aEVI4v z9;cE{gu;bC-?IS7hDeow9p%fr9nXwy%P5{^Jza6b0e05LBbB!>*kj(&*7u+ir3|kW>HwMPvKg)IMn8c2c|6{)l*3GX2kvJ`u zG2_e`b7-^5pl;i!zPg3BsDun+K~v8+$Jrn?nSQ8#xggoMEH?r6{(TJ;)Boo^-T=<%RbyrYxa-W&mDFlGC2^1HUx&#g8$k2txo z=i!saJ@)13W%rE{z^liWRPT2a@9^>+N}YIU>_i(<_HMIl_f+3F=TsnQ8W|B~ya9!= zOaPFf473}5sD_>y9J~4#$cV3Ka!(?EVf|1(tws10BtbcEqsHwj@&y$MF_52N6-b=} zhQKnJfh;(dPQDKX)uxzSoOGyTr7R?bm?gc;XV(M-85+KzvQwzq;JYH(c8bcfAvd4NC zVXxN1A~J}SaWs6UG-!4CkOc|cJD?5Eu7MAfgLh0f`Q271H4atOp=!cZsN`D#Nxg5W zIj$UH#y~K*i*3!=SFK3xOkDaC7AM9=3pgLtvLVRba*=5imkK zIJsn-4Bi^X#2dD<@2AksxfL~{k|3zh%9EgSAxsdbZi2#|^^@#dE(Bq#ecCd=q3KVK zkm~>qnI~C4|ty~t8@7Gu!Pa0@njt6}6 zBwfhZ_9z@XQZ&44MRw>{G^DRLHgi@(lX?JLN=KSYe~gQQfY`YwbO3`kYoc)aE-pFD zBh`5<-P3dHx_=00WD6|WL3T{hBbLIss|K!QIuR8i)A<$sTjPKzS_C7bRD+#iHixP+ zWk1_T#M_Mv03%Ggl>FOgP|gQ=+%a(mCYjdyBPw#o6J=q1%q0c{qV38jEc?KQU0LA` zRQ(3bxmLh)rNT~1|5!aXeJXTYa`^$7Ytyw%&Dk~9ZAk`4=?!!msA_+F#&vGRhaa2* zLK##Y{fh1c@i)?daD~Oqw=y>Cca@FQAqpwJd-y+<2CxZO;*yfZHIUN{EqrTnOyD_% z!f^Q7lZ0xYA!(^Uh`ZxC&8Fq;Tzh;pv8qPRg~q-s{0D?iAY_e&vZCe&UX;3r zT+q4f41ua)R>#O>*zE3vIEqd9B=JMgo>>XkPN zu68PApVj#SDXI-WS7W*|n7CB6a5)(k;zmt8G?#fY(FH2Rc&(wft*n8}|l+2Z~3=8hB23YUXLqPCfJBSw6FJ6~zXE_DS5Pp<#LVNM6G&CyHFp zJ3A7y+C9#P?-s|>-k8c}TE4pdv_Cz|72;MtGYgNyZIVDZbX;oGt$qAt#FoE=?qi~b z0Q|)q-xCYOVLT=bP-+big2~~8IShFFkem~2ENXhF zINH%%6)wSd0(MY)f&BbJ6LZjn`NdG=g1ALjA+kKHO8rXu-OpzS%exf#$6~QnU<;>fNWGxWbfS(<8s?}6X#OLul!@N%NRhD?UNQUhW z^gfK1yQQwqR*bkq6~5UcQ&SqG*J7A`^}@l5!-9^um`z3%AOpT;{}|ITDkn5SYE7H^ z7%TjO^rGNYRG^2rrZs%lOf8mx^n%dK2Cw-nA{??}MSMd>(`?k7`g0lOJ8CLb45Cj` zC{>oOKJ~$wGXtsCfe4)DAq6+urHeidbQ(CNKWl5FWc`r`Yj#n ztE`fd$|tqXPcGw8&}db!9Sn4GBi|&56pn=xFF9(+OhhOc2}cZIyFA#y74g$_t0xh( z129#r2Yk39s8R??7q%f9guFznNRm*}IO{Pg!LH7yWS}9Sx+C@#IGMW9SL|>^#7PD4 zRWe>E#$nN?lvu+OK%qgXJ_K>cqPj`(&J(RbMh}9f7YHc+406KO<0KL|UfRak9v{Ik6y`EYJT6CPXQ=5!8HLvj4=a zT|6DdJ==%oW6TpQ`$t^xZMZcS^((#R_5lFiMyo}!kY}*3FDhQQommM_!J^6 zfU1EOcZ{J9v}uI3m(atM+4ss=Xk$p0@L(^|6n4rk8dHXXcmAk3UK98{=2#}=e2il> zNWSua@49^-rDV+O35N9OZ?u@r`+OF?+2cUE$+`aW?*B3raDVx_PyN~+anXG@RO^DX zz;x$7e45V%oD)WW^WO&?6h`>+e*&CD9=9Xf;obg<3v3>>@i<4QY{sTL8nyWf-LB$; zX=z*&&&|!A2`W>}6+rYOH-<9k-7@e5>+K1B%r$?sHo8hFUx z1!)a=ZNu2Z-;LO(_r+V7uMBuUsP!o8{QUU%*hnr2zVY4Ecff#d+3?!_x@&V=I|x`c zX}b)y>b>v!PdOM#ZGNQFMbdM2MR4vxml|gD4xeJe#hY*f{_N~NA28KET2ur+{SidN z(8;%%S6FQDdiVdwL<8~d_%XJ6%@5(yaEY#ckvDB)IH8T18=P9w^pywGfIl3R9+0f! z_cw4+LKxuOT013^Mc)#0OI)s;cjaI@w22J^mC$re1i;?1c`sa!>T1)T_UOkFQP{1^ zw5jw|N36{(DnBOD*v2Zi+b;M0#{3oaU#_ia0U)o7?j0fLUF*U&zxS2i=eoz;-f&}D z?E9a0?SJkrPWV^9yPMqQ-5Jpa)3yF{0ODDlC$sjZwn4-P#7DXFCFII0^7<*rF8*5U zB=J+c2yCFSnr{zIbQ#7CkM!aH6{rzL=MbkJImP7<$_jifj8wp=zRIx-qUp#mb=&V^6>_R@J z;F#eqI`lGPfM;8&HmFo_+0~Ug(A0Q)Ey|p?hq$noHu3SHwLU%+*%e7oJF95fVt=ic ztW$on5E8-JlvCh_NpP905YRG()^@gc5tE~2l&grJ^~uh#&5y`BCxWU;t8%CgX%Cc& zifw)ryg3V7h_HDP2*WX!nd`8 z)I)MA^EImmfAC`}5XU!!Fsr$W1h-(ZMIe)o(8e2@g3;||BdtE zLzEs&0i8a5ZgcfDyBUk@K(Je$gyO%H21$^Alm;fKze)pR`(PVDX+T)~m(p;8jb*8j zL1&)-O;@4*UrK}a+W)RJ#Kyd-?*2mN-{N4^0SK!6}fD?_`dT0hcxJ9t5VOf6p*1G0Uji9wbS85 z=N_DbCdLZdWIp>b0~unY!iI0D$6UjSRDDGX&P<&93r?q<-n05sVP+Q!vl_mQ45OpW z3m4@cN6qt1$|J!+rva%-6%xmaq3w$OGK^QI$}d>@L8i}!PhLW|(nR4M+~z_&1a*pgx9LCBji;Inb8 z6rt6ezeTMRZ;61nFhnaIm&D|n%262j+bPrw0wCdXP!B8psq(5BK=i$$M6)p)_Z8FH z*27_knOo1${FxR4JS~HPY30Li~~Zfg(6u5>wu zMWHvj5e6ySC^x}bDc;;)Q6VAC3S$rC%s+v@S{aLhzNXBXNAgmp5WggoirS^K z5NTjW=(dTGvWt1CjTMOoOoe6o(=7m8SefN5KXK?cxj)g;*K#5=ykE3sF(_PL`?b4< zeplR$Uz$jtb(Og>JPh=486PmBRfUn+GI!Kzve4<~d5;i`IZl|`1O(nuiFoA}3R=L2IP$e=4hNn)}Jg7}b?;Gm7EXxAL6U-X}TV-q=wIG7Vb6^7*`o zo1|xQ&}(jaN7vH$l&+@wGVc4*H^-l*rfUy2{-vqI&&{aE^*IV(vqpw{DrQ5M`F!bY zL#4ym8h&1g?L#S`QB~z(MkGMjxVpTNrf0|9o26|JkNlkU{C^0$$LC1=ZGqRxgcIAg zZB8<=HL-2mwrx&q+jb_lZ5y}exA(qhpIfKuzUt~fpsTvp`mWD&7XEu%vHQ=M5ti`Y z2?v&6G!p6x5xyPk`aQ&-s!>f*L_D;qO^N~B^wQGqSs2f&1y*Qn60x7`tBb9d{{7#V zZIAUIBXMy30jrsGHiukC+z&4%@~J-wkavaGXP6w%WGkGc@4eW+Seq`v^{k)IHaDxQ zU5GH`?%zJ6TYR=Q-F#}^#xEZid#4br`C`XiTCO3{GxHBG%{z?o|!PZ*;$C!WPlV?8R z>=|(<{|TymEsXr=M)=R)K|d?q?*XF3{tU95_>R4NJaBRWYEyGspi89xnex9`FKp%l zo3t zEv4r+}cVT)J>R1&{0+X%6G3sqXcgP$W*Dpjt`jcmRhH|I42O-y! z1U#$!!$*H=6H#*4(>om@s1{@+8|A7j`fl!ro!N;meLY>0!O*Z*dW5Zha`f_Hzxhx3 z(WU#UAZCkt8cHmJhqF4c7d!oDUAVjZ?^sjdcb0v#QFPa)QO9_hyg2ccP4nOsXTmmHFKG7+s{`R; zD)()=%S|En`h6s4on>q>c{Bd;$(%r<5e5>KB|C*-c$ZtXV^KiM3pjI8lmG3iblpZ9 zDqw_!LXK<;>&>xXhiO0S45`Oi<=+VIcxzskdK_h~g&cP-Oy_Q2()Ni@XOaal^SdA9X4{TGYe|6acW|W*P;)^za1JTT!+bo)0wsb#n{H}<(BTqP)jYUXIDP>rs*m*{p3PNpR z;>0+G)TB{TeVPq;vecr%ruY%5dR;$8JiW zdRD*dy(v?rnsXv4xci+`3l?QG0A#U%@{v9! z**kw44`gK`WPyFzG{Bs*q1sGU`u9I3mKIf zRc=lgYoTHRZHuSwQ5soF%+)ltH*DV}sxl5Z?RTPIMQ#WEtMd!!c?Tw zWz@`vYpJ)~KnFO(QKLqX+L22W0T#Leks$2V}6nLUo}5fDC9yAL8p!Zq)(* z12Qx(c?3Me1i<}pG*Xti%D1c^PFVa8$dKd=f{X(0i@}Vf^S?lb5TndL|9}k6zjv%r zd9WivVxZ<_{s&}$bO(S8#Yl1A9K#urf=#nMKmHYP67RPrK%re`=wl0jH#0nb|(Mpc+($ zBmF_a(y3+MlhR`Tg0Od!fBD9!2XA?zLBGXYVM0ocU;*FT=2x_O8RI_)bCIbUj|JMq z_tcdeTWyvbmMubP2RM=)=Y&|FNH>--I)dWfrFX?Bm$9wDPlyP8nVgrm2UbCkM+t4q+;L8RW*6PGp(c0O*Yo-u;J@-tUEyo z#et7?IB_!R+JcX+!Rm~y7r-!}N*wRTFRhSdYNXqQ@y;fnBjS}HrwsiTNfTR0Ulj2T zKHx9Oz^+O~UZfNU&NaR$qEg(1RleWHnsOLd+BozeQENf9uXO?qQU74$aFHD#fv_!J zjI5B>9xlV)Q@I*2{YxgvcrR0`;IbF@z-P+0gq3)7*?=%1(*y2d@)pq|Ch<2 z4KNurE7 zeWVW`gI%Xrm9=4j1nXA0f%tM z@!gle*rqqqRiE2&5UhahgXyCs94R_0_GUv}l87vlWZx%knXBs><%9l!%RR@L8(yvd zUU80Qh&OnS_McY(s~Ag&DTAIHt4IHO1)yRfqKrdD$!RbPMmi9wcN0G{O~B(nQs7%S zmQ?hB#1~4)W8`F0290#D>Cu=s6Y+r79JkSz1Tw&l8bEQR>wWOeZ6P<{%OqZD*l2Mx zt~-pMjAtr1*JB8Z{INj}_$JSX(e(}ZYiVu8rpAdppBsG9KwXqm8}I_)Rs_NH91Fb^ z78-jY2a$Bq{txxupVWh}4=?ax5@k1J_Uit;wSHUE#Dp327>^Myt*)cNTfyQV;r;%j z^8Pm_OZlJBc1O}3YZS7#>Y;jV<)S?47`Rmvs>aHAaCTA*wRsfME zGxr_DuZBHvM9WHi{(%5G+^zLHRnO650aRVajPL^P<7B)I0IYDS4dtyuBf9s8C2naP z8_UaJ50QYY{EkAyo;)c6CfpTi^i*i^dVwg`KO?5lPMzocGlnPk`2eHZ+1JIjF3`Ld zu51vH1Ly{T*Iyp5Hq#H~di7lJ`~A+oi!r&8I;RgYXYhY; z_16}gGsKY>!>8K#yU1_e&C^3q+zknDLTKv-DI7{|AG=yOh)yaHIdb zO4ATl#aM&E#;YtG;Aask;SG87T&Mx79`zI_yM5r$r;1A_FXy-+kd27pAdA1E3!F)m zF);Caa%Te_pNZMF6h|zzlOA?bLIr#K#~A%z(84V~=jAumBEX&VOYNxF z&)u6AghFOUpi~ESX|NLu+v_9)-BkjQYfWum(C2>0nm&nuDnw?kX~vT!j@`jKzGZq> zBfD4@gt>p=GOK$yzD{=kca1C)gIoX9=rYL)NIZKwaZ>Z^7j(13ewk60Ymb z{kW`ls73P+7i2NFe7Rp9tapIlLbVk=G!Buk% zb&?F#y==EyD?BA|i8_Z70}f9o)j}l1PkS*#(=(G)nh@Q%Z(K89Cqyb+3s_y&Q(N~0sF#y8np>l_CVy** zJTf>gGQoXFmsOtE%%iA03YWKSmYiY<`|gn(G4}m-bfPlir;Vsb3$z4!uNcH3Ccb30 z@_knq8I|XGHHAnGn20*qMN`a8{=O%!k6f{H+pOtAVTNhgJ9H+7@FT z_I0d$t~YbIogQ6ToJwGb=zcTd{i>C^XM`(aZpK;o7q!@ntqFT3sb^3M4I9rJOO5S4Pv{`m11 zmY??d7c6fATv>oBUwqeJfW79* z``2I$y~d{xAe?;dGwZ**tIs7-Z|iKggz?<<@2v95IJvAg$NSex1in9cv!Cyk=NCWJ zB3|_lEGAXle>D5C0$uJ5t^JeH6CT&s{gb8+R zpP*mYf48NnwjxV_emBvtD3Y(^sx+XdD`(*IH%T(I)mNOi7kemDq*)yW{{tL2)J1aAz zmy3SRt#8CXzjX2Mwz;^vd;%WAZ-?l<`0z$}uYLIZSX>L($okN|@~Y{4dR(~dz1-Az zK1&Del6PZ1b!)&3bw{lXutU>oA9BfMI$MMFB0)@8mhAOX-$@aRVGP6>+qg0sn5H z)AF%o!!LbaT}5XDJytbcN{z=hL}yJ^N=Fd#@G0;DOex#oZ>QdjD~r9$wXRqS{_(?W zj2-yjR!H5#(X(%a?$L|W*21pLTMn6i_S8#n!6*YTcckfuoqW6m#1MnrG58}DSK&T& zHMKm~y0VmJ+d-En!;Do|Wox{1M=o;HtfLE%2Ap_lW%Vmth!mi`Cc#g1rqTpMx=i+& zynH4G@F(6zA7Z)?2BUC!`Gi)rx%J^uJ1$hUw;ADR?E5%NH92i}v?KKOkq{b%w(L}X z`MOMTw1|n?D$c}bH9-{9kzL@0&E1v zU--3}G#M?Fg4wA-ADR>BqJu?L?zAriZQ#GqVvNz{zOnoYr@J#A#1I@?gJn<|v<4wV zO2zUBg2 z7A4ISK?v1A@h-^0noSEISd-6Z2l!R^@XsF5g+e%57ps`hrq`!rhck_|uUh;s%XCdL z;3AL_8859IpgD2O9hxz;1Y>bqRyko#N&^>!9fM7FWA6Ve&P0B<{sft+k zGs3RHfO@?w9_AyvmqnI~$uqS;z?joVR*9tVJ05V*GY^h!Ig)KXf74QZ$%tVGulFhF;E6IoBhtC-|7#e+IHvRp@Bb*Ub*Pmx7cF!_qhx@n3F66hJTq7G{ zc-3$y=$yN5E!@dJHeNrrn@xQ@t~RE;x9W+(yN+FegZs`NxXQXOE;Ot={5RHIW*)+d z=v^+gr}aG2kRO?b%TTOnx~-#(FL=;bWsTG-0W*K5I2O#VjPf5AzjXFCV&e6Q*hH1; z7)pR{PUfp6-1>sbV;-3FC!LC)AB&7LLfahCcLIiytXg3rcHFrV?YbP|nU7@U zs?FprYb0LKwGKI(ov(vON*`LT^CI8fJKZEAL6MHAk6?Pn4!06LD5+<&pd^vJLG(+J z{OiqDELyS1^5|w+20BeDrM=$V-Ef%)y$fV{BI;_=U55$qCkn>aWuqK40n5Mi5$#*sDmORG$My@xGTc*M zb4GDu!e#S(%V{{+P10x!D*qABLS2yj%+8Tarp6%q+kjh~9nf`kC8~W>*uKj@8b}bB z66W9Cw6U=b^pBa#)l%7c2d(ekNBHLmJ0}+e`qasV@l|SpkF$14xP&y%psnyAj&2o zOedL3c%cl{vB2gNDsIB*T%zcK~ zDv=4KOA@*s7-{UvouJ)gO!iW+8NRY01NeN2Jsc>UH1}TU|1KeGmFfaY$m5(S+EaQ? zL#0me2W~tpFHl0?%EkFq_2EP6(%_lK(-2BY?|_>LLsrioF^hg!OjKY!7@b!#J!~uB zR51mOSut?3B^kY}e~dq?j7z5UHbmScXKhk()2``C+RrO6xb!Q1khqF>sf$lPg*GNv z`yGxRqfe#j6wu{k$2(ucHKdgtie3?lPPIqonSDXKcGIV4r@Xl`wH?{iVwXSk(qi-KWH-W4sN(5O7TqX@9oP<$zi zOX5=(ks5J*?KN;Ly(m`=m(F^5zMqxe*Q@8@`6Uv)IJyGX`)S|Bes% z%ozFVt)i_PCD{oE%a+lj4@pU2u;IBX)B%-dHw z$g6wsa6O2hbY_&Ly^N-T=*4G0S%GPmk~$!Sl3I$~r-xs&6{dcs(ZM_(pSdWV#~I_V zQd>CviT?~=9x7gU!qVqW30aHbl$)7!Ehq$|BEY0lSgTNIq2M&O#B}A3(pW||bd23m zj;K)n&3kzIW9BRKJ;v&DOT+#0$JaPzwO9GuMg)L_=sv=p&S`(a&#`HE-Lm4T{9HQq zVbA;eWkiJHXT)?zEUOe7`GkBrIEp%=^KP>9auJ_~T%N0GQ#U-z5;HYEsA;%g>Vs%X z7B;Qxlzz~~vKbG!N9+)pAdc=frH@mF3Xl%@py@(|4t!8M7Gb|Be$Lcx8RgX}7EVCP zaR&c$Hi_SwU%C@#Z6Epx=R=b>d}igvDh}jUQ|>~fb32M!Auo}hp;eq{M6@k5U|#r; z)mHEa`}GO6edt25Wft%TuL$r4&%o7EZ{@?RAY1sv_Ow^}+-+2!X1-f3t`O!|-VN5A z^Qb-nR$04+y8O+9ov7U9R@XAidlFUCyy0zwl1W;=;#-vfpUj0-^1NW+Y4+fpV^c0u zp}uP!N@7Le{E;|*>Kf$TK;Ilazr+y+JhtvW_}$jZi&PNvi6^eSQ=TJNI?WKz_OabH z7dNN4Tgin1Ppwg{eAky9_Cfwg6Qt*0ya@q2a3}gGCfPD3D$cj$J_B#VQ4_;w@g|DM z#Qe+ATK3oqLzR%bIM3E zA&zXirAe0pX^=${Gw9>(p?=0ItzUViv)ZgmL`4Oplq0ln0T0#FZnDs9iqh_Pgq)f| zxSg#_yCYs`0gQ6<34KY=ixx!PI_KntD2;NbPRZfx4u9T>O zQ>KL{*qFwGPAjFd<2K{qdF!$f_nHBblZOWBp|gACl)WTk>=D_KDMbHk0u6m)tF{Bw zao*wuCgsE@G9SFp1EyR_U_7i%m#bUDs7v08gb{9)#%vFsHP|eIaJzJqIC)iO6&7k= z9Ma*Ds+~q?w6Wl`K}G*08udbQs|PZ*@KM*rKX`xYgclK4W>+f=z3=Q z;Rf7MAP63AP!+75$Z!r_(&pq<>WQ3B1`cT!>XBGUBdS|U&2x3^bdscB*Ot{`r?WIR zwU)x~Ji2<7KZ_{m^4>M8v(Kl|MPagh@tKM(+tAP++b6`wKj&vUSKg7@oPS85nN~=Z zuR{D2+MNXHK;i{FfuTaR`Un_$fd4e`xuOLx`DPbJ26ig>*#@a}pi8_S8=r8yWsQtO zpH{aNSKeKW(-q-~gj%4Ot0<19M75a@6mV8DXgc6MhAh%N8nCwCn<9&+IjV`L+@wSN zQ-2PnTPpzl(KOuHcx&cl9&@2Cpk%^UEn^vJXoMr9eO(<~lKAX*vL-xyXS`w7We3(& zu{1elPP;g{ILuz&QNld-2|1N)!~iJAV`0a*u;X~(Fffi4!OXXzOaaGZp38gjfV`oa zA1#U3cJY2JqpUcxH3X~|kkFm`V})VTXo|FliWvL#njQzbR}0!tL>X0CSwLI@%9DWC zHw47LcgukbhJ&{!y@aohAc2S}$v16v0XpS@J>+#b(Ue5-dXB`uMby^u@1U3hl#9{wmT5in;9w+^$&fr2^S=D+lKyDM&=CiL{ zToD!O;}bK{F7H5YfLEvA3_L4%**QAzz?Kfq&{H>;WJWCMv<68K345XyWZ75{b1t=j ztcU>q@!L0zJ-=^A&wSr_`5; z4qy+<5RkkQQaRCn7i@iQ7L?hnu&)>m@h^Jf`o7?cuL4UU&7`mcER0g;WK7NTM_@ls zHWf}aC$;)LXFixUzdiAR@#}tTV7aIdx9s&e85daBlCbR0gT`}&*0Z>$tDxSWTbd9L zDbuTw@^Xa<*mRB_Gxgu(|1p+Y?&`iXT~`p#&D4x9`<2P!PbUvb|AVp%Wl(z^hK;Qh zbmKN6OZt|yH_7nDe!t}1plA$70hqDs*RG(mDWV^{I3i#6K{c6}*Q8M$Dcy868iD@p zq71Q~^QQ~aAp6piK)B&S`pRl_9rKBcRs~2qzwGTpimdjhkL=gQi%y8V;p9lkeF(gN zl&hfR_Owb0ydamEQ;k-}otlay(MvELbI`%kbrpoj|A%QbpVxFw_OO{OFD@9ndM#(X_dw|i3n~^xuFwv4uoZ-}U%H*yC zrJ7CZQdG}Py2ZHfFtDpzSo7}BzeXbDws&E=07VE#-rDy%DXGx2MCR2Aa*<*^eheu#z zLk>?If)9ZVbx{!tSX-vy`{~{hsl&|1P?K|`4d5+cu z-FC(aRjBm}%z!^9XMbdXp@dP%5$1$#G~?!6pdkteoh%a%l7MBeg23wrmu1mK_j`~y z`Vk5I_46|U+|b`t~U z{&0z@Ip65!`uL(zw^$2}y*q3fv-?VEL)Xc^s?}%l75CRT?!HexktyKI+s(Qc;J@5- zHowE&7oW%Gp-)>>@#NP$;4|!9*0~K&mW_ZLQO*h~_f$$W^|Mg?kt7XC{JpX;n##kP z?;tUaaC}79QYpc?{=)Rm#iwHmM|}Lq;PP#E{8UgRN~qQ7yCP3qz7me4PLXerUYeq{z48;Y)Tmna~f5&4Z4wTmSe`jOe{`aYWi>{H6#C6E>iOEcl zx?oLm6*wQ`5g}%jC15@?(29+SB^?8m<^xQQadMMqTU7I2ko`6I$K6ST=|m|cIWc;4KgMQSgi^}W**7-&Bs&|jL8hQ$B|7W~KJ4q{SJ42gv1Ix5qy(|%$sd5yW!^R4(RW!fX- zO+=`Uk&`iQk3t+NqZ|$XcmH`p%b|DxpGDr(E}*S91>eR7nWhm4<(j;cH}&isLn=Pw z=(-?7*A5pl60LVbvN1?vT`Zm_cVJHfaI@4cx0r?+05|V?>~JW#x<@P_aRh#*nhFC* z8U$zhldR_pk|21qi*}vD7BOv*sH;ZHEJbBOzmcUB%Kvx5b@lLH3D@RQ;|8vCC-_Yq zbv?VY7GfH<{gf_$>#&(1K0&hVtj!=lKNKaO(2qh4rC&|H<+Mfzw{9s@^-7mJifxYZ z(<2k0T_1g0U7!ge|8Q9=Y<|7GGJuCxu>16}v|9xZ5qV(8{war7x4~lg6gl`gJ)1AMwOJc$Nsnz@oUY=WXe}a~%@-=p(+TnAJ zAI>~)6XeqUvXJq^du-q4TLz~mM@CR%*ptOO3zN~cJ|&PPf3pR34`M`U4nmNHOAz=! zrZ7(Lf2S~?J#+#mk@c>}S=vl#N4fFvt&=J1OwZS$5q=p{C^^<492;uyoPv`QBy{0q zqxXj1P~VnUgUQh*&C}{%K>_tv>*jygTh}H3Q*TA){jYkf1JghCR$X;_8CEvrhTH$& zd}~jA%-L**ozvifxDhjWTDo-`sg0o?pde&0YC&!Gjs%ou_j@#JKF7u9EwCB7a7oq_ z%nnG}EP&SMW1sPiTvD5#x95z=cnT%25Q@9YP*a+tb$kAA@Pypt|?SXY8}s? z`i!&erLN9gswLDgoroH~yx{kE#5Hpmy?$0FxTVom&%)z&Oayg*dm}fKa^8c#-^cQ# z4;lKA8lQ3siBV$3Xvo*@^7RzaoDpLkdlsnRQXY(Q8;;gBF_IMucZj@?JF@{}9mF z3tV%TK7!K!^e1(-N)ic;<%n@rKOj*Y&#uz={m{1k^ew^v(JxEo1wQ?%okl=Q z>tn@pcK4;;ylK}D1d)S@du<2i+<{GYY0=ABHAd(ZV)75d;b|G9A|-a>uWYvg8$P*h zC@xd~gZvU@=3Yx~7VcSrf&tLnVd-D53VS%LzD*G$T6PR)%d88ds0W^PFZXoyXCkD-T-5WVuAKV$cI<;$;(;327CJ0F${Co5x z-k(@}mmkzpp#0c~*le13DyD^T#S=~cv`PEi+J>{XiV1SR5eJaQpGU#E$ALVmi3iBQ zAF++^CDgkzyS76xT>(aD<=j9kR*8MlqRkc-96RFKw8l!M0uIRg0uaMl^ya;yYF--CpN9vIi9Ez{GqhdGTNj1AX*J1b&$)A@);7j(t!IxpXiQO+<5bAlO zxDdOWyl$7DwWV_I(S`}VStU3o!$TSLS>5%chx`f?q|9(cy=*2};-%NI4|YL;oeDTH}Yfwpp$()wA%vcd!34mXpbyfqX4 z^Cg^BkQL3w*#h0(01%lVw;>uDvxE$!K2z~UQW(CPBPJfa>e0MUL}-zBQ< zpYJEPEmMGzWzx#5J>N;D*rLX@g%kzXeZ?9(2}Y&)c~xt2Ai3o8HuJLN%5=4Tct&vR z-G^BT96?sT0YtWTQ`rpHx3m3eF_;|IEQJI33p1?~9sv^9D`D>WUfw^#z5-SYPlIOl zqvi3UH^BH~;pq`R{EeN;S3jik1Wax~3Bk8neH=9glqmNg+8=2e{NDl8>0yy0gJ0sQ z9=1ZO55QQ{m%tv8>kwZtY+qj+ye`{cf7-m)3y%1neRzC!N58uNy!xyU&As|GeB!eo ze<9*Wb?_k_F|v?OxaZ~~%dDJ4^Trd~e+5C~F_Xp<=i*A-EKsi& zf$RoQL`q7t&Swx=c`hZK2`}S$sQ$kl&>~RBWjdEgXWlYLn>-+5oD9a<+ld6cp6q?f zuA>`+0PQpEd1Kwuz}za*_^`&h^(U!95ZZ#i!;<~^`9^Xz{_l6M`|{UR{pM2?-+Xt6 z2H77i&m zJeq5@0?g8KsA3^q3t`o#mx9{0gWeqS@V4$1VL zr7=ro-Sf*)-oaRArF~n?VN*PGsn8|Zr?7qM0|ui;92Qa?)qToDoDEODV?SV>10tYS zk^hQ-vJDK?ewz{$1@A?Fnz=JZ{-Y$KO^Bdp_k+|;vC~)ckZRx8%{|#L!cE-#j|ksy z zy1=TV&O9zdzJ?{2zV?O}zxLR&xv#%myXzlLCuLI6w}|-gR~?={@nzYvyYBbDTvz}8 zD(myba}{H86qT7|z;}CV)n6(qV9uu0${0l9h0AGuhg=pyb-f>X*^d2nsdB%-r*%3?l& zt?CBR9TryK69Se-deNQKY%84H7!a`%)sFnu;T)t02fv8YljoSKF<1# zqO)1L>}m;bAoq(tl~J|g+QZ%-&$gT$-$`s0`(xhavLv7Vp1%A3JfXPuhJ`MyhD=}ooMRgz=I!eF4JT*hnt2Hoz21ww3zzz-0T!&BR_f@2`HQLz2urI$m5{UlX#F5FMx?4F00? z_EmQb1RmxVLHGmPGV}R(lM>R9ICNOa;Qn2$A(BXbWrn2H>s#6HR>rR7oRjTP` z;W&j-{7&!2!{VZG@BL0~RJ*>+ZMAT`Tf^oo=%5wc@pfiY_q)_neCw!T%BQImQaq#Y z*mya4g$nn-qB=kkz7J~jl=%Jb=XnAX8z3SE>aK^sOD!kMQXqmXfb3_ z8y!gUNFf%n*C5j$kUee`yD@E+h*@?Z)^n=AZ*$p(t} zWnv9hd0w2|oIEISoq4E)82w7j8VE)ON>F5BQ4I!ja+N^W*UvOmcdNpdW_Uzt)CP7V z5>?zT;62!{^YrNL)rs8eo4@ts61dsgdH1RNl(J!kuo>cRtA0&6rO4EN;~NS$BR_kB z9cTSnOUQ?k=9E)+DeVdM78&f^)~Ni4d_u6)4$Aix`Dr(?M>sLTgrK6O!=G52lwrT# zE&Dd7VR7thIX$|TY$#vbnw7>e*GudN&Mx#qsO=w*poI&D;^*k|F@Y=0*uu;j)j)gK zxqZcW7tQ(pZ6%Vhz@o)(29oLYzZpvahotS-j@1fcuNheyfL2tWU+a3UJ55M)6L{!`&3U;R&o^J0jUZ-vmoW9V;%Gv9o+>tcvk zU@q{5^$v&&f=|BTzMzUbZRB!X0l#c4He?;|edky|I?wTbdS_>cjNcWCznmtgQh@waz>@@4yq`!*ldh(|&hC86X$#R0-hwLZktf>PGe=Kr= zhq}bHCYB?;5{W*CawQsXnwd3t(lF4ymf3EKT*C&i!0@F^WOXo!7cEz|4fExHM~133 zp25Urvq_J4YRU>mx2{qkfwx}}B&+*W5~NvU1V3EiD|AIidr!{X81I-;fNxoX$E<>4 z1vP8h=Q#?r*&v6@EsSm)wzib=pr?};hxA!|_cVK@8|}{x?i~o>YegHm=ua?*d`JUp zh0-I1D;jMD>6NbVRS5KlB%1$TQ)6X=R$~hseavH3=1ot?g?X9;^UU^+Yxqt5DrIHV)bARTtpC zG((Tm?xDeh-B9SCM~Ndz_$(;)Nkk6OroUe^*nvXN0_9dCxiP^rRwD6YOM%ECguCPy zyy|p|`DDWdfe09SA$g5So7(4U;tvZW{aU#n{?EA?Uy^x+NxDMi!ChU0)E%9|+ASPK z9{!`-pL@l~h#@hPOYYzI2ePVlMYiagrlkTY!xbv00i9iPKL_97ezbdKXVQ?_RsERB zz9J|jMtC-<^aUKAp$#dNF@Wn+HXdIGD2u7fQSm<^Pgn24$>HPZ6&~fC73V>IRyP8< zqB^T=P&+EZ?@|2B`8?j@zNBFiusfzZ)c23n31vjxg=W6BMoO>;GY3FYZ`-GwHoAy7 zzBnI&UGDRQ%F&E|5)jkhF(N_W9}RMDOO@aU>jS4jE$RlA%k7J!)5gn*gKlCoah4HH zn1$f8pAo`2Weo6qq(YrVU5^V~1s=hsmw8cm)%P)C81(o;2la!;CmkL$(~4x>JEglF zc~4TRbTQLVqK$;o$`-O8z6VKR@kY;m*U@Jw?O957-6~%@kc&^u zrJ1Pzjg+x&clA$pv)tu>vYVY!{H8-9aUOMRcgK;9zz^yp-1TAml$P}pPpnodL4>ak zMbXt$&j-ACNoW5MB6h*u-JaK*O&?u8Wy~`b7=)! zIK#i@uk@#{<~y(wf9~PPG#StEN`dc2i)3xtgfbrm zZg@TX`rE4YG^(m^{s33G0<$3Q1sZR$Us;7BSG>LPp=_>*(K*-iSLkug9@+eL^gHYb zy?YqWv?`+%l4F1Xf`JHJp2F)=&`-<}!5`UlJ^`IPh*?bAc$Co6bGt{{NmddB^+L7Q z$BXOR_Y{bELSKguiC((v1X@ zcAtNKPt#}{6*763!)S{ZjXx9x3I8K%$N)u))jPKmm)2MUGHKD(jM*W|?O&3E9Hq2013$)AO=w3vR&%zr#49cS%L%c2qOeTfLy3r3{)`v`9d zR;B?0^2Ct&{4oAA6fbzXm(=6`!`3}@SsHC!qRy~wWn|d4Z9BtuhHcxnZQIVUZQJHL zk$cxyr&_DJniuc-0dtKx`qT0MleZDGgH#TT83ltRHr!NzKE0*R4y!tnhYMAjy#=LN znm4Mn@C0hSg4jq35d|`)s47*?A;ic7DJm|v55dtrIATF2PLT0^=%Z+Ha_S68^W=o2 z%8FK6c`r3YqMAj_d&0H;z63PbM)@Nj!G|n$Nsv?1%cp)^rWlf>C zGW-kNIO_knBo1G>3IDk|C6*cJc#N7op(+KR7C~eJWi?Czf$>x=+2LIRAl#{bh{7*8H0<&;^mk{o+?GPRv<_oVD1fqHM^_in9z4tkeE#~E@^z!BZaL- z>F|TrQ1`X^g0w+`Tk?a^EjT4laSJIvwRteIV*RpT@7RG+!xqI?@_1AR@+>uc#1u15 z7RpO=UD`6E4QgGQqQGtC2+MD5vh!W+H0-Q=wPq$ak6SI{H)*-5B4Hd;ONurIsnLL?Nvak*hsVxzpLgbm zkkZfOx?3AXAd}}cX42kRNy}nZFsiSajwHbXXPr0F->qE}56j20&M>k?p53ffs z=p^rbcD0C${es|z2bvV|kBE}v@nWyq`R?$I~ltm(NIWpB!BqZU06 zU~qfSs;Fl=e|_k_MIugkk_d)R}o`FhQot@>qo*uymi z$U$?_gv!N_+!Krr#<-=iZsPTouCyVg3WYh(FpK}W>6YbtUW%BT9j*a{3Q}I=u`|W! z0OSA23@(0pVT}D|Q13O0WWj#i+iBj34WyONE%*wVfiBtFfekgDA{N`ShRfopg!Qj9 z!OZ!g5xGQ4RTYsDHk@9~k10R#mn+dvEU<4Siy@?q(={7GSBFDn)9+_tHsjdh|L!sH9!t6b3EOyyba-?az8q#3o zbr%rbkR&*-L?Ig3=gby$iRIv!VDY=zBD+EnU7@UO+sin9{5LK_xI+w{ks8Bv&uo`@ zw|Ez+U@XR*E9;u&3RCZcYoTjcO02@YC=E3HzPiD_iTcz(UF&ehBH2Bs#>fZG`8!V0 zXiU52YSWB{hf&kTwsQv94eI4{q}+>+Qux8MTDcE5l0@Qm?>I2YrLZ9J^Jx@VU~ zKazZ{tf8w<7=$kLm`=$hyuE zygsA5yv#!!ZjxBLD|k*kG;z4g9UcgA3>W~BX39Pvy8xmuPHOPK*tkEW5CDTuKA-sg zrq`w){zN~!_j6X3VV5TgV7!$|0r(e{&kgA@M|@7fI{QmM1{z#>Iay9+S@m9z>m>Mg zHlIPdEI}drWtvk@e_r_tDhB_CCNJniE|rcE$!Ut>C(e(>UVf}r5^Vj8U?n)B1p?p^MAd zlpVWP!JIgk+Az_MHW}+Nh_sg z&IGd+yABgOkbWLz0g{wNPSXLm%Qtj<&yiRFDoCet{_J2%TCkWjJSec8Z(D5V>Dv|~ zr5qD+uA+NIs=biR;4fcF?`bDV*|2z5scwE8=zZ&$JyV3X=O4gMB5dj2nNpoT@sXagrSI{+oJm|FDeZgmIH4#lxx11fcNzoLV zb#D{V!kFCQx~(%X9-;!d)lVC0KI%TO7=PWIu(u5D%^B2HBM!D_QhbBN#1#WaYpDSNrQ-*K?ZmUTv}{M}OK!mTPvYPZsh z`=$4Z<6?`xYe%XokqHu`TOtv+#6mNWIH*vy!$AElX%tvJOb_^xL3=1i!z{DOg>-W zYS`Fj;5U?W+{oX+yZ7^f4wQt@!)i?kp-&PlBwqP!ujiWZK#0jyMJ!*QzU7H5=6y zdtf)PwTe~92ymUuR{wsiPn5 zAZK1VPBcd@KSCgJ)MLi;_~xgU@n^FB;!IOKjHXd(TdU}xCL?o-+|JQ@hZ<)si-ilr zkfLaFq*!fKeKY(Mm74WD?S!QK<`h~3pLDd*vI}`{XR^KPr~NsEO!(HdJ-W`#9q<)7 zBj{Sf?yP&I_i`OrCv%8{a+Hcb6WFf*j;+n*?1y6uO(XE8K&mTfIh;<%tjEll-cF~~ zj42l~MAlKJ^z+-eZ5-#WsYG#JOMxa6Fm<=N4L)fpQ`q3sJc+a+bM#^Es&+x2IJ5)( ze3{N8a-@J!Xk9s`Y1j&lvYMC7nrBLrP8@8$N@0TkKJ7ocp-2Z>`skXm z2>I&EndREVg)Lo5V%OS+w7*!^6-LEXP1hPh4FO4Y=;7U5${B{PY4?*L0@g%yXsJ-D zflWK_a>u@<*d11#_uT72=e5=RO$1R@oLZ1G%$5G1)~)f-Yl|1xyCt@jNa2zcJJR!@ zN&Y46YLsI_Swfnlahp-M&rBiRve)sP=|^EZH+uc5_p=7u6FC@2L?|DH*Sc`yl`>%sL{s7uYTX^YnIZ17AN;B3#3_I}V zfQ~_$MN^T(N+XdoaglL0ERlptl`Rsvc+%LIoIp z3}^|y&S9X1i;fBtl`!42BHWl!+r#J5XaFzRoe(!C64qZRru7l!WzYYd6nhzY=cFLH3yqM07U=RSojlD`Jh)Ee@9lDORZ zZIhO1?~0aOMS^SV-Ss(%nRF_fV|*bL7$Sl|kM$u=%KBMGiaAuLS?(La#NR_pOjcdM1o@JZ$ zpD%Emh`V9IFaCfJ;oZPR&5%rM>I6pV4yRaukTPXsl_o6=;ar$Fo7&3{_s(G}y0f@- zRN}a>?>VcMc>KJKjb|k_|0Z!)Gbc74K+&I^T>6vH+NpRKJldZYXzDz-3CvQa6ZVIQ zr=*a9J4I5PJ6@(mfjk_Eg<7f9f@TrNwbi!LW&%l5DXz)f#`n9n;+V~q-LsuO=@aYS z8eBrAPmU3Vmk;K`v~3gerkVZ$S2{-aLuIJN!{V`;e9@^ujE9@VM`KAs-wi)=Vruqk zeQ4VL+#mXuBbd$!dJE_wKQBgji>EBj!cC#^C6LzfOX; zO)LYVp`X@_^f|)0waXXuYvN9Zr%|qvJcUi3wG96e(7rI{7`{kRsI+|36vN-@E6+hDPm(Lz~eN}n)O7UYq?0%H+6a3%~ zpNEoT(8=pt7GbSoLS}B&J~v^cxi74#L?oz8nkh$~GlgvS1FrBihV3DtQ>amLdq1nt z8m}N99O_&bF21IzTK#Et58j!F#qt@@X^p0Vu~Un!vQ#WnQri90bclGk*u4r@J$$Eh z%zTE=JMT~w>=-njWW&$BHRA<+BOQ0CIZNwG?`y1Ru}-jq5Af(SU@eY(4C!^6 zdb#1Zhk;38D60$U#3sLK&UNnMf)!@{YRQ?#2pDs!V$N_T%4_kf&Cm({o1 z&$BD$KAw1f?;|jIOR9I8*ctwr?NuWzqDbH5y8i5zEgkVdpH*o45n=52$CE)D)%6D| z#lzqBBuWOdBn{@7)yAcEPL{<~f|OzonrCSmmTEO$?R$K+0y)fwxt^vb4;V=g-;(rh z-|`Ka2a$USXvlmj1A`;kea{q(srk5hS%JSA=OYxMroW6=y~)uaRDMVD58jt*%g%RM zSuEpsRpobw(>jkWarHcNi=1SzwWsHd=vq8VTJV|KHVC@h= z;7G#LqR$cZczRcXzof?K{1&LPWUer6ZpVdZzO-WM_Ga3*cJAiq2;s2VgJ2g{v(DcjdWq!vLqziBw`Xdci5~(ck1qL%ads zNN+`FHWt&Tw!NBtm_XaD8P(bby=D*d+*C<-dL&0=IJY|zaiHH0O}HJ9rRrz1+4}Ps z?}H~(?@D{`kK0H>n6PS7!OVx>*z5X-jiEmKIDZja%YctHa-z)Wfc=Qr#v zj8U0FazSWQnk<`d0UlM4GwPLFmPU%4GZ$|B-rf!FAs=W48MDG@G_>;pVFY48j{p!M=V03^XB%J`JAdiSP1@GK6+xKIcbHSn%`7D7 z>L~^04B^Gvw7xbf?y+MBmRV@|G>ehS`Cuq3*Xu?5B9M$FKD?lX>A5mHDe&NF&Ia;; z>FP`)H&wFUw(NqtVl7Rm(z68zciO6V-!a0uSB9xV-KiIMXR>Ja`Ud~nk`6`@}Uk_B^>hxta5URV}u=o{9>%(V8eK55-(X?hu0wn zGh^>ph2M7$#$Wfm1MkPVd=o$w0`Fp&U-x1te_ z@S14buAwJQKvqArpXE?1PV1gK&?i*LG4qBfh%DCLx1&NlU^_11H-5 zV%TmXFU!vDz~)FptyWKlPaOM!Ri#GI#gPmAR`?aSUmjxa_WZ<=V}Id-6f+Ve9TV19 zKS98fJ+pkWLnYSxM?h3>g9`H>TP58u?OMG{&pD3t%M#bFzXjn5Cc4w0Fy4J?%b7d* z5L(p|xsA%hhXUR^{y)uA*L|+k;2gb8zgacVus|J*p0r=T*{TL(DaCf}Y=!JL@r8eE zRejxPytW$XMf}O~DbBs|xyv_OHI?Z7&<#WKj$Ss$v)ySU!Opw38<@@xrG57194nUg z^Sf{={mvKgXxR($nwNi02N|O*T`Q~`)*Sy zv+to#Dis}^pu_(1_v!ZU@&1hxnp$rHB3}E>fi>%`I>f>+RCYi#z%5gjNC8<@NlH~Q ziuPNkbK=Z{B~#g6>3OG_|Mzh?s9m$ zj$SSXU}-{+7wWO2F%XLfmZl^1eSb{Sxk|O399TB)0C!3bJXyBLztpeX@;4B8-844y z4`>K4eac@L%?kFIF}!Q+h`F(bOT$B`sx!hj)@>9^Five2t6J+xK~6~7eLR1s_+Usb>VYQ! zgAfDYiC!tfYqQD2$r8vFtCLv93wo9`-{&8BcTHMfms5UicT1Px*OWy=+;Dq+q<#gB zd_DIq&EGM3^?+@2zbM_@rLP%s!yxkA{d!T#Hok9vPWJ|g;+KW}5tlI%G9$!ka9};K zlB_arkhEMi(ln?u$7N%bxh-C^8alFaae4ebEi=JqeP$|`t^BVa=<#JWpadbOzu~b2 zBIYNL=hKT^UqS|^FTN*W8|n*ikv0HmQT+gjX5$o|i`w>5Il+AH#Np)g8|Kw|+h^Dc(0O-A3-1yubDhW_JIvSH8f& z%DM0(uONY+p}_iJ_Mjq)#w86BlCy(jA5+4Dzi#=Y3Au=+;LA%J98MV~uEB0Iu_F<- zG;M6Gv$L{-7+6>*?)E3cTDv|LUXA*+`-8Ha=P5y&-M7E%ls|6!qYRb2=ehuogzPi1B z4HCuov;}xNdVcQ1=epjy?DXzw>A>%F!{GM0e;e9*?_#Ujt7giq3Bs3zu^I<)M1IC)+L7T9x3ANbzc`Bl3ZX)S}$Nq z(wbN{-S~Bs%3|f0w$63?15Sz4_|;(S_!ql%{4;W`Kz+i-YAmGUXC)VWMTQEXOWxtYC#a?rAxnpnc`E8XoNOkJ;|+Yn+`rHXz9adHCs!;@t@C)RXbCDo438ppD;j{; zOW-YMgu2Se?SEuWTKrvKunKua$&-?)|J_f~0WNMJ3{?deBqaU=qjonyS#cukgG~_}O3jLHJNN`Bqw!1VmV2IT5dWwJWp@-BjSgvMx=l^FxcN z#4=@b71clt{3*T{en;&aq`lgLDA|@>@x6=uqi;}(@^%?|3YYq&q4lxtwJBfWO+%OL z+a#7fJ^-Rj(GlP|-3*0+blR)|R7JACn8WagVGdVA+HxeBygumgZz4c)i~?LKr7T<6 zMLt`+;?z1HD*1z|y*Dxm5xIk$fk)^+J((mc13LDk$D$F1B=(qt!+&TQwjlj8t|V?2 zttK*>cot&xKR6gIMEU6}P0X63Z>8JOGW<1CZf$-AL5UI528!Fj#vHjk#i0l$NDatA z+JWkj@d(4^68JAAFdYOz4Ygpte)ql1JAk*gird>PuG{=-3%-RG{S4mQEgl=Giu{HYrl1jy5ZF8~C6flkUK!@XdaeKLXdH^(QK3_+dSN{R7c+H?Bf@`TBg!_BC zR$FinNIF_}OW!bSd9Bi~f&I*i zlu>wbAB-)Gr72f1R#_{s6;V;zIP$~81SW$z=DDdB%}7&h&P4{(D~5ZY_p(orSk+lM zV)@;#GNob@SY>Pi*IWF~lhNw5UggHLQ1>A^y%PH>Bj$_7ag95iOP<$4jj4nIRQwMZ z^Fez>N1PNF5QcX&qT=RtmMnZ`o7b2c#L;wjeM_?zYh^W+)|s*1&eFHywU z11E)%w@{JLtYFWFez+`mi6eq#?vaG@Sk}(e$FdCwV{OJJug1Wz-v5fhx6oNWhz%cJ zvM=2rDOIDvNY(@QUq_Pc92&r-L}Pyjy-}~%0dd_*v4}=*A&a^DrmjrQ&kehT9AZpF z@pN^s%fb2RkkkK%x(ZdJ!imj;^T6)h^g@H&-u^Fj6`9eXDvUaAIpBhu106?uqAG5W zd9NScpwz+K7mL=q!I#48P+l}NE^B=G;8rrlq;eIe%Hb3~{rACY>$BgcBeL8MRv*~6 z;Kg(a*0f#QvY#@o7mWmke)ykt#q@1mNgv{qL229UjiTrsU^Slb0bHlyKX_jwhwnpe zQ-?kww`pkNBpZ3_`U+dc4Fa0Y;eg*M6>Rz$u)m+Ct2urTm}= z$s3$K3^JGCr^aAZNQ4+NNIsxfAB()k1cP96fKqf&syp};rwX*-<7|3fxA^w1Vk9s3 zt~(}Hc&(BJrBZMwN2U%rh5boJO5%^1;>b%(S8+9RaL{be^FuqNg{O_e`2tcZH2Vp^ z4(hT`U?O*W&-FHD8EmdFhWIy<1wDWHS7~paWzX~0vt`+x`x8&;V;yQFR_GqNsCI6L z^!NJK0DHBh9_J<_H1T`bfIFN1$@|~j)$o6~t6@@LE8+QVIT)jQn4njl)Q;mlvGat2m#jf(fEqAi9n-%bFoJ|Uo z%-U|#t+iM}4a{uYmrl01tmv6-wcs<$Sc;j9Kz^pb;p3$0B0_0=MOFh9u$wTA$_Mpz zjvWF`ocaS-nX2$%2=&}n@G*?HOhFv=R?X@{* z50OP6RUMnFebd}iJv!4 zTaaF^*+N{Sq140ZiwElfv8bow1ubg_&0` z?4MsZeM(>agu*8tlv>jJAKdwX4zjN|lcaMya_yJ_3*QzQ%Otl>TDL(Wj&KQHvpP1R z$M%?few@&;vbwM{RG~|jcU(#d3)nJu*NPP-5>hiuconD_`z&cm<_?~mc7ls>(WNEl z+6@6syB3^%>u#Pp;(+`3R=1zWv@I~TZDTAR5bRk#nJgpxJ(W}&piW`Sh*|+Hxx_{# z4Pa6=S~|fh4~HU6pnL@TA&^6QqJ3;igyQ0;(-AW)J(`%}W=Jj=Ndr?YPEi7=Rq~-( z`B%~s7}8Lk`^y-bt4!3NVH!Ibc~6(mN!?|%o{PzGTZ(nAv0)DZ?exf11|`3 zqCNfItwht8`+VH4FBf?b0Mj6VEzvYIK>z#1dqL=btBNgGIrz%J)sY=OncfHSLv%$* z9d@@GZT*S}yh#x${Jko_kW8E=C>uMQM6%sCjX_=?!k^!YQjZ&`y%Af&wDFUH*#>R2---xb|t1mc($D#RJ`MBc4#rF`x3e_Do-^ zGJi>z^Ruak;qTeFU-`f5vsR%a`mp-%Ebfj}nNzA4R%Fa>@5Cg(W$H|&2>$?wbH2Ae z0LjrDILISDT!#`C`Nc%{GtRc+niw=nXSRoKkVQ2o9}j*hHSB64t;N<%aq&~3BHfsf zth^8Gp+oNpw0v7SPo70N?>2oVQamCNY`lXjUFP*sL9BYE$GdL%N=>psKH$i-OdYyh z?!6i)Mb1NMuzwt~XWlh^3O(_UGON^~wZf_78!i=X^BZedPp!dG&pV8~2DW_3Jow!G~z#LFZZgH7} zv?HZ@(5YfFMrYEzL;-U3BKn2IhSr4ZvO}Oo{Hvm4M*@D5woiD3xS)3soHp|m)$HMJ znf4>bmE=Kab`|I$22X+0;jr~77#H7*b*5#6kAK{NB3U{)ePo^7%`6%&Ks*|g+ga z+vCcA^V?zzV`|jE%!<&s=mWpttKRejt0&yRC0+0nf^Pt0r|cG(PF#TBT&%5|j8c0= ztYUDBQdbDN5IvtXb9>UQN80wr`|crZV{5uBBrM7~=R<(c*FAYyePu|Lp=Qe_#2%_v z@!JyC!SzepHwzra?18Gpd1SSZ&8shuAhKvR1u{2Q5&ciGA#}j>CtD4}3yf+owPLQ~ z?g%a!=xvp)R2V^#!!b0sqXfIO82xA54Fkq2F{LP3t?c5rtn8>?^&`NFynXVc06WwP zY^)9Vu#=tKl*aJ2S)Lj0pssl)O*;VLsWgJrz~n^vtkGgsbb)Y$1$bBh2TaYOL{li3 zX=a0YhLZb+lK*DIyXj&Yx>$y%1!P_nc3*SEd>-bsgkm5Ha#zN)jF!!=6)o26hnS{! zIMESvzL2S1iCj4ZS};_9Szt^8EU|>D47V+sawCz>79a&3x8kMdpBpfgy+6%%9Ld`SyufTL!AZ!Pu9qNJ4V z<=VqqedE}3^x?hPs39anBY&obgw8;o2sSEc zHVgo^J)YBxMoS)&Qm6O#t~&JCGL}Um)LV0}hRCn!(>8pV0%2YhS(@xOH#ku3boZ$# z(w@XLM6F6F4;j$Svx<1DyVTU5QXlM#ls*|y%{t~t!$l%mrO;Jr&;6l0hLdiOV+qp^ zXgvW!RUJ+Tqk;SlM`;z2Wlk1NhRr}YT`zHXa{{Fa=WCIp?e1}Yx9uy) zZ#9Y9(|*AN*U;^I$d_kbO3$u54*b_(0I1`{Msg&4(`H?_BV7SQCwruyiP|l%vO>=k zHRf&E6;n$`&Ti|4frM}?3J#_9(d^o&S5#OdOii+EPsIlVf$IUOh!e2+AyN@K*^~D5 zDH^f`c{j!2O{iGhZAVEu#j0p``IAQMy=O-FLWu|%zZ!+40&*bw_8}0sBXiP?*#iEU zHP$cqQaqz{RA3KgIrNc{!I4(R5B=7(cgAE%f;0_Tz^$N2Z?Sk`ooZq&z-B7(ATHiA z%}{Af_0BXgm8X^=-4_&R>R$3l_22doXdExh4a65>va9J!QIOr3YbnTSz5HE9PK7q) zdQ}?k55n2|+U0gxGz@YSqNIn-@Jw4Zpd9^_RLVg6m_*tzXY|t6O1e*5L8WZc`O|p0 za$4Ex#Gew5@v6ey7nD*sylOGga;cgfQ&j6MNwGPOv%SZRv36YhYm35Emb z^jPIu9ncZ1O+h&dpg`{in2dwh902vyJrk!NhZdG>&Fw2QFW4!Pv%)AWEUxnV(!^TB z8>@>+&G8`M)%5U)KEJ1??REvO+R$BN$2y<4*sarDpRelNDD06U&l!A?pNn;E5<2~! zGzaZ#IwlHWH}JxjDE569b8yLC9|5>Mob(wYd>zk!fBnACeEj>B(+*(8mgXljCJtmV z5^(X)Q*eF$wcKNJaopDya6IKlExv=;u-L+a)N~06?FFlDIQyCZ2!OE!mm44D!haEJo>Y8_$*Z zFgh+n_IYkPDbeIFalgWf)F~C|<3j_^&C_!D z^vFp_KB#^by!IEFkWkw7_488X9zatIs9<)dYF_*7jImD=#5(JTHdS){}>X|aydP0O;E}+q}IPB*jQC90! zUheGv$y7+%!owQjgCX$xMM3eHvUF0NsIfoDL zO#rTfvFhDcR++_nz2H_n#^Xs@B72L4CUU(__wfXl$}RoF78Nj2?SFY~Tl@Luf@oPI z*)4>DAp|o6MmKqWh(_b}`*p$^(-{+7dmUAByjDXL0x@rR_%v`GLvC9CZjUe{ID737 zcwXbifFL@d@W8RKPY=foXMlCSC3X>9Yik%s&=)seFWSww!r*NPt~L8E{#&Ms?(~;J zD1T|u?w(ulf7R_tb_nJkVt~c$N?Ka|&u~QEf63g5+4=1(Gtlo#DA5X%x29^^A-bhZ zzJ`H@xZonXP^%)x8QruE;{s`bMTJ!mIoTdg-2RFBes00!tf{K4?mfsh^joI#A@4wP zjv6)9YB%4{o&togtBiNyVu5AEChu_X=q~wdvCdFl?irwKD$f_2$`7T;d9rsK?DSjj%@-A(?VA5brUJec zPB3!k<^uxyV>pfiYLYYohUhikpFCgP_x$yDKP|E=o>kH9kv&+!lvsb-K$f>8cT+vz zUK2L2XO5)?y-U)%df3EYG5dAr*uW)a&4Fb()!VC9-ukiY2kQ6Dh)>gEgES3bGV8av4u4`p_#aex6YSH9$@6az2ESko*eE{M(O( zySF=aeeDzRl+)wZ(Xp+e!tet#F7#Vd?xsZeM^gn>nBPfZ`6;<=nKSs?TScKXKc-Ki z4StYF-Km4E( z@mF+v{1d9CiN1v@xf&Z)j=kVHBsL>4tr(E=;-*IKvA{^%l!DZQ0Q3%e<(hZ$@SW|_ zOzezOB<0F36H7M|iKs_qgzFY08I9>^YyvszXkv|}i5UOQZ;py#If&TcRXTkijeiO! zr&xJRxYo?bz)DPk{`!a9eT+i}xrHITGBL}S zXWoew@iGNboqlnJVO27_6oa{~iwtA*p7rCbUh5r2I-}CGJm7{a}UF`(Yn-!S*Pdjd~Szk8_?$!4G zC}G}7&XvOPGX-Qp?_a%eR1cIWodfze!bAR&5U-5G+gtNayiRYByUT5t?WAY)@-^}x zycnG|Rfqn4Zp{hu1pgzIzYNe~S#*biK0#OZMRO_NMRIvW-x^h{9G3!xxpzex&3a*# z7RsbNaG{gs?+m>`F2CV5L{altsOQ3s#K=+vWLjha6qkpRT+So#61rtK51w>Ht_73kWBA4SxV90l(ByA}!7EE_O+$B_!gmpmTYaY92>7$6*LGwxtm1vc+mnjyI8r zl!u$o({3eE+Mr&B?JOGxM=~6^$6C_ZIDtl3*LECXq2)QL2r^|sEn-gXei~%^}GuWa;&~+3ExY`Sr;!y>SVjN7SEgy8Kz4w zj)Q?+;Sn)eKLUelyk5t{lXStTa`F}$P?^{!K6V)^vrY_}A&CEMMfp^i@;9OMvpK;w zO2!z3w49zQ7^%hjvW1M3OoMB%jAuciU16{JDi~@;&z$9U+VW;_*{ZIkL25jny}S6e zp?u*}eE>8)tXBYrhi`Tx*&RE8+ncZe0N|wW8?D$U%}xT0e4p5#e0u|N%W`|v!FvZp zv!pP-5MMpBeEs$)yG`OJvY_U)JsS5%K(*Yem1-~8wM#rju)BkjRR_M8xSD4=$XF)( z{tmt9%drW+gcuP>@Jx>EQ)_7Ed(%f0egL_h*=ThPGb2=T{AU5f-N_A7vIg^a>+aNc zb_)FWx?Qc5VP}L|HNL-e(sRV!@(i$S(mhYvFGtaJ4Z28c<8nxye{l_F z4uajJW%5XK{j{BzoyIUd>u$l@@f~xJvDy8pdZ;&_h*;VgZPc$#b>AWy3Q5}cTQ&%1lM*cRbxWqfMRoa*3ed97OG0j=@ib853 z9EP4ZdTc6}kAS0kX_`>SG{cPyCaK?ZlgRT`Dr!IF?<~&Nvi@8Jx@FkYxyI>Jnxg{o zs~g_J9dG#k?RPVkC*&-RL*Y_CJxpfC-WE8*#fuRmljLt?D_+zW_Fh%OGg%q5~I&4Pb$N%Kuool)Z_pm(r5HRd?&Z=B1|xRWIBl}7~fQ2u6YAHz5# z_podc>(DRkVs3Y3TE1trxgOokHBD!6gOZ@&hSj+ljXVJ<{mbk9L4IOT+vhD8Uf5do zUF!oWSX+e%Aui{bnuvoV@vPYrOjWdpG#Pzjk)f>0E=m-}As7x4CWe0>nUQBH;5l zee(UR{NS_RQ=c!Krw~sn`^#D4f4@^&?X|QN>}1MDQc83j+rxu#+9@xp`fXCJLz+Yk zNQ94qeVbG_NKE{r!QVy8@;?Im)mVF|^1npjWd&!mvJgC~ELQ~5J!~q&_f%O#9yHRE zSnNdws_T<#%1UqKcc~K}mM?;pPaEHJ-NT;m=$mod1$W z>YsYX4^xE~gW;KS>XI!(0JVkCimDEfV3mMuJgslxZ37(04th#{ezc5Gyg>O|G^a1eedK;}-@gK?Z?>%u)W6RUpPB(c%0aIJYZ@`E*<^RNjlC-eRzZyo zPh$EFIBi#e?$BW1&cOG&>(h2oi!I#T+WY-#(|<&&q5$|2J4u6nm17y0oSlptQgn?8 zv~Q7W<9|e|=^#J#sT;0uk*fAEQxh+qRE+O2tE1us?Q*Xs_K{kLIo1JkkBUx|u} zz5R7Hx_E#si*?MIFARk!BWF}Z%MMS845p*LP+>y11=-4Ya&wBO%>QQ#^%wgp~8c3#Z& zxd~5a3&QtbMKc8Yql?dVeQT4skhw3qg=rp~BD=)Jx}lwg=*~}i2F%ss=~tt!1JLk% z^Bal}&A@@Z-4+#59=@_&xvv*Yd5F_Rwbbp2daJ~8GwF;d8eEZEAK##VC1H5iMj zOx#G1$)qih&lb^Xi2S*YhA*@qWXB~sN(DS_PFHd=U?lm{!h~Clt&vlwS%xf#t(Dg! z@QP@n`zthWR|b0lUnevaSOQK=Ub<_`Lc;A;g)VJ$1U?@^NGfl*d9&d$6m*vsR*hB9 z7BD`8g@*qLl1zj+*Dl|UGn#&x8c{dFur(tXmWFYr#%35@#PP)n zL&iB$=SO+Z^BJTjWC^b#yfD28fMEmcmZp5dC+`UaHYcMh#^U!*94@4i4*aUbixb

NgF)QE~&phz4znpzmJV$H*D`$;QyzEx!;9WE9 zP`)C4^oU}P;w6>>&_gx)r?Rb8AB%pvHS~Sf5Zm`xZ#b7 z+Z#}d>VN+BLR2`9X>P(@!j($4nGbVlSp3zazK!fDYg)pOYUb$@gy&AK-B{Z#t&|TtYl>k#=97b+efbc$__}`d zbQ2R=7-XqIS~yxkUK4qp%CNmAo}GaOOZ;zP9oOLLw3#N>ibx2Gj zZBtV0fRifg=ock5olp1;H}{fzUg9P#eqbUC(v-D^%mlilc`UlBNR_4Az07u4VhLv+ z9Rt`g=_M|_+U%P6l}w?~7xO@SIx(hMu{~$ywI16W?HEYjc#_kW*qrlc_j#y#CrXqO zdr1o;p#e!16N1O4T}Jq!CBNX|0jUCWe~> zHJVJpkMX_~3C$BXrzNta-)(d5LCy9$ZdmDJrDiHiw5NrOPM~nY8l4ERultiZP0#@z z;z{ZtE0O}l-+)z`P!FgJKV)tJ#O@43P5xiN3hIYo0U+H67r6nNKd-SEphGfaT$9;q zfet<`h@5F>o-KbF4g9)3(C^`Xu;4|k9nbuPia)6bprOCb_xu0&(CLT7n^vajh_+lL z;LLIP`s6NcOx>>J*&xHn{7^o>yWGDGjd6ib^16>N|&&XCkO@X=V! zcmFE3aSTbEe|!Dy^a)~A$1s}iog~Tgj8rs1u@0HCYBqh~_M*vCy_9lV`2U$JYuMsy znT>;ZuUGhkiz8uWa8O2%X-HAN>%;eh6h_kT3CXCv1$G`wEPwW{;w&T=1lN52yfeI| zd=RA#QtW%IOpfmU3a1$@P22uB>o6Jwqw#0|=ue~LIM;+!DmA!?&rc~l9UMDw(jJ20 zKDoXnZYOq1F^J9C9ws2nz3G6DWislN*CMx~>o{YXGm#injzMARz$qdw4SL<_Qj6JwCADceHQ)~? z$cUkWpVYX8kZtSryaMv#Ib!ylI~1ZykX}(703ELxRV@ppMx@7rYLHzKC?IjZFXbpP8CKBCz%?)N})x?Jlv$5Nu`qGJ+HU z4&q6L;d$Yv|8lxJ?z76%M*7^($7o&>Eb*$-j zMRTyrv_p_mCJhlL=}1Z}wQD=E$g3m=aKX6YRxhu`cJi;sQ{9w~F7lLEi>muBtzNVWLRJuSbeouBmD;*QWGUrH?<=i9@!j19 z)GNpq!hQ1PH7?or@OD)CfZm2>MGei#!VG|{_#*U&q7tfzy3(fh@*iN`DnDVJZ-iCI zBRq=Bn`I(T64m*BucLoDxdF66T;VJb==jO(I49; z)H-=Wyn7s%KI4QW2d;y3mF3n|U}Ac$pk({xA`7mO50AoV>pjn@5h0-sH)Z)0dw5kj zl%vDdf=)9y2)c%wDAMdQ2w9}i%o!Up`H;hO4iKR*or%Rg$HMUCHj-ZNJMZh!7z*6A zT-kurAqqz$^`gP-U`W2~`j^Q)+s`?=Qk@jTXN4^)-@4;Eoe-N1VSG>4pji;0#cC*L z?FuyCB7=Lp5&uN9#+I+VA=emwO;Wcl*a(MK(U?Q&k6#<16Bs^f4ZryT#uYaQ^>?x+ z^XhJ#Wxdp-vT6&d6(8F^K<0Y1|ATun&~ z-?jKwNTX}EH6tbocF_y=04l;7AL$W3d!(}%v9?*`vUDSTw0QM;7TGBPhE3 zna`gMXMJK-RYeiV4~kky97@=gWG-t2g^XzcX;Pj{rv{3(Y|c$!aUPt4B-tT~bAx%$ zP!e-sg-e|EHXPu-p8?o+M{uqSJZ$95^m2=}dw+SVS{dS|OeqcWzdY5SsFhqrb9YC~Dg~FUO0pNu2#eybQy$DvH%9x+*WC~z@mt$_=9 z!jGe_kl{hu#5e3CzO$apxDh>zf~waFB49n(t=?)rGti&dsX*DYppNJq_aA7Dfp^q- zR^l3UXQN>{@$g*UMxWN+@^5SEZhz=!YeC+dtMYJC6>vA@v|eE#BLJ3}ZHQu5+t669Gsy+PXYCug=gM$=`3LHR9!o!MGha=z_MhlwOmlnd?M zgP(?Wae1~+l=4FgxW|m$M)F~Tez%lk`b^(6V^u3(m9)*`yLNXeO}HU?7V(ie662iH zDav>>TU>0+wHZw~$qRS*AqXmX_O>?1d`mvMe0sG*LZ~uRCzgbswb_(8reE7ThFZiI zB-SUooCD~Ggfsr=Q9YR)<&E!6ec0E__0Al)FI3h#2*4qH^p`u?b#^wl!%a3`)pfSr zZtLL(T>!9J&6MkXYuJn3=-1724-(c_+VdCG*URg7>+}xlOGDdJ2l%rdROL0fH2@Nc za&z7hM7g6ntRV}=L3j7e`zi*r5Ra#IeIxd(N&DrhNAj~h>?nQeOJz2O>vO&Ted+S6 zQY;3S&*S*;%dH{)>-)w#;`@DTT;1<>dEu+ubz$L#wO zz9pP+f4z7Ys4Ws4ds{lP&d;!d`3}|IF+l^hIG2uJXc(*f6ftrK-6W6YNO~AFW+n17 z?4Epq#yW%i;L)LgIvcleWlji+AeSbvWFN2Q`vR_LA(`sn9giTj(jo323#BMZI`2{{ z!i`Kh8*U!xaJzhsNUs=FhD@Y;fR(JUK5%nZicR#KL{1QcQ(h3JfB#u<-$^N4Hys5D z#DBfeitpGWPPQ-j2S5dVp4NNBm=vjYHasUIaL52MWSXcJ=xW96r!q|^T(lvi&KtAPlU4T;4+b;-ZtWyY5uDpxZ=2c0>C{XKVrYhs`RYDG`m4}hQgqzjJ=@*9{aXE{kpVC zi@@=sKwjYeNFCss%+osFEUrsYLviabKrb9qmitO{N`sc@j!DWg)^`x%-_j|oaj4!l z$4>0so(|8`C>Tp}KAVnS&_yFh?rfQ4?#+2=xuG1#j~<;KU}8Sx_is7zfXN+l4(!Gn zUa`M!8H0pQ8us1dqrotp)3-+wQHz0uO{FW~1oj8uB#w^Q=WYRzd|dbW{F_j zpQWq5D7yiU4sbt#PN5fBbt8p$AYp)79X>-MP4!7JZ*w6f(-=XKGwxuH?LOc7hTw5| zH(sT(utn}CwpaSdranJL_ITglzW1Ad+xxx)e6u&(E8TqFug_aqpKFWVHas5B$fMlr z%O4*{2FR7)OJ+8u5*v)ecfAO-hGN5OPtQDlAUh_?=6;2QL5yvG9$`phmRGP_i%m;? z$j9XY9*bj;<|H3M0?I+DBiH9?{GOUq;H2_{P}mW+9+tDGoQ5rQnl8>}_w-B6xUHd# zI}U|#R@lzY#~t=XPa__F%r?nKVFB2X7_@xpUQ=86Tx?Q%B*Gy(R@b1S{C-(to0S*BT%LnAf5(_ z*S@TL(unx=r?0Siq9oTeMJ&(CfM<<_Ue5J|{-5>nh?~>cKVp#0GfbpRU z`Sh)=+teHVG?&#aMh`Gzq34b|%13hCC@p4GId%%J0(`pdDk216V~H%VjeA!c`2$!u4sSs*C;G|-BeWB__XA4 z5QgL+SZeU1OXw_<8I7Uj>Uk)7E2(H?SO}^2NfH0hKYG8Wgs6~~ZyTV6FWUxwk9f`} zWdQU4gGWP}a2NH}48VdMcbB9~g*7$6p%W zxvHxeE|FjT%y)|AER(h`k3!G+f*OHJXdLq@d=4)Bm-BKvaY~kfq+#PIg0;JUR2DxF zyq)0sD)xwqXZgBud_L;FAD!Hzdk6oxt;XL-f@EtXFt&H2u81Iq1Rnt*ZlTjV3(g}Q zuwHtNp9&y3+9XtL276w>X+*B5J9yXPgQ@7&lJV7k>(q8JjN;X?^qA1yBR<>G-cvq<{N4UOG(egP zy);47O&G27t~^QZ%dqX6k|tIUEhU?4{ZMEs_Yfhc{Jw{IG(N0tBa{AqVdzLMMaLHQ z9ohFH<69iB@G`;Yqh?xB-Aegwv(SB(W^03gP4==xlG5wEKkA(6H7?BmdEZLM482L2 zbosxJYlfuS2LX?=(EIcSGcIq}8gADuHJ!-VyQSBPkqLHe2<-h1yh67JUT z=JOziG86D%<(nFKFHlXwHvDvYW`k58i5Rp$k~6;FqZ``Rc;qQmwdN{p2?2m(go`$5 zoqtI$Xx2j;0V13LX~vziD+Gmx{f|6T)JsHnDki64U4pjC!YRp^)@{ZR@@X6=+9ZIYZZ;sEEM917)puR*M(QUnd64qTl zf8bcLPfDS7Zg86A(J2sqlU@q{kY3{%1K*@q+YftC>e@49r84wSzpti~QMf$>=49e4 z-J9HVMHYsJZ_?|;18wXywmV8lSB1_^?;vd5wSD<%!Zp9T;AlSKwEDBKB&Lf!y?=;z zQ-dgc7`aGgeNN@r%LbyYV4_AXkZgytyNHnj3pwf$m|}aB--0ZM?+2VCanAIVETX2t zE`KxEfC`Jfk0rS*4bHX7V&Q4rjeYhb;qUW8qNW$o#=??)Dv!0^v__3&WZ0h%XLX<) zmZLE3yaIhI`dKpStqd?po+A@EY|^eUjOL?gaJ^7YYDA_%SrXR2k{lE6 z8&Vzt4IXEdrjQiR))O`tnKEgbZ8voP45b5j(^LN%F;$%W(er-{E}M9HG}g8^HoY7un|pu`tJ7XdRlRgx*EeC#fOTsA?oea zbC1n)u)WteRSK*;gjRj*&xwO=Fodvx&f0PN?-7ei)ktnE!;99VRb4^G%YsA?6DpE$ z?IS0Vh|5P{oDI1%8uj(uSQHoBtd)|or>dvL`n4)k#B>Tla%|JD^b$onXGsX)wu=`J zv0QxSiswElOxOM?s6U0{Py>+M`LfNjQFISXMw~5J02=hZtGK9G0}(5HKI( z_7b9@mO$!qeG^>0-vrm#lo=Hwc*bF-^waa$&sa_aGl}4T6I@jmc1lf%Go4OtffSL0 zwb;z^q~lwlT-%SrTT4i+fJ=!58Epqpp4-v5i?=19dEv|&c;@N5@n9Ed=DUWmVEOo)g{6kLl{H;jGS9-+5t3-m4La2gJ1KV-}sjJKls+rfAFob|KeNMr~k&cfK2~|Zy7eXkwL{dJ9$Gt>zbwWm_43p zsiOQbNF`bin%Vq4&8gT|Ex3qyFOxK572|ewKi>{bOA|}Cbx~-}`nXOt9Lfw01oyk1 zTHRd=)=zlkV&SNc@8Gy2vaVKfV`f8%g)`^! zqDUE${|_+JzJ#5n;e%IAy@(fh9D;vO(jq$(5226=Q}?76A1H#E#!creG&sb6lbxPHso1rDrW>L z<`|BW#@?6u4TL7_x#>hSh(d02-7T`*(^->+5Ye8GI&XMrs2ST*m!mB5*NqQYHbYpW zqok;dBa=Q_308g!Mz$>+&#Z zDp}lygSqoLxKIkcoqQHR@F*#2zPX_AEdNrS^tbrLT%c3Jjyx>>fre8_uCa1>;XzdL zPaf$NVZGO?+DZljmbqM0RaaCrmHW4jA4v(}#Tlbt$!{vIXQfvbA&Ja*5*eH(QhUfQ zMMl;1DeXvAk)t{{xtsQl#kAfBZ*T(bURl_5r1rY;2szZfiW>vItWe9@L>O5*t(1|$ z>YL5CP=Tb(J=}48BT`sbHccs+85;Co=E@SZRRlnl)*`~z=cjwhHA z4@=>Rjq{`3*&;d~jOMOv`JUucag=X|(hA^y)-+~Ad-Bj@MhL|yGRf8#{ZCm`*j?k& zSje6Hg^jo$*}iCkM|y@ybv@EBS|@D?53+_5V`n6q5rjj?bM;DNAzvh`58zwf!b18- z-P-3{nrj!3tYAM&D)IeC-5SyUx4K2>*+^XlM>C%%8D!a8>e!{CYa3_lU&-lf3J72dY+a+UF z(RwrQh+OFJf6A?cS`5!^!$r<6zrg4$HxP>sfF6=i2m>1tHB|&pp?etRe&3zdJ= zt*BL(Z*_}xiL||SNC`{8{oD#qITy6JAEYT;EI|aYlX>IqNdj?l<(65_1WqM}*Bze0 zb&i7ClAC-o@h;qEN+BBglU{e*JBw_NkVhKQMTr{Pcq8H@ zkH1K-V4CPGuM`AbrEHqtY(n#_Y+ljGMcd;rah<7gwncNrnZ`pqh*x2n>&s=aih$e- zI7|PvxAYcu25k(F946E@6f%t~>TW}XT~17vZ2;b?60aCP+)vn~Jx&>0(trWTelp*X zL*}WeRLA$eDg2ePZJ9#r>V5MLJHy1pYg1*7^XPJx@Rps`6jfg$3E7S)-rNd&&UAgnnjVGNgj(mXaLN(1>Ac3(EDG@r<4*CA(B%uXA z>*^cblK6{m8MJ#wg^r09UF$u#Xstx}$--EvYpf*KN15WE)JCQSH-vyejM&TW2Csdoo(RjgOQAFExL zBAm2fm2fC2aE#f0V>;YgiR|Uwm^T^4ad07_+fKziyyjCvpId|(Lr~x(IB#qE-6|`X z^Ksy-W=|pp14J(OF-(#MamWJzc8xq&y*UFB_Tht&zJ2#>6;?z@W7*Xq{W@6`C{PPq ztsn_#lHcam@01TNSs^{w4-*|EsNvC97{EM~RPccjVZ&msoi#?gF3*viXi^RClov_3 zRYUkxX$$bh zsTzIAPTRp+Sx(fB11G^Sd_=xrkOk2DnmAspFGp2(LJvZ@MWAVnk`4d^*Ruf5s>{-4 zB*-5dhe&|muYJ>ub^QRQ`O0cf9r04s7$J99j1*8qcM&C7svP$*sEyWg1uaR4aI&^V z#Jvs;qFupgrFP94X_B6tw)yT1{Y0H|HLrYmP1fBJ^V@v7=L_1P zc<)xr?mPK_hZN0DaGFKho6AKrI(;pVXHUzr?c1sH4%Y5KNcE$iyU7Z<=3uI`&B~j@ zRA;ZK&g8W~(nZf8C^-qzC1P82_ezOW?v3+(o2~2J=!@*(gP}QYL zzCiavdRxeD*ZJwO%wi4*Yi-X(UfGVS{JKy%Iz85UA_@S!Mbw)OV5Y7qMgFAUOIW03 zc?PmvJpW;6GL4qo%aJ;wZ{HiG8?YpI97+{Az`%B*n$pi{mSe*N-TG6u=yuP$zj3-L zwAD8}Yhof}t0rZOCk7Tf6|qmANg9+vM~v!&+{C~AC>91+Rg%MlHY&MCR6tT@kybD$ z1uFUxkkCBnVT_p(aQOwsmNY!bW91J`+<5cD{&s!-sHJB}`l%nBv4eFKvEc-1d6%0@ z8++wl^?&ygLL=PTorB#43~nm~jU5lX9r2cjyd8|D$#?Ryr;vWUJuq;9bJ$h{6cVMd zN14T+ad=_`Sj3PXYp}=+{t!XSGXN@a=ED!*rnfGT9Hs&mD)8>loz}%Af3yT8mR!C$?4`@ zN}{It9@d1Ww_csLbeHfkFNL2UiU6$!-9Wp~>2qT(lDxZ;LDlZ2oO11lX|)pVCRM`B zsIgNeDNzErSBxkTe8O!;6bKilQ-8ObHK!mg0wDAtw6F;eBluU@xtO8dHAT|*C1B&E zuxTT)r}VX>rC>yYY<={Y_|VP0K0%t^9|d|qfr+2P$w{@ULP^(Z-l2$W<~8Z&B!rpw z#$7qk!DNJ3+n~Ncq3PF3Um+VJucu=o-tgR|QZMinC4Csc(WVL|dpwLZWgX<>5;dVr2!@`{gfaZ!1((A?!C=8)`#c zW~zv1LlZNLhWZXVCcM~jkYXh2ZKl>TXLl}C%I*%0*yzzgLbzas#NJvA5uvyeFUe@0 z$sgrWf(s{`jc>ppVD!eiT9Y}3$HFwgFFRVb`e9lbV=delh(Sq9a|4}O{Sa*_nT@>i z;r`6lpzYZSGyYMu2dYN-uvv)3Eset=w%?&Ajh?DSDASv`s~MO>Bd6v|UX!Rdwj%)* zM-T1UJQI1_!Z5wbm{EH3FpHaIdS_HRElO=oWIVkW{mOBDD!hs$_{CB1Gg@_MHC}bs zRn_AJy!5CbU4=_qb!cA*Icg=#4_eqDDl_Vjp$vMHsJY#`rV2Fw{?Sxtdm~i%9mGXy z6>Zl!OOuIN8-1$s#nG~$sU*!t>*QOW^u`YEtHle=$6;T`;L5iAeTQTkH6^yPHrqMW zsqxXKLO!as#nC2{Zlnrpt$$t{>uhx9n+{M2(xbF|{A^7&+8EA~N!qK%wW#h;+3pz+ zE6M$N!ai+HXfvbL?9Z*&`fGj(9M>n8gNYP&)nFsguaR>^is4=K3+H5`{d}e^su3jh zCmMa|(v5xMFbvipO|56o?k!(Cr2U4g4!#f&`7~vxUG1{G2AQnGyW9w$1Pps7JKf>A zK;0@R1`~)W>MEcrYoAl}(b`B~SUzM?@eQoqKW`^Kt0XpZLbw5K2=dXj$b{{Xp(ZFh z9Q>2GESX23r1d9a$n2tQi|>fiTwh$(AO5t1F{L8I2<>+FiTi{TR*;47ju3|<%j*x! z9#=mse%=dl{|iUU`PuRRgQF$TJfwAPt$ILxfzVZ#@(k7kv=YMm^BrigR(n>TJlWmH zS@r}gr?3WEwlHv+&FvN`6S0-g56fUs6iEMIR5VZU4l_Gy-k4h0^R+enJbU_DOfZ|m z{jxZ_sRx(C;|&6L>&X|3Y0CPbaQle_d>wG*JNiYi z7bADr)AtRWNeTTKOPN}_?5UTCqZ4_Yq5Igr+TDi54TcxDg5i8u zDt6I1u$49Q7Etkiq z$2b1Hn9ir}&X*7G>!HbZSFY-Rgmoos(FTt^#8`CLSX6V?g{U08xjoR;nHYv)M9?|?;MS^ef7%WD+Qm-& z_^cwwu3$$_(1nVVC#l)k@;_A?dF9?=D)as{O(J(=3fjNr#58~01d)fL{<#gdGV|Dk zcez&kp_qPfeWU@SlP9c=nA2Kq>-`3(;rw<=*@l-$aUW&$JE`+3)3z@60rRIs{Lx! zReJTT1Pr|Qy%(p9to^Wk(wg3LtPy{TdKwPm2UiJ%6&R1HSik5@mV^rR?K|-l>JVAa zPxJl<*bqhMb;s)s7|z1 zi12rU9N^+Pkvx`o$&p}2Q@;iA4Hz@c(}ElR$tgI}Ye6IEgWHx-3;f&KbyLDOiFXQF zj5Hl|4s)9z!k~HMtX&?F6>sbnx5yDTgN>in_BGJPK12O{^UDmZrS!7Tvuc#yqZ5gHcZBVY^%6*8-R5? z7pu`k*kTK%5}GeSiM9~9{XZLh5`Z~lh0dC^H|d6B+Dy_M9Vzzeu0sm639D{d6|df(*`&xU@cdx1ehz}DQI8yRxc zW6Yr@+m(*xQ!?sOTE5;l&a#{y-|+;oW_vpe8AuyslE9=VAUACaY@Vt9E&Oh^jK^#k0J2wRz6>?WvfRUety zidomD?M=GwK+LL^b3;uwj)AaQj_hXQ;2hjLSu8wp$THGOuR`}yE1)fo;T6IDop|74 z9PU;d1ri+tf2A6>>(j3_Bch}-jaoF^Lb_aof>!e4un_z4TQHIzWE-UsaS8i z$f?C#efQ;uWIoPE5=K8_vTeR%#Nfa6$JT%8kD1$FQ@CyKUo+ufTm6oX@7cc(B(^2$ zlZ3W)-2a6}4#nWw*|ffYjf{SM$F!5aw!WX7?_bNUl>e}X2}C+j)pA)=UzZ}`PmG0g znR_v0URShNw&KNe5{!OTm_7k0)e$6=V1YmY2_^5RKvm(UaiG-BKHebEbOK1XftH-n zL?2i~KPE}@LD&9k7q-t?1nkyZf~cVMy%A8i6U#9$GG-0G?lQOIX7l9zz#R<2)T7Ed z>OAMGAYtnW9Xk^;O8P?aQDmM+DLEoB`0bIud7;WuP;4t1!@!;}28u2tdgD%+2klxU z5@<*NOlQy%{}UA%J-Ba@PKUfiHzo%yd0JKBephw|GA)JSw#Ro}Iq-d|k33$jWlUtC zo#1-?E1ljAFtR@Z@Qk-_neRKqbH|c~f?*CN3_evgBHVtOc-Ah*cXLpkiY0)J1%%S8 zkvRF1m(V8OYVQDsN3duk#70~zj`Hh%gX)Qah<7^dSMESvZ|c>IzS+G zM7IBr-$n`4xQ@?dSnv`dh&0O%- zZWvMh7GlmXx0S!t=0>>nS8I}g4t)NHN5sT#_DP2g0R)EwE5=9IMa*gE>e!~D^EnBC zcpYf{O`2e{Z@uGq6Y|`eN(UEV!`afm5W_uwopn2=)@743vq)u;6eSlRz6Oo3Ck?(yx3&)?WVJ2p)xLt#%=V^>W9mBOGC9tLg_>1f@u z&2@s^TVTnYaEoP@PLVhP#9)igIu<|&ik#wOE|p1O?u2<1RAW-y42+km6~alDWv(5hzR181eFVB)WG5hN0|vxx05}55 zf<{S*v}+T_kHo_jW$b7a?;Mpg+0kfu3Gp}jU?{r`zafq&cInUy20?+EsG;)PXo5Hx z-{{En+)U+z++HZa%c~~vrvKoKJ%isk zV;oPxy}rvhxD#=68NkOJAV?>G3}=j=g!O>vJY--@$FfU9@-(LicGq0>Dgf|>rDr`o&Jv$W3uyg=4w`qIC-m6K6KLH;{@L-DtrXrboISM+Q>V zU_Re^=Pp96_L;zl)n`Gsx%=0Z^I9}21RQLY+mOcyz z{q*QkUdq)Y=vgxB)x47&Vv<(%!3`Njn;%1dbOc@HG!e9CE7#F8ZW@k|77`YJi$ek%|%~KmULc4CWg4qr2N`M@a7zx;%dDwFf(1p*VO$@P&60umG%&7&O!yN&x7GR zQAiiBkrg>@qKSWzMSF;DcKvzKCAj=(98CKIs+7wddz2zjDAhf72%g1U z5^=sf8Cr@SxaZ<~87?RHcrMV|{Er_wBrW{Ri(}<0q!_Hjn5)Mu5$IWkl`#)+6Flj; z_RQ|KWRMSgH0(0&5X6~>5p$|6Aqyw7UtATd%(eres^v(aV4}PKh*Z>IcDiO?r zZa_)Eebh|YKel-w(lTwrB)%QZn#ndcxUKvbKbZN8AEa4(B;wND_P6Uj+oUM4L=*gr zKuA}gYqpY^CbnX;%oX^o3QgFSAc}WLoq>Q80{y%0g5gtJp4<`Q(BF&g-i@q1j z{TD#r`j~`A>QHOaOHcX#Rw$kKz7o&oiM$s)cVhiuKFuxLp0XMMfL(>{0$rYi@bu2s#2rRi4!_lTZ1S-1b&^}+_5I>>c7^s=@fVJC@jak*|4Y` z;|eAj29H5&(ThSl0xg|H_z63a_WFt|!M8uI>Jc0-zfm2vGO?gb@{Ej+NJ zN~}TXb7mw6?;OovDstE$4On7PQe^7FgBg7#*MikB+J@LZMU75e0xX>w(OVofIgCfv z#aAVWimXKjcPRt%ePxXGIYaKX#-;-#2=_`Gf1Uo0$Eul2Fx(myPacO(DVqU8palhb2cuo|UERyWJ0V?e(OpeETbG;d`U zbk$*HR&llDybftK^f}m1qi?}cc2If1A@2q}V2efo50k~PA7B-X0P+fPg~KGUbBOWm z?GC(cB5vRq6;2@*>QSBTCaRWYr}^}Qfr#Sv0L7pPV^k=$CgUpT1!7Zts<4uB(ILJ~ z!))u2bL_+8MJItLuJP-V`XArGGx)D>kQ_3azml!uP_He8`y_$8E)J(24`0@-S+aTi z15x2wf#aEzh7{Sddv!=mLSm1oYo>gc3=BcdGkVt#(&CW9=XZV+Oz)lSaUI@ zJ>=xoa&3q^B#*?9PjHf%n_;%$7zAhl=xxTqevR2|mTXa`8&P33Zg1D+Ls`EyL# zMi&q8YG#}JT9rWAj|nTH<#X8-=>r?LKI){=HJP1_;T}zx6fSG3n`6?Jg*!OU(tpTYb}`-@M5RHD&y|jZH3H2u7)4FnHd*-R zz5W+A+PYx=kA+s5n+Rr^(eMA&G(Bn8Ic%0lmv#? zpKtuzAe(D%cWM3LRzVky)RAg0ZOAxQ;VZL*DU%GI{@wFj&lV#~PeqRURW+ye*n#Tn zUf=R26hlSVx1(;TQ9j449Wjp=_gCJuYgQAiN}|1EZ@?=XyxIOE_SnZ6jl5!RDb`q5 zg1t|PI0@lNu>j`+kJ-`4z>@ zM)q}-SYb@^wpDrbc<@y$*ObNMxc@~4ul9fJ&5BtT$$hiI7Ky<($c0^f(7T8)a_(*& z1di6|(FK1VwO(#6Iy6Vf!^L;PiZo*00f;lz<)uNbz(S7}cBlsXC}B6gZgV*WWN*ZF z4B|6&lRs4Z%?|$bLuebIq&}f`(miGYp7}=_-_1=dfp^R6{3YfG>RFYEW4miH=uTO> zy`I_L9)FzS6nZQ`D*u9(Do_|#lwpMET&mpjNTL> zxoR6f8p|{ehYB&Z@vm6)hQMXEjRbl2Qu-M&m0?xPJ4hSIXQ@qkZhfLn6@9$tCbyo!^|%VLZNStQ{ef>Fc(BO|4;Z87fMq7 z+)-A;CvreWLt#8gIVn!PZ;+F@w=s5l84*5EaHv%!LWset*Ha9LLLw!w&1Q@VIhg#8 z_`mZ{eX5k+NgxkuM^mM|5m~J5ti$b%))n|(qhydFAyY}xGy#mRdEhw4ghfn&zU^X} zu7sb~+NKc65${$*uwMsQO2z3c%~2TExn-iNrf!wi8PX!}B0d#1nVA#{c#;8xZgT;u!6!=@ChZm@$lx@~mes|zhW?Na$It?K z<(l;J+1K(z@g7x=qD|!{l20DbNl1zbVZYav`%`4*DJ`(kH{I;+j00?0s9XC^r8tP} z(4V7;gKu+~P2hPlm=TnuWDq%|qsh?*B^+q;R_(#iapu#5HNTc#SvGDAc7t5fw29Rksps;3RFhy|bRt zbdP-uQ?!pv#kwv`bg3}3Pbj+1Kn0fxT`K6N;2WDgk6s8w9t_#Wu`9ByarGdYPEtvrj zL!=##k-x4up9IFU8iehx)PX~AU!~$J$j^p@Vs=AWB2Fhb*Vlqz#ht(g*hF74j8h6h znTP%frI~0aW_j&a#5PBU1%B89JwGttZ+hbEa3JH-oppnqCwK=0gC*nFa`sHlZaJV| zVefjd#ISS;U6TNx_+kDup$HRWQZ($Y`rrosP$63EE+EjeJOUP!{_-3B>5BKMGNTza zVpPNAX3$gg>kTGBT{TK+o3={8t&tSH)q|>g^)NZ+`A_zru#kr>Ej1ISg9@)YavZC% zxOvF^JPSX|1)ae{sew&QumABtjb{JQ)3lO;OPOD+Hmv%8Kz%SW((z`{kP>tnB%i9K z`85Ramw1rb+xM1bIg8h9Kna%Gu?A^h!5zgby0zW?xXoM!12-GtI3FY zru|$Rh*1qo04W&4&efqGa!_lPeb#-g`Q#2*V9T`AkHi%5sI=OBBIPWt(qf_t#_@*r zyZw#{9)#L!dD4E09YIfyEzwPPR%gnyS2;^ng#ZJ+lRN;pNl_zQftcf9Tz6kW8%Be- z<=eS23k2z7o|NZUQ9~kXi{1eqD%~(cgFF4YJNul!vjJI(5IWEKF)#sX6ed*Kn9}d9 zr*ZGd!XpFT#6(p;IjXRPyiX+0`E7#6Qqxokfay$;v#v`i@F9e1`v)xKR^}$!QkYeN zRYh4&f0(KBRq<|cBh*#5QU5sU4R9UJNJMV{W~0EX$F=RI8iIm%5tA*h4)UZgv_}4U z>lW{S>Ky!P?C&#VzR2Axtm-q}#0czHlkIVObOPVTeAWw<)0K!Jp<~SaGJJsGRBkuW zG*XTdwbbihp?P4(R2ZYo8E9{Sf>tJI_1UTJ`fSd0rQ>ATwyb@o?rs#Hz?p!`}(#==kUNp_(LSnE3r_EmmTH@S?4d{ z8^K*w@!3e(QmgOcopUKj!Yt^-^pW*Zn;h#fUCLR2RCT$l)JECUxIn+ry#tEWF@FJa z?(nR0hM|fF-LssVoF?|kv6)1!qI8Egma}B#T1(6$a@2~7gyDnCEj)(Ql;$oD4SH{U zkP~QWb)Z2ufOP%Iy^)=y0>rTQaj1XcFAm(oMz$$aj+NO;`f7RWq0DAaav*tm84NU2 z6#}}wi9HB7!Ie3Lg)mTZr|He@BZ2GZ9^jat{1bH<0*@-1qn68wYtwZajflCqLmwsHlEnh-LG8!0&^`a!*$rJH@Gn zOh;L%O{tDo@;2ODuTlgz<3Lmb8ebtPjAw|vS@gnPl7Cs=f7RPRG)?ahbvh6cFgN3 zu(18A@x;!F8e)0Obyy%O<)Sjc`i0g`%#B)3x5OcJ1rzFHJu(FTp4eQsi+hR+uos&R zI6u7MH|oq${TOO{Soi%9Z;$jnKJ@cz9R;|f{`m^<$7SE|=iI$VJ?LsU2#zwyqB&Q; zv%O6{d3jRUjUBCv$%4~6CHVw=x+mEyuw&F7GMcgI_c&BB9Dhv4^|RlTboS8)q)PSs zs#t*wcYFqv`0LZg+7Ya{S8#Sm@1&lgdE4>|Grbra3coZZA}LB~_B^^Wf)AHY5o!<; ziPWFrI7<0L-=@6L2ts^I(TY7Z80$-zIhY|5J{b}3o(a(<9chM<$~b1|02`yL!wNgv`P9(ut{wq?5A^)^rh0yLGaV!!TX~aH?!a8<&9wxCjrNmW1 zn#6o>nbEhO7c5g_3GRpdDBjPovfjaDzML!$Zms1zt;VR@T4X0xkP{yzJtL{-=Pr9m z^t>;-x;E3PeC9l_9#C4>>ox;#B&FJ@g!&461+g$A)ZPAyd1~k_7ji61D6TErJj?ss z;5U*&aqHkY*)SoHpYtN2(~J!?;;~VH>}oI^-6s001n3U}%c|Z~%9Ns5&KQ!>$FL&Y z(As*bxc|dlWgv##kVf8`G2B59YntoqAZ{cn<=u&Mg_ zSFS}ubUztP0D#;Z7^=q~hBUF@N`tg>(}y@yF*17T(|i1rr2%i{zkrVX{9IgVgdU7k5ZC<|KSL*m1Em!dw$NM#Ss}m$K6b2+_ zH+MxfBa}Pq(D0pm_$CkNu5R)Dxn*zP87K`d@ezA55GP+NQwg`VNNA@jJdM!c-hFNru!E&K!_ z#D;7Ns$ak?jo;b`47@P4@@k-n|6(k#WJXJ5vIEA%S=o}J`-r*$gh=g@iE{? z2&wsRphhj=e*-me%6v~kx%=P!OQR07)?LdidDY&|2F*@n4HY5aO6L46aN($tSseeP zPcv~^_P0+X2kg_#n~M;pL^k)TF82L<DOcDo# zF^Z+#n>VJehTV61ankhb;e-mQ4M&ZXB!(5%$y zhm;v4b9>J)&;~f#ITT72BoY>qFO-&=%Qq*$X&iwEPokmktQb`d{t(0Otg-cmw8SY& z3%8WAb+*6-{gVv!NNaL_3u9(M$|>(Fr@A)j^Og)NpenP-o&i)>$7Ii2h8Hp(*1G`6 zXhC}c)s@bco4;C(JnDa95tAWpI#X{_5Cx@n3@I(CjXsgW!0t(8a{ut#{5VJ5q*Kx3 z&qwbkWGVjK^md;(RGCZT@qYJN4->`-lEQlAXvRbl1mJ|N?k8z-PWijAeki?J)Wpch z3wpBhsO-?Pm{cfHqJ*;kCQGqbQdci1SJIoZu8!ybvR4(^YX3j%)wTb_UZtT0+N-}0 z{;^ln8xn(=Ir{sux3&Nn=lp)Ru5Mk8)L1YcZbMcIrC zATs5-Wu`7E0<6z6ygyD(GQC}s5-GEde9Y#Zuh%h$&LxCuEUE*h#np#%%jbAUDiZJ_ z+u+dB0}!y||7Re%J&eSog!@3uw|ga~Ph8|rc^n_t|6qU>JyVR9A>>&T#}^0JW3Jy^)wiBp$BQUss z`bzlk%ntSqFtbzPQpOXsvasr?xk-Z=Cr%wVeD2tt;H}W{L+CywHZCkWdbDTBQqr6C zTwR-!n$i-tkKNOa?aQy6WEEpt*Kjtdi+8AN6B)tMM?61(8&=EAoF_1lmJ1 zC4oU^MZ(aZpqJRWMrYty-KjgOw1YspHU0?lDY0cS)kNXXP*Pz~N-IJ1S#9S$od1Dg zla-^yb5bRBdfiBte!rs1Bax~+Qmo27adIYQU(qH+nva^y1x#jC>q**?vh8l7p3;et zcBHhO`ugEZGIN4Ww{Mi9+IRk^+hBo^IGs{(_<)u>VMr{+Uh3gIYQGD}k11wMz|jgU z;0TDt^#KTj?3|6X{6RMIj~=f5@cBI7p5g-mw@*EPzW@~5fuGpden<>0_)mjEN1&!R zBtp3fFd_I&z1NJJL?BUp1B!X9-;p!v5l#AvO)zCR3bRiszHTW`d|?jQfF1A)i?@!b4EG+dv-992mFs)?IDc;nF<(`ah%VLTF?%r)awbT_Bb4rwLzCW zlLJJ#A`rC~b0YT{28opjdfd1n-ls8zhTBQi({vf@pVjNi%_^xT`kL`8%Q0tLAcu6I z@o73$l#mdbg_OH*;lV>k`lF{$kfu(c-|VTfkiu|awG-iYwt}LU_K4*~xt&*WzeRS8 zV!zoEMpckBQCP!I6d`=NGDIQ@ zLLt3Uw2S9*vnD=4?%-O_Df`#451&U}%XReyG0HRdsP6gVhfkrk_Sk3EHKxj6!e>8ms>T!cpgn@VE4|# z5$)ulWhT^Vkl;yH^v6@{!`zbuD&E;XcKL02HNO(QnA$xaM7~RmV)$)&0HaQw_>beW z(pRF%ivhXWaR>{vcUoHC7nx#<3Wk1YQS=Lo<%;~8f8#{!@?J;aLq>gC4n-_$`t)k~ z%|k-EX04C)S#dMyIQb;HM!wO4EVDl7k2b3${zsb)WasmC_?0xS3rz%Fl7Fq^uD~Sn z<;L_~W!76)y6jw>= zikR7&b^Tfan{aZkXzt4Fl*xGuNYApCS8irP4;QzKjLJC#2cs&c%ZN8!v;CQeDJQSVi3)$Sj4~a$<2ilU)Us#(C zpc|z)%wpn_PvPMdizH_{_6?4MQgP9w?@v_OID&{V7LC?O8V~WItu!k1B&Ve6ivbV$ zw>8%$n}TEuJ=ZTV+;yO(U$AJPrn_S7w%;$f|AOq%WT6jSI^bKPHzChky{_YD;aR# zl#_W2&};GC8aR4*?`qEB^LjEk0Qg8xjRL%YpV1#%*E_?f)IJ!(4mXLmi4cp4AB{8O ztB$BgjS?0YNxcfbjfWFpRvwkwHMLd-RbHMjDvu4!Db|i)FOB3teqLqE7G z!|&tE9tyaMeLqo@p8`m;)CFnWxKG&{UCM<4p4pyz^<^>XwEc!{xD+R18pktWpu0ss zjf)l}EqQ`?e~oq?efSu6uwhz&n^zYrY>JYgTA6WT6py2+G{UYSlGc<|Z;TwurMZzk z24Jo@`^XW2P*~7(?qqQ@Je`Pu#?A>wXDyp(DM;B$7GC3-OwL@pI~Rb9co}Qq4W7|q zb32Z?xmYTfyej!s{7TDdOg@*3M^m1F^6-K)!_9*o8!8&GjpjW!-{5%kY-R62k=9%g z?Zro@!O}g5bWG}KTr1pQnAOA9ZTCC%NN;}Jw`bZ<`wzc1O}DK7AHR0``d@zSwFUG> zV^w$SfBUtLB5GJl2L+-#c5M4epxUZ`{My_BQCv+=x>Oq*fz3mhRTRw1b9+lHYTH-` zNu8hs;P34szce4XX)2&VA%dXOiPcf;&#Cns;mm zA-t*3v`u19yWqliLJa9F2|h(uXGkR2&AdDW^EgUPg(|G@`+`K#+Mb_AMNv=+0dgwf zrWSut+ig02xR#ltVAbr69WExaIK%aceN!-q*4t|MD}pmOS-*TRJbveAIenaEFXbU0 z`?)Hy9=J;1WMRkXvUxWjRvqfAbKOgCJTf!9MzNsrF;41@&wyO=YQR)tGGGe0tvdqT z+PWPLRBSNNcMci8ndPoM0z7K(?N9Uf0Jm2sqksPJv&#DB1gvK!uoi<``|p)LXlmoA zWs3_Z4UaG$+f9w|$)U6xK?BRo4BEJIvx*E{lH_~cWF`Xqh{3^lhC9$*?bfd9U%R6f zoe7khey%*%E=9Z`%&vJEtD-cQlNKz^R#wWA+@~zCzF@P3j5xL zy03TM2{@mK%wPF}r`{~u#cPxI(PR-==?g!$pU9$xl7Rw2UYVE~`JGPOjj3WLA!^Ru z_R;1th~O4j&)Y&p{CJ#8ese>eV$B8glMow9YjXN+^&F8McKHJMz22-(S4IJ^DZmGo zkHAl^w=PLGT+>9!UP}MvrAJu=dUE5t`|8j+jLq$0x2KAtkwmXa(!8Kn$ zzBX4k$K0hR=f&M$Dv~n4Y&tA=P<>H1_k{{uKIPs-awp@&o*N>R|88N(7{&4xm%9RM zdUvc4p8b7X+UZn>(NW;{%+xNgM*?LvZtr^7jyUq9g%`Ee=^1~PUE$#MGi$1y$5i+= ziMH;RvHMYq=Ndw#v!qfVmvxJ<*lG%$#AlQfH6bTz)6qy+)#Dje^g6=v@+dd#bNRg6 zHJX^x)99>MLd=~~VB#T5&yEaSyeBh$VlOpn-aw+WTn??{e0YQuBgPq0jd0TTzEc#N zpMzO(@Xs`OKYw8eD;#>U0*1{ZL3Gh80;T}q%aP-cBy((HXcL!#Lmse~Ou)w#FhMBa z{E?w@xRlT3`)Do&G~L^2$Kvw^Ga<6O z`T;z?h+3_pOXVt0hQn0~HN|8{880l|6Hy!vYlE-zS9UXpj1nAR$-u&){1tofX7sDg zIa-ckHDC1OsGB63t<_9SzLIcJK;|{ym2zYsKf_1zy@TJ9WY?1dn`Mt!vG>lC5>xY{ zVon&TYR<5$CkTvv*+m4S5TvbrR8y`CpU~evi_#nnYGf$er|0aiuxO*r7Ng^Y3!!A4 zN)8u`)n0pVhZ5%moo_NDafdi{Mqmi^dfss~YYGL8MTMzBhcU98{X z*Rqupblvo&?f0S@as{1{(%btzKEw4pM$mqy)eA-#lJlo*b5;{*?o>$BS!rk}K@Gm( z)>oa71ZBDDz|VdevcwOxsop*?y{zDO82YU_VoYLwG4(JKVPkH>)JK-@vnmx*I5rUH zppziTqV?X9*|RyW`n4gR*kS}l1gEnTOK_fAoje<(yJB9*x&Wg+o20v+PoI)1#-#Z{ za0p>^L5C&RP<%$trM?q~Pd6~0@IMA4)<>Py<5t~(yYrNr_&W!x27u?{L<$ux(c+zb zPF2)hFA+#+-KIy5CHk64QP%%(o6P=|AknF$1as)Y4vO3RQ{Wk~u_tV@c#3fGPZ}sP z7)EH!uLWi9iI7WS;Y99Y3B5C@sF#nhsB#q_#Y&tfhG_ZgUqm0U=T-?Zg4=L)l8stK z#p6HyJibEZf>nk-j;`jeY;oNfDS^GhvI7NCtGSYjcI8PYko zC2N#MB4Nm-h|<$}g7@*i=#0L9Lb7Y*Tr|4Adz3Ug3M;LXD$SN9TS-?C7I>pro7*5t zec!3E+kAU*WDkH8?Yg{_Dt>*wXnXYPI^%`faVs10fy~|IAx#c5j^?Vh1**Q#ME8GH zU$uX!zTwh1u8trSU~NJ1>U+>Y)z@_osQQBB165!1Y5&N7P~W+Wzo;*|Y1@C8zOvT; zW%?r9&Hk6^+d*lu=`n=oX^};wt3-YDsjq2OzG$Y*S5i!M=SS!GqKe#cMbxh7kpmZ{ zNlr1b0mZ}{#okzLDuTG4Fb677;INaGK;r7-?%POIKRTc*lTh5>2Pjm#dsrWY#p{$hv_U?Q` z6sj*r+uH`2h#9?8R25!UG)Ty(CG7CLCRMH{JziQ@hkt3`oJgH}>#+^)0LUz9dH`zF zWxC#Wk+swOv2>o4kkfi#vd_;uu&E9Wm-RAV zM|C70eOR(PyiSnoJgKouyUiR-MS7F;O>1x4*VvqXFBq(hk9{t%2!kUuN?&jzjYtnM z)Ogz-KZUlWrSB9y!2<69V!yh%rVeZ~b_N`DA+u4a&8 zXjh1pFH)I>7EZu}7#1-=@`!gYkuHCBAk?6*fL9Gvv=P}JM0t}Wd!YWg4())OZ2}=S zO)roj@=DSxVV=3P#DyBFjne zwW(0idH{gDxgagNLS@HO(P`Diyxs zm%x6Bz}w-#Ld84P>ib3NOO#mfMumRcs%E~n88|uC%RDb&)4?m=(iSc!{;M{6j0RT1 zXWpCtperg0`Flt>z&)NUpE5!b#1EkJgSg!J1dMS#YYAS1XjHb)rqK8jDn}B;=*P0T z$jWuaN9GAPHX;ir%))XUcFEA3&IWltBqlLOpb_2Bh=+0iE&GanlL=ZP^@?NgT=-%6 z11S3nn5ct^xWWhz7TLpN6`QsIW#1iniR^!5UpQ#*XbK+B zk@DXUeFGth;Sm3U95H~QTgesoY#K%xw20$X$y@8^Zl4i7;4l1%ks-E$24F#+xZZ7K zk(FFbVPea&B~yx1%Nc{3(q*Az(uAW7`d9Z2^p3$r^Q5>SIsjFMPS>!9>MSq~o+qlH zX<*>k?}wVG^+MG+bmsa!oke#T(Y5ithW%=MxxbF)Ff(P;fr&r+OOOwK z=D`L1a1YaL`u8J?R?IMI8&V?G^dC^kpP{$Z^x|E;s;5Cu#V5a|tErSHY!n=!Q799r zHgy}S`l1O)T`u(i#D6Yx(NTmn_tXg7O*iCuW>A1A=S4FXe3P(IAn>N+RlPb&IkgY?Q<2z%c{wj`jz86#={5|{)f*b*ij`TL3a#DTPWq23|+v_3V zf-Rk^IkY=HH0Nc@VLT$v`Uf<%XTs$-zDC0>3n7C z7Vn3_C__Z+7GKhwANgDpT@PLpYi!-~_k5p6<3G>$B~r`OvJHoEWODvez@06KS^In| zlPprdj*pzsxCA?1(y{`V*%y7f;-s?%nMXjfJK%+^oLK}bK3K3)PeA>(9>H!#10B!i z>cz1QYDHLF%AUGo05Rlz=J2L{$wogQ$GKLNB~o+hvupPDHp!gIOG`3D7lWx|g%TqJV&2L+xwu6`@PeB)#&b}p_yVlewcMfeToNK>S_ z8+gBue$hrU54_(WU!iIP-tX^!XDl*KN9b>TcM}NnFyMEcuASy&p35iRlHw zJ9}Bo8`5IR19-_2f_*I6?S2_XL8V>evYH)s3zrvV5oY)i(|5-4;0Tt*z&+vX*Bz@M2o&akKKdVW91L4|hs;`*Xz~ zC{&FEYCJfW>(3&P&TOwrM!`5^)NsWKi4w2~BLA&&n~g@Db!ddtMxE}6DQ?(a5Q3I3ejqyyni2BTZ-J2IW17fGjykcT|7N7 zK$VY_=cQ61aoPStw=uv{60?mc^Xs}0)?^5;W2OOT!TWbM>>fBZwG3{n;%i*L30Le~ z7N^J*Y(91z8`ihY?{MCy57@%?uXMC*Mma2*(ZD1A#=67&k#Dzp@}HHb4I#!}WvV@N zg<^wG1oX780w|+M@!<=hTY+TNSB+%^*ex|wTy(z z?q=zz!x_E-;gm*?bCK}CV5hg9EGWZE3va{|B(2e};;`XVnJg;PTv$b8Og;96Z^;0w z0c*_73j4Oci`xjNfqZ9;HD&>yDYYS{C8I-eDLQ?~y$i5c5S1qdv1CPP5>ARHTV1-UDj)hOC|gr5hYO4NwpdGwlN*q_G>^ac+;i)vZ}ahJ4NHz7*0pmHX|_UwmtCQA)x5E=u;&3hn0HX-_qr)^ z1neDE4Nc+m_&lNIRPpn=-yL6LoB_z$8A14;KDtof04L0;0DkRj05Gu^2N<))-8p+} z^6K#1cT#@qG6UH0hBWjX0uTv4{(WT+@ah?S|J)850<(#Laa$Pe*JrmV;&{Wu%a;y3 zvFGuop^c!|=hJV4>go)7&LQ%BG~$x$?-)inWADN-f)gck|HAk6R(X0Sm#ZW9 z`zIrtJyp6@SrMx5Kl4-){6Tue0`Dofvt^Z}7|P*KWk|qL0DUC&!c1KKS086On|D|L zy0eGe`u}rhugiR3u_IT&-@jLJE1@*L!Fyoftj5mJGkEcW+*2~R9CS=6^YS*}Y$RFS< z8;j{K=@wPDr_2&N!2lW+v;#fk)$0^m=>1XunM;yJmvKoDfw$9fnAgG=5>t-wQ@7(G0sGs$jj-(&( zHN4BSot4$;wQ}s+qX{Vh_!>R|pmwv>IN}E^_DG8D(o&8X-kh1d5#dcNJylf3~oOVl(C2Q)?B$U3UB+Oi#2@1^eN4 zr6g%=BWvPjt1xdUIH-&3)0uJU%mrk@sS#_Xu+8LVAIXbPsq59h)-m=Z*`E0lL*vuU z!gxSBv}%f^CSh$Y>&B_uAv-5tanK}Y-Akwl>f>pkB?iOt)+U&sQj#H$>dka%@mWP# zQuIU4B1~4NsNw@KeTongG0ys2Fl<~)(KfV#}k5ZAzC-HkERAH_Gq!QFcA+~ zwU;b8y^4~)RV(p3vGBZ{6OIUqJ9^>9NY}G5vwNa+>u6v|?Sip^X5kD~Hxo<?ovR zS6H!duBPC$qOIQ|)2S4_!vl>!rWjva=2*(!2EueAo*ia7RI8(+;rI%^P08_>MHRp# zgKu+d?BEfPYsKBsHn&WF|Dt<( z?>xMUarjB_$XBB~kH9QfnA?z+)S&ayn|Eq7;xcr(n+*0Y<{hW?J>L^Lv9SGLpWn|gxxV8`j`m7ocPBWXE8 zs0QZ*4Z6(iKiyEMo9A5qH+}c3Bm9r>1HTV_?5R!tD>!`jrx^b5ngIfXZ}Qv+j{QLK0dz6Gt{! z8pfoP_{xSlq~VeVNggR3^)0!9-gBtzRu`MrPc{ucq@LO*;8auG zt5GQ9Akhw;gdPC#2kDvD4Rt$xr9*2Zj>I(KQd}*tV{#|DvaK~)%|RJ9{<0ks!(Pi*|qY8+3GC0tXcD%^G!;t%#&t$lA7( zFeSi!u;E?2Z~MZp!+x{?uHpGLanp&2CAJflx?l~BYz!17?gco9twKA%Z zN^yd)W;8_+L*vl-Z0P3AHxO8BX=(D!z+fv_HZG*1OHWv3< zNN$3a*2Iq5UdrFV6wU)N&k>$!rDYXFikE6nAfwT)=7yJDMMdS?wbqbvZp+nv%DwhW zt#*1t>)5D|v;f?<8J0mV(OxUqf%l~YMNFE$CtYt*LWn-b?HNEMzPs zk~%&&A{yIo65-+ETxuZAfz43BDMj${WSc7M*or#JSPyN`&9ttvnrr(S$wHgM}Wtq(#Gh`dY<*yE~ zm@KAx)6upR(Ga;*gzIl8MvhWxSL2+9`ro@%6e}&=7GuCUuU_mIr-bvu|3avQt#%*< zZd4o+A`Ovp>Dev|tT&t^*$pxVLLFTPw!p5Zn4Eqz`>aszKj?isG>Nqz>_4)~Dx=|# zDTS{kX|42gs*{|foR`i1z?aGUFz1YZX$E_bH7%JxKd48wx;s&tvwFZL*9075mtuoc zwj1nzMDo+I_2~SvwS7kSw+YN0#X6vee7j`2wQw~Yp-igkoIm^FyVHM7u*6}WXkA3F zWjwoYhnXp?>DeN=o;0w{{aj~ec0djGY?waM^wPO+UGbqi{M7LdWSX*|EN7rqo=>j8q{p!D4au2RBzz%H6BYqIDo^YLZ@EYh#o728lyrFAw@IZBN$M(!wGGC@{Jh$U~hX`lMsw}v?wtf-p z=-;U(D(E@CeK0+0riBsB805&i&vz+zt8o2)@+0iF1Z!apoE9~rTbl=?GY#u(CVO9c8&Hn5s!&;%~y`>3mrO!enx-r$W$uZWG2P>oBZOY2aT+i9EX6~6_8 z-`ZXKY^2{nwB$gNUO3 zp?wWm?IEkP__}3fp@r;Ov)&kjF55vZSvK2bR*-t)rKNeAmjosq%W_Sb;8lP8Ky|6> zy{op=O68ScGn+p8@99dHj>LZ2~_lPvIq_4HE zr~PO4=de<5S2XY1m|(Em5GTu>d|MG6Q0X(Sg(RvFzwNH2*7`mU@MzMJHg#``HWk@8 zzI7u6?_`IQ0d%O?3~V#|^p%pWBV&juX!NqL&Ik;M+?27_#fSShvM6qRJ~3 zM|t)9+eX6U1h&3SEG=200bwHQBvaW*qn`v4pz4rP+@SB_VNJyGK09Y5`RHT_&TYy% zs;Eb$A-nUlp!%k|<@i_xkCybkBYIp$nRY7L5mKE6&9qsXnWmC6AnILo+Ht28Aqj`m z^0|3C)(lf*mFr(ZMmzS+rg2KRDX>@$;Lw!vzt6m)gz+Hp3}SgA^9fFni2ELxkoHU$ z`v|1@u=o*!Ht`&Nj|@4nZgDw%_{6seejI2>xXhO57z0iApzT^>=R5X9Dgtm|l4jTf z#pO+xG5as8bBaWxV!&8JCLr$|q5l}uD znamto(1TezT4PwM&WqN23IPASVGDVil&*OQ0gJKjr*Kkq`YJMLyL2k0Kul zROCVYQk|{?FtM(r<6DMuP-59kfQme)0*Sufrv*$lE2L@|1pX!biEQ^Zp^)kKv~cA- zuAN5m4k(+?kdtjlK5V28Am8}rowvH+>3^U`q?q7&a<{S)cN=9tJQxPFqPfs#(-|@q zI?zB(Tws5O6jv&zpZlSAk8&nhw9!!h#XNkORz=-McGWwzQSXO!fodsgP$7NJ)NSD;A0rPv=WU6N@<1aIk3&Cwt+zV(IHZ`Kwip>$a6dIGjn#@EyeK zz*2fm$FwkH!~WMvR5HW#>Z$vSr`33GG3R1uKF&+8HI}zs35R{B{Ec|8Wt{346qr1& zCCFfmFXLh*H*xulKuTV0QFjwa$(Iq+9*)@oX|^n3{U6U`xeNbG$%k=BzsdvDz8xmh?wl|(eZrd*_;N1-)kD^o!h=rXfs^({WZRSEcpzeC4cqD zk|&^}t^OZNem#tb;Zsc3T(?Gg{AWT@$@>NKMt-}S_9%$@1pC$8Q$dI8ldQwk64Jdep-k&_TBA<)1y4Tp5Mi8%Vd(|s(V)o3sCO7h<;F~|^o2}A zg|}h}JSTo9P4iq$A}?7{vLPBhj>6gy;Ld}@AfDVjaM7N{CKY%Y$JvUGmH$nQW>{i%4ty++v!Dm$s8)=T29W4ru`0@KLPKIR|Hd{`z?PX&&>J=?)jgGm2y55WnOY_$W(^aj1HHFE%NL18b)x76r1!@V_Z}?7x&eiRjW$yI@Ww z$9-~v{a;Gn&+K26yir8s{05Mc?~(GbK};;$`)^9#ib>XyN9xrCbtLXu9`zqeKCLoQ z81RRZC;46U(GApWR&rWWzg8VN`1&p&?3;?nx7hhO<|9eO?mG7>M>X4Dxx~w!p22+n zSZfuPl_oi(rWS#=BK=t&goYPTm%e%)7JuR;ZDl64 z2KmX(;z1tpwMIL55yG)XELqiduC2Vr$Hqg=L)H1A)QSaV;W_UGYQ{OpvNEqXc8r|^ zAM>=+kL9dHcbjS4P4F~*Dr2V+$52;J+33!z$0%e_US=$hW#_(+hBvCbPr?0!9p_36+)4~i|TtW{HAjoZG~0$YRRNc|a`<`FOcKD3sJ zK6CyH?Gpvr;RjC!4eW6-mTRrNqvNDnl?PR#xYymJR~T59oMHYRqhm?d&G_SM4`GR8 z>MUEBiBP;_%Tosmgp?uCUhvM52NUhAaL^|R(|{BRriTG%#qD^7KcKu(MG%8(#H@h% zy4GpNg1T{z&gkJj5R_l~743PZh1A02bCWmpF;T7iU11QG=k{(u-)?a)$fX9qf+aR zTdygn>6GMan3cgMF1J)|$(h}7HP#(Twej=7DXQ6f@3u49uszw68A%=|OK`V&%$eBA z2=;TY)bb_V8rfStG#CGp4w?orX?6Qod>a3^`@eCk?Y zz7yi~m3fP-84JwXx(HAipPD&kg|ywTBi9ki&fLdngbBPo2M%{yu9$s$9R;X!CTsLx z#}~m91aLe~=+rJwb6ma^71tJ2HjwV;v;3}~L1qLA22E+*>JAw9aDmd%CIH)5$pez| z-+-h%Nh(5ph5uMAk9PX6`hSt~P6W<-BP0y!O_45HFnE)I5=&RrlWzrKNW2_C#!!F{@_+#R-PE`Su> zhs!LNg2|l>zjddXT5w{SK#SJE{iiy67{F;E4W54?m>AZq`mGdEYn!hrlS6mPsqPq0 z!0m37`73bt#?VcJ1*hV9yQtXE9zfu zfIkcBu_YW0ctQ-5ABri3?oH`(?BD0`sF%D{P~3O4Qng*VaT9hEZgir~>jVswt;-E^ znd(^?IcT@MfuelpCwK(-6|CO%)eaaM1$d?$B8rfI5H_mv4l}<__aX-9xAu|m?*D_V@43^v83MX0bH zUXB-3_^6RQ)$1D9W!Ii_RDL4lkTW=;IGoga(yyi`eTtA?Qa)Tgq;yvfXY%Yc9tWwc z>AHY8ATGbqXK0^9hWf}voA~I!v*f8|eq7{qoD(XBm^AK^9C|B_D$*dkVv@M{g{hyy}AuZ@m11|vObCH(| z9F|~ufFEcb17ybp=8~N)_uD&tK!ljzxy1pgO!h6u7;DUm+ru=4+&g%*>PnGO>Dit6 zDQU!ORFUOY;2IPXTud|I(4*Hj%RDraIP<`wm@NRHS5z3=b4&uN30G4&$zVe%lcgFa zQ``=D(WmxHz7qzUG^_iW2N~2PuQCvcWsz~)VIX&qxg{{$CA_Xh9M!obgKRG>0DVRd zWWJTazJcHiq%0|6@-^|S&W?g*t#D0)@%LSr@&$?Pi;9yR$5G!er}vNpE=9qLYu!rI z)6%$7IAM;2)A7#e_>d;+R-z@z(n!ctTl_?S}=B-LK$ zt)-!&Qin*a;LUGJ9cgyF>|{b2EdpUrCjp2%7y$7Q9;oue#kmvT;K~dsek@!%4Mty9 zdQBmA%n@Bdz&B^`E)ZlZ9>ad7FW^so&|mwqQmfI~xW6JlM;Ra(MjYl00%Zxpy&9Lq?TgI@P9Ys_}vhLy6_oUB?i9O_dH(&lAj2 zcv#_Dy&f2fN}|AGtyG_GLIAK>yJ`)g@w&F$&NScSW@Em!pem-2)~p2s^^1F4DX}tN zT6e4IMgs>D7^;}BZf`dKh7o5^VD=^b%ubRGQ75PZnt3TlK?0BD2AH)Sqr#b6= zvJ4Fd*?`kE>GBY-trir2^BN$--~Yk@1EEJpMJ>MpuA7`Men!RzG52E=$qhz9+HRC-{$jr6 zr$bqJM#=+W9rmhbm`SK=45M{$Ei8y~|4Q|&%>v=q2~oYR`pVw{*zpdVD-_f#3kZ^7qR zf63H_cF>$56%tHyk$mYL<-3zz4#k!mI*<{Oy_w#qMY&d78nB@5i*BJ*|QYdX?rbgK>{keNe*hrZYTp&0KradD4U|jR9Zi0%pM#f3^ z+knZsv&)S6&z{4HGuzA&buL+s;3=J&!Rk#7AUa}+m3em{yVoG1$F3rN0tTsmq38aV z!)6SWWxBUph9vx=$cw0=Up>U)Zz61TNdByUb31d%*WuX#FDNW|sV8@PtP9s5Ii;}# zb6r=<0KR3<7ZIP5%jTvWKKGl_?E}`vA$N?gPX~fmr95MYE|;wDAJKeD>Kk#bzeA=~ z+0Blu={Ax)&&`tc+9>Z=C%8IX6Jsk^o^2jI?vtiu$Nkwv@Yk(7n2c95Ki@^D*RPK^I?>pla1uMfMXJMf+OE$DzsY2wLGn*tO zk0RD_ngle-N2sJpXi;pw0tyrxz+a``y3}xCOT{_p|FlWcgV30<2|jZ9(~+wR<(+zPxW<_+B0A zUcF76VtQRZZnlSX`NFvB0pzdry=wIDOzC3xnO|%b(TpSd!pt=0>re_oXJv-JC=wqp z-MRZi_8b3v$j8MVMg;>( zc{Gxkv{vp8azsTw9&{Imzhrx>H{Iy^{_a1qGDAXAzyfhum!y^Nm}&Gaq;uF;C$p9a zg!#Y!X8pSg#bJTgF!kH=S?V;NEs|p8AoRk#P~cr*-9oqNQ%%)@>tu#Q1BgWyl<8a{PpgPQ%vfiGEdnBj}w1z+2~mRH+#+N!dCu9?LrJaUEt z{eNh?$L`9%K3~*v#kOrbsjy<(PQ|uu+ZDTF8x^}^+p5@HXVw4iySw*3z4v)^#+YNx zckml)esO(VXQahv@0K}SRn_RZ8h;T+2oBMVu*mbop{QF?@90t9p=V@qGIM{jm{|&c zK_f)UM(rRYfZ;N}@d&;6_t20|I zgF7qs6^WLwj`6_hkRz5sZo*u$6A;^BlzCLc5BKX^RWq+S_#vhiL1B z5VBm^0UyN<`rDSZxRLRqA^R|VCDq!l7WCQUThu!lEk0R>qlUiv+4(8#kHIZcIomz2 zkJygv=l~VAPIw=GMzDr}Xy>75Ph^XB^l^jQ*Ca({hASBxD)N`G9h&>vhadPSf%s0X z61PFpehX6vF{4HFhot2h#sDrq@zr&frXSb>XElL9O8vS*N|Ji&O_|VO=||dhWP@CP zPM=NGE6UOYdA%Qe88C}kR6zGHrQS|~JC6^f)bYmuq13e>niv04>di5n)4r}G-(?+o zyP{aAmb#oDfs}fj4i>`$+b-@(bNxtlELp%fyP9Nj*M%jb)cbSgbSBh;Sal%wP%+mG z2>UTb+vj25GT^!4f$3#AZ`m}8V%9X!9YyRqvR}5ShXb=)+%=FrlStD%!d}?Y;Y`;O zL9lQsf07rA532_bvY)xxM?_n+UYYFR?xON($Q8!Xc4wA41}=z5v^wIZ zt;_YWFdML<&ZsRbT^*+Mo6|Rn8=Gn3;)L$T7%vop$Usyf)NC*QT1oys%d4c?s;r)? zVteC};o+>k<`~GT^E-d^=2pM=0$Fuo0Mp@-7LZl1)rj}88wZ@PCR3%p5ecq;8tBCT z7pkte1DuWFbA16U{iCXXea|yamMoS7s_NIa0%v1s(^(&Ss?1Z%FlySqABawMt7AUdp`5j48=j}$~E z7(P)`4fKAgtDy6YY&O~B`ZY09aqPR!_b20P5tu{EBTlgXFW$94?VA%w!8v+ z3(07e!ZT|3M+i^ug4&M=N(zq%con>f(|pav zd3y788#`i#_=Zy@uP&gO=LhnJw!#S?{6!%a*CWHRP>f0QPu4v#azuT9E9g9PTr$~- zhEYjUDoIlWYNG5Qx2^6qikdfTExu|$b*NKLSYC@ynE8mH$Q5KskQqDJ#wIDKlo#&t zF+OKBRpc!uvwxvW!CyK3y&KO^)+Ud#QI<(gA3nk(eH>!k+gUnB3tBQ&i4z79OG4ro z6vY}`Za0q?39+NLzg`as!_J~h(7Mvbt2vu4M{l=3!0pcHis~`!mu-q!#<8mC9?(vA z+BGH6tJ`C+@tjZ~f^h1SG%4B;-$HS+lD=_fF~G-McVUn4=JwRxF}+Q%^%)W=s@_a0 zDA5%Pkeu60WZH!l%wP(=%nUf{$hO%zEXcHX?M@2Fm9Bx%XMbr;RN0CiIiZr|(O>(; zV})e?L<{#5PtFs`Kxad~v%%!z>B>K(5zv-@4r41G8|@$IQifUw4$k^appfl6^oJK> z=iX9ltUl7`My9u1c28E(B&=0A+xm-%)M?&uHcXa$+0DU})35|Pw6NHX4jRtO7(Ds!Pb8Mr<6V^UFX}B5tpKa4#WTKY_br8 zqhFs@u*xehyj;D4zR(flkEZDOYr74(^wPAILhv~&8#zlC*H8LI=C?fR!`vvERD04P zyeGfPo-RdUkmv1vwsWG^W)oMfIclk?;0ym2`rcp|#-5C5j81CAkB7+an#KP7z&`)g z05Md|p+6Z2YNBwFtre48x=SZRCi9-~vc`0rh4REc#aw|!SRqR^d)GOBi%{ji?+;C0 zDilr*O~xw}qK2YL_ZIXW{)B$*?FBHb`F|c=T>5P{l0o&z8YID&po)+xyL?_u^&CD^ ztaiW7wbd-~KiiBnN9S~EIIrj*gmjPASBT=lL22tWx|s=Hlm)|9lw07gVy&}pPfe8m z3rBx_1a=B}URUM>)evZ+A~*1rh6eLj2VQ_l{Z((TX125}MG%sOFWprAd_Wv%yo zEKi!k@Xb~agpP#Wj&+Z+t>;}(du8Fd6jsvG+VCQ<>#lVUs&0jqv5vH#=n$5@dVwy5mCe3*epZQd8hma;5fP(gvD#}v0AsGZxWlihh0~?q%e0v*& zboG&fk2I6s%F7ERQW@#ppWd?r69eRKhUIykA`C^e=$dSh_W2Km#G=!hi~CBd4xpw& zGzKx;9wL%1kR$=dC$>djOq9L&&c;hWbE(AVHMG^GEZAaoqgTB@y&e*4at3P*S&uz;dx^QDmVUOnp|O07;3 za)euVu^Cte+{BcD7;y(|+Gn=yi1?f1pgrEE2n2VjuFZLf0sg_`ktsHO)`}JrUe!cC zkh*W_y`R!Go5^FId3M969(j}vmd-{`!DAsr%SJRY$qHlSKVHI6wno8a6Z*Tei^Dy$ zbzY3Sq{BIri(P)HemW-2n6l>bfrcFkMStGKKj9zlB~Pm|=XHHg^2CC#(b2X?uHQf^ zS5TJptj6sr90K?$GY=TGk-|!=uJ}v_u6a=|J5Rpz4tcyIey$6PyhKB`8bDGc3Jia`2L27MmU zlI9PPK?k);z*v^=Dx1ukYuQx`yS$0*oz?8v%-7C2Aim62N7NE)IB|MT*&Wri{A9lG zK;KzXwgvfl^NeAIa=}A^YvfNe^pfh!ka*dUwoEA^m5@x-Az|VCV*QQM*g%7|rk@@8^9A~ohfj3J zSE0L?`NLHeS3)lc)V+=&(7G-rk#8L+SyVe;yME0;d#Vs@qWz{#S)?taKzZ+iWez4gbI+KJ=lL3_l(Gv$lnX%0a}zrZV)A_;9-T?K5qUpYnt zQbz+=>^{eDaSS{gX{#P~DjSeotvDP`GPh>a*ge#x!&nbXwE=?kaonv@l5{*g_n0&4 zHt@pnTFs-yy2-5W2J+>qA{U*QMk`CbAa~BHCpzOiIq$u~$tJfXb|Q)16-GWn*WJy8 zzTnpUE0eNDNVq*+eesC^^ig01m@o1NL< z5ysDvB_KgQBF9Jf9uK^m4*__8clpm6A(TgV4^3hS#RZU&1D|d_eJF28(gvN|xLriF z6s3c!p;y3&=f_aO+JEv<7u~^OZ4BHWwJ9{<7prg70Euxvma66Nx=O}mpOhA8y76^@i@NvU1CZsbww zPjq`omZcxck}PVT@w*1yADMlIZ(hJORminAank1mgQha-D1pdL_*aFhBnpgM9UkF~ ztx!gCG{HeCGwX&v{+o&x$icE$VlM)oZ5a%{xhcfi?Vb3NCXeo>F97gxoxUg1IiZJf0N#4gMt3JWrSp6m~Z8 zJCJ`KfrgTzx`0-v;%$qejAj{G*g(=Z8yR8Ex);dZJe_TKuuZZgG!i-Ne^-qQfNgzbO;N+NA!!FEDvB8&bm>s#eFmyx2t9H@H zeCXo!m*>z>UNY;#eO}boS1%_ip$!%(U((a6PGdz%r^5CkHRJ!6Gv2@Hr)$=p^0se1 z66>~y=knJXugCe*GrXi;ic@7%Jel|M*BLL((UKt=r%WID%9Uk{>oX6o9hTC}QQWypU|j(!98y~_^iYUzA}Yt5$s~j!0Yr<;7qk?6{+=#yL_kA zd#fy63qNzlpVPG4NZ z9a#Yk(?1qC>hHR^2{3!vKNdvE3^E4JtNh<*oxX4uq zleQTllOeChcmZ~-M4^~8S&2WpI#5PfFQIrCy8{x;h0uv$jYU9ror%QxI~8(B>(KTg z+Rf|S9nF9Gb%`@KS`VSqX)NZyub{fgcB^U6@C;_=FhSLL*~LY})tMfJ6>L8oFe3=% zmPlUy4Aa4=U=!LAPUG32{ki%vAIl9sP^?l`p|fYbT)KvtFLjcgxa`s!gF;&D-fi+a z6^4B=gABVTrJG$BWI;e}!}JTQBPY%FjO5<$k2-TTkdJVZJWm z^{*lroWft2G;bqX_#Qy)c2xRRV5b=sKDs=D7^`vQ3ut;%POWr>2&;9PGJ@0nl&sx4hx{GAkJ$f#gPKjIPMdTO%F;BZWL8T+a9fXPv{XYmf_t zvlHcgtUj~&waTvD`^aM(?h`G}&N8m3C|03gn&l)4uO>N8G47;8&k?sD*QdK6>IhYEdZ806XTKY?gUrcFas#tp{}w zwb1g&U7U}D%&}7?tfzqutD50)Lp({;9NbJueo5bS@Xk%}mt63KEK{yv_~fR&g#a3R zmd;A!gpa2MCorR1?FJ=lrfI~Y!}0J&5vz(t*{MK&AG~92e?|N3`3HjKMRPKvrVPJq zGjm0HIUorR9om!Y=^;~%muQhIB^j9%#;AE1UDw5{DR%nE(O;2PozkDGY{4hkro3{Z z_V{rcdZAZe-q?|LLfTs4p6cVx0Q-G_T`%&trrL|?oBG42WC&<$1Jn;o1P6KCJ zLfFu0m!fyL$*@9cOjYM4S$+gkbouk|bjScitfF(as<$@ zo5g3L$cd~<2BFG7hXDp?5}sC0(7d%r;H^4q_ZwwFBas`a<(xO^|#ph}7 zIL2J?3OJwCS)Gx0U=o9M3t0f|D=VqrH<_OwQ4yu<4xeR>)33#BMg77V;FF~2!34Qy z7E~Y%K3a<43=dDIEV37;SAah~)M-rgGye}+wc7Ko<0}m)4R=mugi)f?3Q1LyFDm%q zeIl_WM!#8=#dl4A<4(K-NUzCx*Dp5&{DZoX2fP>SUzKHoItDVewA=^~6A1PR48-`8eKdorON^VIGP{mBR(j%Rd!JPTIz6{E z;uU^GxX3=s#N{05!n-@eES8%)ftB zg%OAz@U`Dq#P5{uL>*f1q|zj=QKhq~KLPXV3r8DraK(Um+lK0re4hImpUNSjK&ndF zb4-8G^#zvS8<;F1B?xzvznMk?iaR!|@yA!87)6Thg4Xx~$djP-Bar*3G=VA~GcNcO z#NZlR*b-Ash9d9?=C*y8{)_0cV`fjsL^%N_J+%1*p2vLez0!|BqHMGrkxlyQ*&}@4|!{JmI1JE*|k)_S7_xj)PYgoenz^^fd{yTn6 zjBa&)m%VRGyI?H~H%8q_MzefYmNTSv3F$rPAeS2Juv(%Eo|Mi1U;6bKiBH$0`|Qxf zU;X+PXW1qSG`ZwC?47*X1h^x(uaJvXxs3ZDlqyNtg643y*B1^C3jQ?3aXjVS=S&i@ z-d{*5iA&dq4$ptD9T~NeS{h12A7)SD~^?RJceLrBCVH-rfOf%sS7dg zNWU~hEdDS5ty{aVn=p3kUUyk#>uCJ5ZS&gB{0}FzgHAUs&EsAkfj^Z8dkc6PyY^04 zE4#2j?1)picXiBkPf1qjGBL)B_Fh3ks*)WI{dd`tk+4mEs(&L`G1wq?Qlg+&`X2~v zC87Tlfqk6!Uj%kd43NM!EOYr^32a8q;EtlbH zxFqgy(-dn*5x>lBt(#9F_VzhQ^P4JnuQ8L{U~Pc|OarHhoq-!7aI9~bd3NF4o0ji9 z-=?I&#Ke+Ky!Zq`L2bTIpnWw@ofIpKOABSdG7i4_NE~6qu_L!FzCCksr}u*L*+4;TkTL%{fO7UBrt_+D@|?Zh@TF*PdYJzApUAHr4tCF?BqA!Hr*Q zaUUE7ot7lu*ASDAUzZ*o!*4Oq^Cnz$1prl7)jm5u5Ks(pUfif}lMknuolL(k6GeZ{ zydxGA)eJMM6@F6_DDn0|3A)vo5sq%E=m9_E%6}h5$rcRSg&i{*Jf`UQViD2=ZO5-2 z??GKPc0*p!EGylFY?@HgH@@6UmM)|C=QFSaj4%x-VBfS0J&%>U!L}|zgj6+XE1oY` zs=x9QWS%b6^#cux=Yeo5)-SAW8ryEW#=zDc%Ez|a;4;^`M?+GXO9|0Usr#uXJ8EvU zWSo5xQrgx)0qvh6rb3}2C)mo0>t8mOp*9>1RYLo=v5hx5P)kc}!dRulNDAL?gsX_K zcTM(=Ln2b^AeeORgbq|Re&ayCRAuaAu#9Bs)sy@GEk@BdSefbt$#Bx&(ix}3K4V~+ z{Af;IpnTrQ5W)zE6EvVcAsBNV2XWJ+lq2~gUiTXzyskD^hR>bk6R;aB;r0$lHdoNN z0dU=H$iE93vF{C?!$Rz&<*mm9w!Lma{2KQGM0VAC0Q)_yAwcaOpqAy6s9^mJe7pMO zU5igJ^7<04@q26ZKG#;E(B{AR>H7T|R*#&CiQgH&puW!E^#t1mbco=^1k)j{rUyRC z7)mi>*v6ZHlaV|+kv#pQPfG+2d^vzAlcJxSm0>z#vFV@naUz83-G~1TH{Ml!xnTTS zsflmrkmYoHp|I!pj4+hx@12=vRKNX#y_FUjTg$(o(c?No=Ibb}k=P|ygI>vWGY4?~d3fO;!T1@o=mu!eyZ;0;cD`bIhHJ>n8+hyX z4~^R~Cu1Heo!CvrOcEr)1^k0SYoGmtLD#|lcMLj7+U0-2paFj|Xiv1lidf~9n-e`d z4l2IijYBa`rWRWX_&SaYFUs=I8Yhezw7v-pXGFYvQ@=r9_Rvz3j#{%cTIA+dIA-A~ zl)ad!t&_(+%4Ri5`VkS5c5_p5ffO_ykb({wrvXyXRjmI51s#R`Zwh*C=$q_c3VN>- zzgBILq3cpNpr0+iIBwKq{$Plfz=llM@l%!8K)~)xUIdoUpMft69)WNi&3wfeD;K+S z@6@%y_v81&%g0MBC~pjzqHnf8?$ePDBcuQeNCx<36v>M=^Ax?u%Hc`dziNLdXRexj zox|FA27kElZK29cX8>Bz+U)-T(Bj%xvgfmwu@Cl$_(q8n_uvx-XK2v8MN8)<-Kz-j zzC5b6niups2at^JG_8b%>NJp(yY)`^h9tKr3>~~PZ*=v!+vXWuecciF6jF0AwceM_ ziFYK@_bl1<=xr&oSY=>%Td04$QxOn%K>`zd3S*{>5a4F5FSH__U+sx_0k{fB1RF5~ z_`mY%H1MF=!#TS_UE214IOl{6%vUn%|{<*USRQ1n@oi$$uMD%Wt9BHVApl39@^MYub@^VZyjZ`i#RopZded5GVYrzqdYb_aFTJ+}N8VJsvM;;|D^faS0K)IJK>Z;vcgF zBzM$zmwsqv-;>ew8-9jxNbpOy#2SR3Q|>_|EWF03N*wy>c!K#cTX^BHc7s(JfG*V{ zi;R~c7)LFb z=b+Z4E+@)L*ihIkL*M*D7q_U6JwA!RCDfq!`r-wtD%;vETcRe zaox1cV)=*k6FMxjY9j$zHPrGw^5f3HbMD(y?8BOFK8i_c+BeVCWZ9}r)80nZn`O={R@tUlAi?bL55er9&wT}-FZzYU$vD|kn5LZ~cGx|EM`C1u zHWC&2BG%FsTZxv#?I7*yY_2qfLEWE@sO^6zn4|tX!OUyZtRGo2c}8j!51STKb1TL( zzO{BSYlm&g6w9b@@YprE?(M`anP(=a|4kVdDHzL#l}s75qA{LG5Vix`ux>kuU3ab2k80p4}u3f(b@D+sj`P6r6@9)k>ZUd zr~}*F{A$O(HN^BZN0LYE^g*$eQR3%4LN7H<>Z~Q|@o>pFOSSv~^;svasuZZBzdHs; z7}yonU6Ks4N>-8x%6($5Y9g1z9goeRhM*+OH*eoc=0!!cf!Oi}cDkEod>DQhDli9T z1JzzJ!<0Hj)u`_pCw~aBkL3|cOlBwRNK3NWj65Pr9J}Qy5VG@GB6546d(xbZjyIHFBoJo|U8Z+hNXaZN^FIZF2a z1aj$ugf{#>z(;CZwYgj}XBja?DJfnqY)|k&?O$G*GcPPfAYNDW^HG-^Ph?D^KG?yQ zEQ0~Dz~moYIX|m7kc|^vT@C(?s<@|tP7h_5={5v)?&^=vicUi=L2=j9a0R2Cnt^C- ziIx`AvA{u8xk*xYG~i8rVxF?8>mFL25dOQcbY_h?S}`>rKItZ?+w zXjqJqk#CY2eN;(FM1ZSP3^It%Nq`B5L6T!fAAj3L_Z>fk>C^Q7$5uAZTdr{#-mQ}Z+RBGrKwH@dZENtGInY+#i~fr7 z*H(tFpxuue{Yxv)fVUVq18L>;zqB$1#$Q^wp;18}?BBF9Po|q1pZD9Dm@;Y2@Wrf? z!2E3r!g+BOssze+quLER9U*F~iZ``<8eUOXgpR~E1vT@exytImpp~$x&mGlh4=tXc zUM4-R;3AI{`2+^mrX5SZP%YxtL3lQ$2}gqw0=KNgKP*;9BRHn>MfVli3b!^{46vuf5&Kc3 zFlKxR?M(qcQzqP>9->?AAN6~=(0;<1jQ@ACn1YmI&cy;D%L{c)44$_ZIP1|1%~F(& zy?RE-o?OjnGxzzIEME91ksN0=mhSdJHbR^6R~q0f4`VZZO$`Y-U!o7IKI=Z~QM5%k z5Y4GOS7@{x%xwR@pnLc(DI7E35Q3N;nO)} z>T|pB`L?_0JuJldNg)l(xJXg$o=%xsm6My?gF0d`ePx0|P+($Ili(=n$R0ZwwuYHL zI3h=m5_Oo%U@w2`mr*->eK>e5DfXUIQZAqV$qR=??wRqjz)|*1&#+7}xZ|1_rJmR! z8BEV9>9)6v;w2-SjicK`_J!Mhct1siMs-{%)gUt1l6_Lf0COG=SxL3)rA0e3hIHl| z>X0M4%&)6>3eoP;LzQ;qe(L_VEb0pVK<)LxBuA|1$_DyY^0E2sG;+Uh5-PAHU9)PD z9LqJ*t4;ZEa{HlDI;%00w~Wez2aegfqOp~!o$uo%i8@Y)@h;D4)YtxSJ;yiV0f6I^zfp2`8;CO_T@bh z(8(a8-nNhyiTbZ^#RCp}Q<^2^D$+(_l${Oyn+#6SM4zumQ?*R)WEP6|Z=W@)CwW&r z-n~x~Th7Q&;a;jn*EGLX8h$vD%Y0cGNkQ;Jn@I9yy)ngqPC7kqU)?>1hlTRNxX}pV3+^-d z5J``sAoAt4zOma^(yW4_3a79q^t6(*y6g}uulWO&B=?Pi@ZnSvp(t%0ENt`zKhjw7 z2N~81ScM0QOLv}vTGlA>?2*&rgosUvUy{SZd`Ko9z3dgGjSks9s0APKtu2JhgsN#M zt1ur;O96eFJG$OI)JLn9#LrUykLdFoA0 zUiQ3sqYg}UG!w<8UumQ{! z{v9obFjN2R-p2XlB)UL4$vL|?6{F=o#g6mb3$d~v)-<1Z1*jAYO0Qn_lS*p|I?kr0 zF2?XmC`OW~A5?@%Z)4`>Csv5Op^^m(oL>eyQgp}OZ>c_bu*ltH(M1lgT4u}BWuH#< zOt1!0J5y{v%>ucz5{bdHYK!dt_@PvkNVs4#@X|8XbzOdq;Br=`)~G^~n(Bz=miBg~ zKV0wwoD_)AE+s|Vhb~=;vl#u3uhYYY#fErP=dz zr@z_P|7NP2q+{k7FNKaQRJbIyB4QDWTBsO0%tBhh>N}VjoD6JA}hRPEun9U5;|V?kIhLi$~`yl7;Frf zK|ohji)x7U^|yR#rIoC6Q}TTQ9O>@Hlk|*D0>(UsHO;=6l#EmpAI3${$hsgzP97Wf ztB!Q5Fy7>%nFb2} zlV`v83Zwk;+$-m7`8QQN7@sDT`KPSqZ1=ww7tgJPvq%N*=NP7Z9jUmAO*?7p~aN_dmJfpJbLkRsV3sa#)*fGeS~8t{B4KxCy^C&}-j9 z)hpNagE>VJG1d&U7W3*XAk+?k!e@G-Li^!8av?^kfzJ!tK_-mJf?v-niRX2&Nq#h* zD$)qd?~~AwU=EUUfWEz+zve(9h#N=g-*vez4jAUXHxzt?At>vi$))ij*Gi^X)KB~B zDr?dbmoz1En}HmjJ%!A_KPX3iv=Zz2&Qj3)wZDic6rPpWW9?FFwn!|lo&s%GOPk(| zdo$*ji`AOQ=>tZ_(qe$6UcW9Y4ZgFKWiR7Xl>$3D>#0(XBPSY$Wj4g+!bk*01lWt=d2u3e>FHb(o+e59x zsY=pSZY3~~SuaS&_-YLc@okjT+l)}I!Gke}1!)a6aC^^@FTOPu@8-)CHjS`YCx1NQ zDysOm0ipm5Sa4a5T$8+(?vMKqjIfj1y#LlB&&kNry~w@3r~5}Mw!^!I(kTXJIq8CC zlHF|M9b_lg=N5*1=$$Zf9m>9|hY6gV_vLocIb zxMR@++yynnBcP&hoFz<`a*}-*vI`ecwkSF_wuv7isNhS11#U;i^=nL2?P;5&PGLiR z3Ht-IA}+Qd(hBn8B-rnx+xP6bcFqy_%sCzDqhCr(O0y>wsGyAUxN7h1s-4a_mc_=X zgb+f8@YNdNrdQpVkh$)phbtONk!W@HS0OKR>{^e+vT(z`hcW!BsEc9_!}-1r3YPhRwO|u0>&G63sD8Xn8^?U1>@w71&pYlj=b-k8v4l z@1)>MPAy9yT6_|od(^d`PfVh&g0jRaw@$3J$;`ZyJmPf+M=|IW8Qev$QUa8VKVvL^ z7{sXEV0fM2w5cLBs>_oOkhI{MSV&79qE8g74+qEfbFR;f9htu?Vp}CkP#-r!QrwC( z2!t-p_0Mmj^fuR_GgK9}5_Cx-!zzyYG5;|yH;I^N761j4=ciV9y$M4zp5mQ=7fvsR zbOTQ^hzd=`bb`zhD=9{Hp`(BV?uXv`^|in(;>O2?n@7*Vy0ipJ#8p+DHkgd*X;I~j zhWoxuVff8_7`U#~Hw;;9LTEEpGH?oG3dr0}RRbYR0gu<`f{A*^*_&ZMrYejqMyiK$ zKBJs0o!uhiK?#om((#B0C-f=wHJ>@qK&7;uY6tpTe>8_wd?HRw<8#5e({qGSkB zwuSG%nd1;Cf733E5P2YMgzGux#i;$W9EwlDIb$wBc}&a}>l)6adsB8JYiDMz7c_|V z0a*3EJ8DTJ_x1Q(D*H8uM=~cToHlJx9==(WxH-R8&ro}q8;1~^79uIxpF!FNVyRU- zaJRZWURCvtAToI2l#_+UHcHfVQ!7&|Qz18|Z&V;sLQGmfxY`%`?Q?W|y&AFt%v8P4 z&`Z@S$+LA-xp*}=bSf4KUR9sUB*WT~O_PryKUG#da)&V=nY57=s&HlTm#Q|V?h#bj z_sOo{f&1{j(FJ<_@VGBpN&X?61%qBc2Y;Ec<_s(~nthSkB?zZ33zy_%y2}6QFDWzX zQcHqw3ZBlcLbctmou2OPa+)$=YY^oD%)_xQ|9ovU`Z`FOLQtkMkYCtIbz^7laAkt@ z1wW_cWY|h?Ux(jk)n@++#|D%|0%U}A+KJUwyhy1gsW{;L3yafC?(Ssh3T<$l3G%l+ z+}JT05f|Ne(3nQWxl)nq%a+RsIPXF@STD^-<4j3+6E~Z5#z70sXtkPUhHL~EyrSv6 zMsD1p)p)ZJaWbAGae6eq4oRkrKBYx<1D7BoFrCN6aVJVBWH25RhF$uL{mmNM)km=- z&ZzO~8jjeSew%mOYQa90q(o`K-Hm7O{8skyyz&@t_w5!Vm+zk06a3Hrct<}n~{WfZpObgH6U*WgqBBn`g{>D#DyAJkEGu9l=<|Y zY9ZYrHl}oHdp)HQQCg(eORtt>L}>3m$wo(wn8l}DRB^zfEDZ~vORbhQePCy2A6u-? z|0(6F7fvSZTr4NdEHA5~T8MKV{B1Qy^Xt4ZCHZP7@b5(K)l$R)^bc~~Z;v!t68IyV zp{9e>^zc)>5Z3)AU{|zy_{4BkAyXxmxC|9HgQNn z)i-eZqAitXIXklitK{ssgmY5ydRSM>-|NT2`kbeg!Q$K?S^6Y3ngJV$SajeiY)Gz9 z`&dB9{7Ye z!Wg1*TqDFQ3(@Uw6M(O$C3?L*hDQ?uWW^}IdZ_0BXsBuMvurQ=b9 z1;Dw_N!E-Y{l+&O?S}B_yZoWc|L%-;hxFrhsL{OSjYy#Lc{`pEK;z+t2Y#J%1(bII zd4hVtf?LsX%X2TRlL3Wao58g04WQ!P02p|4_Y7DnQu_>F_fUT!0-j>J0fYm82apx_ zh_Cp_&UH#1rZ8+$igG+6rshsf>gp|9)jnhS?^EPXdbjOFx7*(hKE1nu@9O<_h8O$P z$8$dccSeA%Ex*_2dn6NpUu(?2^``2e7bwhrzcpxlH?Z_;&HUBT$2{(8Jy<1Ya+Iwz ziByVay;`TPbm=osL^a}`OZA7BH3UOJtcF<>jwPUPG}iM-(IIyjf@LbD&?_O{J>8~& zx%{~g8a9>PlQqJR=$W#~pN&Y=cm{|m?Tl$;2nM00XwelUNHJ#Ofhr0_b$Fp>r zs<{#jB%a6BfYvTc_Jr;(-uGV&q_s%W@tg|7CrsieQOJ?ChOyMTnQ2CZP5amE^w-|J z)Xo7{ORCx5oeA!DiN{H4NKq;Tc6*@?=tPqboT#v=4A%op!+J|%B!M8 zLUe6~L6nP9Ri(tqT9*>;(o|^FG}YA>vN<4K(5n)I^P@d6=&A5XhzIvOKv-QOEIEhi zYnl_LLw+Te%+m`W*MZ%j;;KcyNnbdlkPW_yz084?B{NpWV0A$%O00q=$^KE>FIKG) zX*x;T2o2q@Uz+Z^^!QcOa?IKvZ#6dCe@(tjYf<)S7G;*}UxAOh+y|?V)rjXr2Q8!d z8D&48RKXxY8=AH>>_+anjLnPI`xuBT0F4^xnxf~%cU&p;?zsd-)Z!+^CV~^Qbm_u7 zg-ymQyyxAm4W)f8KZFB1Ea$}bZkmr+zcU?e$kyfYcmU}3xP2}Y?q$L$wh`)EydE%^ zgwXH`CQU+)tw)gC=IjGx%L?v%qz7tzu+z-Yi<#4V$b8>a4$OaGo`jSTlot$V1R(*l z61eZlEfE_+60tBOfbrAu+MX4@4KWbR?k-=N;K&e5a4p$NDdz zsw-S=z4>d~>0_%qhZg$mV&cXdyy!fYb)sA&UsvtY4n-M`mBrR*6fzaThs+F0;xtNS zo3q};C|E9fH~bqLpB}9zC=Cz9T>I2Ca6o%AV**mmpN(M_WhbPjn_)6mLB|_GTXqE@ znUZ}4Y;aPP$d60w6Nc9=`?XBL--}Gay96sA2hkW71~+C{d!)60QEH`}rA+;pDp1w& zwuPdw*JDah8j&j*q(%PRB(dq_L})!g#~2GEHXk1I;p^FW?)79JE+!L@0^3B)Ol!d& z9U8@HR;T{{tXkxCZ?7Q*>N9N;x1IFa=U?Z%!et8yCf0X$_>~we=l*NxAE^jt%LK!W zgBR74#sFr*JW`Rm4sXU1cN!A&YQW+q6ioK#GtK+%aoqA70KMNJ5o{HkHz`eGt`IWF z2{}GA;OWqMv0SzIi~U!FIhOjJKVL;Fj&k)kXJvlTys1rh-HA-Ubk0hbpS^sW5O!I+ zH~@xxeg)E<*{}|l8RN8#Bc3)^lG*NL9|BoMt1NUtLO0o4pZ| zZTy^rRT#+e+E(&ECj`@e7}Dx;wBAQ$sK2UCQv1#p`D0~Dbi%>O7g#-{nkhWNQO13? z_3_}9i8#+{Cztx^*deN&4pBO)V4!XPjK^TB)Ia@+6fN5_{{(5S^K@lax{eL~EcM|! zRN{cfGv-?hY`f#;mA;o4?RfV}Yw4>3e|r9XK1ZarY5|KA-AafF58@sXncV&a**Y)?p*I}q>w0h3vx#A z3-S!an(%q5`K=Z&#`hdkSFPT<<@Ar2-3pwwYBVBz-JY<X? zuVOW^GLspKvy^i!7WbWPT8MZjS?+TN`+%x-KWohl+fBOL$*9x?Mo(~+e$2gwRe-$Q z{B1%vfD<=u`JslmK&CS*Qmb^LsbNls8jZf&K0?8_nTkQt@|ZRRt<~wMrf?O;H@kG- zE`L|;BDpQCd$mjngXnaReh#m*_Q~IS)m<0lIc^dE7&3axE?Ylsf(EY4#|ssoccdR^ zIkweZD{_$b1W>r=*h%9I2<|ccsJUQ93>`)_zpxfa@vY$GCjJAS#@MN;9{#R}f7{_T z_9m@xP_sS6$hF;ElQQ|UY{B48MvKVLku^@9XG@DDs@!JUbYouQq>U58cEM~^D`-qk zuJ*L}4pXf1BPeBOJZMfnz#k0rN->DdAbY5-{~++vEvlko|9wRnOG?ly~$vThfT3M8gWA#h%>WBj%k$IMl5{;WJ2cgw& zQ9ocL6U3Pr|6s#Qc?(5&&`*wOa_S1Zw-{&{m$8sjBTFb$G$4)M2y;6!DnAUlr|jc6aj4j5Jt@9m2pMXFH6dnB*H9T6q<1;biZEmHnv>c0af4x5 zb@g`DD(YR1*)0y035QDABQ4&gw74FsytQ6AQj8@SX|5dLFS4j0no5`MyGd#%{1a>vM8r1u%*y*xH8Q1nn zYp>sb=%@8zzb42urp&*l-l5~SOvpZhsX256&xSklS$?ezVGfvgD+AwnQ_9(U`jHix z-ZThNmIC9p0b|reT(+%N1y8ubB6ZE(euM4Ty^dHMaH<&N1GWIY6n8Id zVQIXxVmi8-bkJwc&9=`EAk8k8#@0@7%($@7hyjUo9$p_|IZ<5cHfad>2|rSg&E9Iw zjqPZMWX8%;sUN^I3gIn}QN*6s33*;oGnR2xxMZCo6*DgDw6_v%)>vixPCqDa?hXwz zXB%lW{J4rD$*b$@ikFprzu4fUk(~#6T)gX;Et>xoApWo#viJddG=!Fv%N)<)Rw+ZaX}>z?3^Q%WU-JmgKaibEkR9=QNA0(C&_;?@x7nay zZP_2Ywuby3k5;Tgt#xPhy2Mol@)!;ZK}S|>9k8gh?HtcVbq7tUWE7{`DfJH%_hDim%%Rr)$!#*!EVVC~avAWz! z(!19^SX;MejrHDt-c5dEJqvGXCYo$e+?ou*JbM%09)wP6ek$c-MBL_qL97}@Nr5=6 z(q}wqnKCm28w%GTs_ewUqk|kqn?{@AcOkko*=2cdZzuKQTBJm1EFBy6I^?iJh{<0U zpdMy!d07f?&hUE;5I=psK1xtWYRz;-d17z%U^AxL0lqHhp!l4fh(wN9eA30)?w(iZ&NHKefDY& zYEhqAma93K>7nvWdvW8Okj6AzS=@W_NfL(FcG}1?{)tLgr+WQXq}kj?Vw<+|i9g8h zghzNm_rMA)d9rV9aJb6}i@sP_L*^-e*eG(gsE+qP}nwr$(CdD=W}+qP}!l*9cIH}J!{e-?4r{;drGgtRYYs!{`Mb<6Wc7kT6j{7@u`Z9K4pZBXUq` z<`lVT4<4I)Azm9azu)7L;qH>8+8T;EL>|T3No20li5y)@1bT{)sAa6tc7#FHtf~z2 z4W@%Bif^RNFU(;-*d}m$S>_{Ml{d>g{;#vona*&T>n=<@A;EjiA*+$eczUgCaH0yl z1>6}Y@hkI2xSTOAmkr6kXN$mfRS7Ha_;sAvsr~@B*bMNhF+E_q^4{S@j^M(kD6x1H zj2{v;*-XSJ0qAkA_bdO%(KD4mtc*AhV(0~EQ)TEs@j0SvN3I_c=z-kBJx3%$l#w|i z<7p)rH5)@Ko?PWj1pnGBGs#$p7a7&nA`xb!EL0%R*&%=f12uFoCubu_C%E$2YkQ_p zyQ77YX4hR!I&3Tl>CQ5EhpuU1Mr-!Ku`!$y?j8Dix9o zDf$1jv`WLiA*s{a8DP+#)A1wO4Wjit?Oz+Fr&nQUv_j6nvK-s^BTSVVoc!6G6Ee6+ zcmWOdkp&WdY*O-}77d-Q#EDO5mFz~DM0Fd|-({eq3T*LWLRHuh^yhFrib zmt!F+XLUyO*&70uvFkC&49}PYI_|F0;u3t|^qA#1B*F&B@yRD+O3tnUABrJ9G1P~Q znU-=*|EZRVcd3q5Dy^HZZNu1=0wyl>ijW=OuE9AJy;Zbc+PCh@hBM&l% z!=VwSVCWDT55^hsWgxDD(-6{s>uQZ$Zk17c0E;_pfT!$()q0;$0w=Q8Jph~{*9o%1 zjeU(?f6M`*vd0T|oJK5%c>At84PK<&okuyz6NEVC)mDL&6fo__yC5*U7v>_fYYn-d zecpp@tD1@aVh6!s6w@(^O_pgr?BMm>*I?a8a^^=wbP1Jun`gjl>b6$2cvOU#dv{>*-4IX!~&3g7W)z|u- z@rp9L^qP*OEp=|M_cmQn_jdNvI|;WZ8iZ=PO8KfQm2DVi1j+)*-Ig|b~(|r z$33%VSnatnOXp=sK{>6YKnxZ`1`up7aQMT-0Qj1))3w9e86HDta9e}c%AC(@>8jkDmWX%7{C!De5^q-NqP`y}*R-x9x z1P*|TYxt$ijOKXj( zC7R~zKzag00iFU;wMsK1NU$YKgzZ0*Yo_O=0Bv&1mZoXN#gp_z^n|=8>N_W%C^u5( z2Y8hhARc8!t1|_dKWW|SQz|z5luWmL%04odcwiUJG^u87CU!wY!@rH^ z-SfVuR$r>uyN*_HNv1H?2lLeWU8{JKmKoY;qgTKx<1OW)lBzkYRvs<|Jd^zJp^uUl z#VWJc1p_J%8sr74Y_1WjYu3)ZBn8nIt&ek=lPTW4*4u0RfEMDn>_ryhUAQvbn!|gt zFma`&{}t1~gUKT;&`(RApiZfXV#Z=?gC-Qj;AO1Bce*f(YG)>Fk(XO9Xw7dV*admE z6Th`icdu;3?TU8Jr)9dN5Kdc33(Ot&(GZ6Zq){IHQ=NFi8k$JwZ*XsHN#wy2`V$yLSJn(~*omjfCPG_)@)vVLZdb9K@v~+Tw`+T;V@UwF zHuO%)L5L3iVo9ybH4oHrE{HO~6xB1D5n;FoM6b?nEry+?C4u+VY>M&NYF&k?E$;pY&aLnHjdhB0BV*u4b5RiqT z5g?YWuS{kU-du)gDT@CZ>LxxodGR+=oI3?7Z>Ah6lje11(j5XdECiDm`hF%aje*?# z4dx{fqwLMj)xx-xAIZE$Qe{>)0*%b(>MpNtFkF`t5k_acJj9DMOwj8f)JPCdNKb#G z|6f3X)iU|=7q~5S4bO3@{buRyKP)-J70VYWZJeIXXUGRMv0{$Tg=;q=SVYyQN|_t7(FHq$KMh(waouEM8Ds{2U zGigqR00l3HHgo6JmR z>SVf9`&gP(ov9+w#uNT13MVEG&O9zEnHzO6IgToq?{H_WXvl zz0XR{zuCrqrz#FPZt1adyzxu>@To8SdliS=*?qIwF%{gZNNX0Dqxq@b$eseZ;4hI_ zSS!RSCh;ATta&dso$%GOOW-J`foRcgrCMI$`YW8sm=RN&3Wql3kae7}G!56J)#4On*<>qKlRB!-Hlex*YL+&+kXdZ)&`k9dYg1C;R)4 z>gtoYoZntOU*W6zoOT4c27*`Rl#<4Zmvg@#G5lf^8wy?v;d4RkMQNryJF0BUMj7*U z5^TGkGh7xb>*tbf;lh)++$i%4`M4Y&&-c^2 z+#vH-Mu45S?_T)NpSwbGx*z}N{kLCV*@!dvCq8NhMQ;{NB1@Lu_7jB9&VTEK`>&tF zwJ33Iyq_JU&!2f)m_GNOAAAsOc=o;>fX8kFKJK+w|J&*HU<3ASJ+tw%H5!l4)4Ro8 z`!Y2D8AcM?+ zWwCOqB2dVKV$xFxu;t>DMaQ82ll5155h1~S|8NnnXg3@MsnXO5!mMrR0!%gxJcbr~ zdpkWHoj-_dY%-0D)Ac@#J3ig5ALm#7m9X;$H1``OI4AA*HUgW}1OI|4`W#&X|8A9H z8a9Tb>6nxay9M*`rbE(lp{a;L=8fXanlBraFAGx19DvGP5GM5n8{Fife!8Cg4r+_f zo|nCquN^*+-kUD}-iPPG?aE+-AK$vppXa0Pu>kf(@)!#u8CcqBnr_u?O4l+hSdfA=G>?nzN5e){^?X}^oE#0eplY`~=PeAD4RfM^|!lNqL8c)Mz(hMr*^GK*tXjRp(I&|7!m@ zHEU zTQ_T!8d#Lx17f_*`BcE#)&)z4|J98976PF3oDJ8v_7B{hmDUmdW;uOXDT1ATREc-L z;J_+;B}tDz!8OuMXvRZph^~^GDZEUeap_}uDvta@Cd!Ffl<4>WXpuQ|V5H-UiHi`R z4oU=xaJt;cBy3Tqv*!yt}^(o&rdP4nL@CJ^E@oUA*Jz-#nABOp)8m zdV3lSbI*+9=1&j?sLCV(En~BMTx>tOg@Wnh6=p4M5L{^EPYTf5sFM{ET1ntPX?%0+ ziP4#pqkx_HtKWk}!5rI?XfL=uM!9fBh%PAy4-#a24=U)aJKbWSoezuIswcJUWf12X zgweH4g0SWRQBg!u^o5Y5Z)xhtp5xQMj?ec=5!-XMWZq+nam3F-i zkbOAAwLdaCcR~p{K+d#ZlGU;Yp2Ik4L6(E(yy9^;9;1<(c_f9EWOmfb`B9n-OoixN z?yD-P@K~q2dNQ1KCA&0mc!d!Q$kH|zC9jbG1WKkk3CN&nm9!%mYqHy;G{L>|k^hv2X2~nh2j_@sl2E7wGG-P2}k~t}0m=1l! zs6l|9e2dK}$TUg2mOWFaTbRmW0RNTlXux#5L4kN)Y=xr= zgv_TRh;@lbm~GB<&wx>Q7<2naS5Rs@MwM?QmP$2fX(r(DD+cGl!9gA>(spzNgBF8s zH6{=`ULra>GW1sH6*dc5vuoC?oe30AS zUdR%y`v{j_Xu`%L)7sQb94FOB4RG=i66j6RB%BbY^`mQ*y6FaURXUfs)VZ8T3;U|2 z4NmW?<;Eow{PR+!au1lvcJW*Ek1exhR-+0s0lO5RQ|pRa?$)vzq-|{_An3~)&Qf8F ziDfR~<)2?PBi_m!o z#11zU(`a2;lfa~O9=KFub6}feMuq8_W0t`(KnIb-9#&MERa7Top7cWJ*$-lvx!1{# z4y`_km8c#NeCsXjtKXL{mAC_8Zjdc>WD|EOXa~*RJJBLP}XWL__Xt06{THq}PV{_IdR7&dS zDaBqUbm;NGUNV?qKn3Fxg^#ND%w06yL1-?J$%8)xzki_06| zXjie95&fCV=NE?NdGW6Sdj(`VMhQAb6)bo57Bi14@CxsOaq$Dv0t~?ALwiRdwvqr2 zcr1!2;KM#x=0*)om^;i+&vqwBMf)X2{U3kDBu;stxIS##V_HTFb3Z)seatR%*r4<8 zsbfd#otxnT4f^lu506yHY|lB^!bVQSAgg+5_UVz=n3LTW_K)6E7~=RCmyw+V5ifmI zI{7P5CyaO5W-T47a?|tXHD%#Yfs&sh*-GC=E3AI`>wiw#f^h7u{H1Rpi$f( zZedD2BIdWW;$E_Mh>0QHXUc`oLB-1~S4)JKDHGRexAfXNl*?%%c{L)7HrdA9#GIip zM@sHA+S@81PSdJ$dGKjadW7vtR3QMukYLPbVmJ!SMM{%t$_i)lC))kL&7!UJ#UO^s-fmGKVS3)v;J8 zhR-6ju}CXc;;8dO4>7&knI7%OkMmcD3-IF)(1!MGbOZBjMXqE36ltf)`%GU^_n4&zf6(i8gyb*Lul4CTn2xf{r_R)G8Yyf<`~z zy0-s)Nl7mciaJzT6eB|x8yQ+nky(BGMN#OWt@~z0L*3Zy#0YqB1_s~%)~qeUYm+$@ zwn)$#7$)0z`pB~mw|x!X`SIiNv~3kwlVin0dN*gDF^VE5>K;6R6PGaxEb2Dc>%?O}EG1-j5Bh)*k=n@2C1J z{6tpIfL|N<)b-<$RT(qdFEb6=smMdWs*to@T=;oat3SZ8#dzUq*bZ?JnzhzqXO(D|EK?nnNQ=c_;U=Zd!1wZIRs zSl7bW^|$E?J}Oc+6fx5yE{rs|Agc9U-TvvY z|Iw7aG|`EwV!K{luTmQS&5=*Zt@^n>iZxm63?W4Y;&c8}irlA3w6(t2;e6CJ3Z^Es ziTmN~xi+g{ycDoKs4?EYqtjV1w-8+`7(yIf(BacQcnzkN#|{hU;}6xhhCm$qq|+Jk z&~Ak8SH)}~e2t)--oMSwt}dqQEVREeAIneom(M%9z4S+_2I#@cvCHA<*Hhu63M86q zxH^RysuT28{ormoO!i>Q_T;k^*cEeLvR0iIj0&JpAM#m>PfwE4)tkLOjw`q7GBt|9 zho@yTSOxR1HGp`9cP)Py6av#v=1J0L7|&|0a%T1m6PH~mhx9w}B?^ z?3n_S!}2ST&)cBxhAkMZmOeFR3LY_)Rv{)l^T*vv(y1hYb#=;wY3=FU>$j0QMr=|8 z{kSG4B3gqhO&yb7CVkzWh|bPc2mS!Z9hrpf?>tLhbh~iiqe{*%rM#}+ANaat5SL={ zKisjPV%Kz(C;7SsqD>&JioDe~#F$Z$xg%6I4)3%&R@q+J!kZ#WFHOa-%SD=QX&V%} zaE*`^R;?_JSG!Jny(8B-=jC<9qpeD8___5v{jAz0x;&pE6ZPtZyHNHMPX=G;qS^0u zhdCqF`_dje=hn&If>2_V`l4xik~SJmQxT2cLDpH{trx@S1icXflqE=3K8{pvlRz_K zn&EXfO=Hj~y`=E27QAEQ*^&pgMz2XSr0BrK@gQ7;aUdw+Pb=(Ym@fY9@y5h+Wo6zs zYqy?JN>4A7MDiP!RTch<{HUl}^pCDyy4`F)+H$Qn_M2s2UDt;(<@%RIQPqH7Dld?N+8rxtqq} zfRnm!UpT{#IaCD>qYEfbH*k~=9#4B*r-!yl9h$I~a>#mPKLq!(Am$RwE7_}Bs|hg~ zBCNSDv>+y-@omwT07I)R7_1Eo$BWb;#;+Ia*&LMo*BTs%EE0NGeE^veGKHLM;8+Ae z-uth$lVKCBmV1cx4}n=Gc27nzejUI9No-NX zD%V$d4UdK@$iG()1V}ShxwP&)G%I@R_$Ux_2m0($^mdyf0^s66E zQxzXS&$6gJ(kzO$`<+A7+NPQ*OW>5-KVvdGIcIYZv11}_aajjDsz?;y(oD=sP`bn- zGCB7_U#S(UF~VA5I*9v^3;N<>ty56N>N{bw_p#I4hNM#KRtxgeq zVj-b5KiQ(cEbP78QK6lgv;Zmso(lKcNnB*^@-^*{K7LWNwws4y*b%@|PPuL}r7FR53hf#jd3!$Uh$HP+7a!PI%#jOG zr{gC7$z-qFd0F3VqqSffi3O}n9RMyL4FNjaRy_Ba-okjx`?_%mtUp2d6o8srU!`Yu z0=;Q=2X}I(t%n7J@yyqm!?|O=kbZk@e%$DHfk3K&oiWUB(+yz53Kovnm;_McZa?hT zhH~LQgBY1>;)-J3UaVOd$<)-nb`t%sKYYC zNjJX{O5+mSBkiqL@9+8AlAr^_VF|qqS{x!l4GHWfYkKJwV}8j-c1uHlKk(BNw8*MY@X?f^JrZZTklaD&I;Z&0M z)>>xXDCVW~VUSS?K!JWbaidE{e*KE$8*DLs*IfDDkYL!vfcR>;kgni5j{L3G(kKGR zYWp0Ah;(qSSO21TT$(aO<`Ek(Y(U$>V}NBCL2D&gY?1p@IT^gb*o8+{qiyNvR|)Ch z86(@QWyYR2PEQn5A$(rq^sP~})mZ{y4S%jrRuOuE22z}OJ4$ccHUmu2roBkZbV&gz zoAmTPE;QOwlLwW1rOlnK)|oc7@1)mtc@HS?dhlB}wrbVL&S~e;2o|8aUX+j;C-6!^ z;vFl)_=B3&x|D3^i4|6FO0A+YwJT8kr6yAlC)cOmv^ynAkBzFQtF_$xRG{&+k3xZUq9R<$(f1y^{3R<&389ro`@++BXdiAvP(#V?O*yq~l2MDn;? zuUC0(ZR*d`-}~%W`QQ2bwdSx`5*o8Pz-badIZZ-Qrml!cRDC{QJsj?+P=JwE zA;>^f04J=ImiDtie)PcvX6Ej{>?;u3c=PmNCeFnjh?+$bJXoM^JFd?_MM-JsHn2-C zKSTO6RY?gm?_Z>G+F7g`Vp-CD69oxlr@~apXX)@9Zm8iZ?9|SLk?hyh({!-xG|rt4 z%B7HCttsYoOgUqRGCw`E*rlI5U`Hj#nrhbN(!R;p85O)p%w?Hm$e|h@+`DYp7Tx+r zW^A9X$0OyJi}#yz=-MoI0cxiowV634R$;ME;4Lk_ak^w@lvZlZ*o#A7yBc5!XCP@o zXF$BX5e(aK-JA*&%RE5SIUFOchdz7+zgv5(2d)?8&|jN*DvvjoHx&5}0MNpHb<=01 zxH>gkMHrREupk083N~X&?7?&7jU57dzz5*zuQB(j0CQZt^Je=S5qii=xT7GFHCF}z zHySee+D-`2TauZm{Cmy>&1NkvryZ#g7l+$*WA>h#;XeLpQE7uf3>~FmByN%mqv@FW z%2cqlV%yj!xEWpx^0Xe+*pekxViH`-f`Y3Al%OASj{{>L%rdZ|Jb$?$_u6d`7icT- z%Bb#{=*(6%lTEHmh%nf@1@$>P#E!nNQ9Scnx9lEV6*aygKT0sw5HyG8@~SL8xAU~} zd-&Xi@{>fWq&tPf& zDjy^EKZdkmTdOEqlMY&;;0QwS;^S%S=(2RfhoYWbkm>77K+IaVPIPgJZM!aI{Q}qy z*ip7-c7&y{bzRl$MF5-v{WuApse2@2A7;$pv}cCbF)om)*U5MGtv==DphztKw8t(h6UX?OE{~e?HZeMQME7gT;a^z z6RZk{T36aYh*uwC5stSv%1AG!mABR$i_O3-n2!6Q^Q3HwwXu%m8cvfj_sc@v!M;lF zk9k}Y70ORV9a+PA=SdG8Y^GPd4+Fzv0eO9AT5o5<2kBCVcMcQ~N@!8{qrqT$#fXTW zOKlCPz<14wa^{UDS$^zJ%7$XC7?02Tm4&ULAgSgVFrAH${H`E zdV0m>Fzawu(n_o}Gpi$5AzGD?4Ph$vt9&->-vHE{b}(uR((DM018&^gi33)Cgc zLX9FmJl(&>L2f+z6~vtQ0&!oeBy`oTzeyG=M=2q9m*IQA8}!sx@4eY~8ueH5oBu#f z$I(MYWe!MCDrMgShhO~y0RoK%Us_LY{AIeHlZB5XzO1(b)|@Z&Yi8ViegDV;NC?{O zF`_;v4SFgJ&WMT=L7ad(8q!f4^6vB$L!`&q)6 zU5Q%P3C*ngK$`90QuUs&_ccfx3@KYO73W!+bww}b*eFE2gC3~f&@GcOIYl6b^r2cu11H*#ISE= zuumZLi{8{fHYcr^j{EJ z&LBW(e|mD{oCN)N##Hu@I6b30D{dTIZV<6B{^bQROW~}r)H3xWOA}#{%}*9LQ)4<3 zy4WWs3FWn!8N{-vmB)M zR#7Czp0cW^V2q+cuV5(NqIORC4o<5$t2%*5a~(ru&zGm60HkD*LYf&O#Jm1{-dp+Z zzy9u22ai!jh5m;Wo|cyKTzP)$v;;<$HWmMiuB9$K%!HpSTU(Ml5iRSvM8Wx!TX~<%MKLrB;sm%i|vC#FE zPTD~@VwW50C+4h1!3=d#2+|J_91CY;8~hjV89B^>HQE-g=$*m@bIVkJIDIp>qGaLn z14IfaC)pT;f~iA*YvRJ~tbeF9T`J7@?QLyVeZb=~B^ z7tt`u_r0>xy}~}p6DWKHiIYI?5HWg5*0_lQDl*($sTk9^4b;i@Zzk_`{3@Y zYb!}yrOwbx_;m8DV4{PCwV#Uw%V(Dg23x!}D&dk5stUNO_8rj+aoIbz*R}BHi}3;T zus^@|oeAoXFZL|%kU#M$zK%#uP~XjW`^W1|wfSrg|J^}vZtZ@r{ekAN|9_L=8@sQ) z0ysDO^wN@r`(n@)!GMk}>Y!zNV0G!>P11lRV6MN0J|JDHvS!uriaT+#27Tk3YaCm& zP2ak&1**v|`ny%2i8UUk>aZ*7k4~?w`CSVp3@sl3K1UpJ`nDD)a@^1e_RL7C;Vt&m zI?X6f-@6s%K=1wA9T=&U82Sqbmap{Q@{S&pUj5LGFNO7>P9r_V zS6q-P#{^aGuQ^Lz8De785ub~~gs|S!+o=1`YyH;y&hzZeH%;d&vdYG{C-==KjmXh2 z1_ND}n>!Ge{eyxVIIHFpDxF#Yfh*uKl=~&lk~50Ywa91r#fAt}VPIku$>N_a>YWlyu<))V z^Qu0tTcOgv&-D*p`+j;Ev7?AMIq3IEFB>JvW?9!@Xl0mE-IFaPS0$U4!&ttd+8yM_ z{mdjDF#3PY7We}~|u>Wz|g z&1`}I*8&IZDmzvf4axDO=SoN0iznSAv2i4^8?D6iuvZyin#JIPFKvEa)jj3Tdn^Y{ zuLSjfAbK?sYOrWsc@;F$+V#jH;ensjlJ$C$!O2U@ZD;-hbx?l@?wTw8H0xh44DOWU z!_kcHx0?mpC^p339Shf{e8?)O1p;JyoQ4~L)#r@N z#Uijn7!6ieLy4QXBxIZ&$J5S*L#|`#!+7AEg1{*eC z`2l|ZnfN(4&Q1Oq{heT6`~?Su7sQT;5&Nh3^CZv!z(4vI*n4deb6O$1+@7}bt4>L z0Df{$u+|$H=Q+%?|8u9o?aB!O6^BtDFqqwYjTTGKJ!;e{=I~Rq#Y<97Rf~RAYB&^O zHR`59s1gadEBpM#i&J5qnKThkgIlzl23RQT!|kJvD7{ktgiQ&r@YO=_(94|UhRWMD zV5e``THD7QSqkY98eFG0E~aMDM$Mx0M04qD(r+@hv`mhXpm$qL+G}aMD8H3wTBy)R zj}UDRfiV*D7vZB&J|VvodhHKdaJV$~eH@PAOo7gAdh~CJ5e%7S<>0W#`;9F)L*BU# zvvwP}s%JbCs1s#1adP^yWW6myLEw0`gDU#^95O40J1M)a8>E#~XY;j^_9)j>?Mgj6 zUzF7vKmgtb>8Qm{;lv{v6oFI&CNb@3x(Nic0_EnzZGN-f1@yoDY8534JM8^>=Eg&B zwE+K=>Vacn$;$F8w}u|%=jyTGT~jE|R6!7gNbCrEh7-I7)G2O5$UQ;WtX1isnwFxa zS2Tu`?=uUJ5>OF$V=i27x2aILK|oq$*bt+@qoQnOuraJaWby zJm8pz6fjNq5G)Y$k&;wW;%9Y|aTug$4qW)C0g-GEg?|AkBkGAdz?3sZ%xdk6e=Ar# zzybk(Zu+ap7<2nAQc8sp7{x+hGv*@)6$t0;H#Q9LK{SF;Bw3Q6?tF>OBye;;2;`vT zEOY%etRn|XFHP`l5UL?4fHR}}C!zAWtI&T2k?5DqDYqQ#w2tbGT49z*m8BiuJz0T5 zd&Qc{*X(1$(2P4_)9W~+;#Ri|0DV6W)It!HM5`I~#(3RE+JaB~Uj2DqzWDY2Q}G?N z1OLRm)Vk^Qc%quU;XCs5HlJMo`oMnMU%yvhemq+4f7)Wqr{e|4g`8wef;e!)$zzu$ z%x!HI+-HpVI9(9lE^4NFKpX0g!S~k17_#x>kjFsNqQwO<1))!^31}-3zT+S~MA_Gw z7W7M|MRqsNj`A86Xt@R4?RUy)tW>n|^`#dI)TBTpme`(AlaukRvqB2wR3H+@L5_SN zy$Qy9JfD7VZBl_d70EUifDZbaKtFc!Xe%&@>$CVMiP6Lsp|;GJw8eh`6-RJ8ak&Fj z%v$7s-<{ix{#7S_WBz#G8xP{z)NeOzIU5N-@zl@7nnp*T-u^kAsXsZk-5$r2zgvga z4bT5AV9dPz5ly#GiydVQlt`>S@gviV72mzkhAkxP4urnhWk+Npyfch7lYF@u&~5`V zy&61v9NCKCtkpeA5@t+`OmmrCv)@Jb!QLKHa&8C9-9O5XtR8)0K&v<}W&x|j^ox_5 z<8AO#t`z>aeOp@NF23X+{IgJOj@}LWyDiweoU*`I@;htrcsX90+#V zh-kg=B6bJCnON^HSE$OTH`nBnJZX1w1MYzvr6Os7DR26ttMc%4el_X-;cd^q`c_Z6 zV6@{~{0ay3*F}YZ7FZ%)slF9AM{A(y`LOrYzh6|PHw)(MKQrOV#z;8?)`AOB5f8) zRTY8B+tv1IDWUP*Js~#avcab{`d-F9r9@9`*s3$$xe)TLnSKX24r(!udRaww@;vdr zNxOra46uZJa*>|YxEcTUr-lt54YUMYy(~XVPSs1>h1vBFm&^FyRZb=kvp)%6!e^r8 ziw#Vc8iH#ONyND-7f8N6)6PSi%}V;%a`q(z5jD4}d(;bsdPMJe+FcjrWj3$zn0iXg zQQ~P_j^->Do0uP4}VaqiDq*14o7-a{EA$f;a43d4;BvFBDm6Euu>16NYGQ zMq%nFkp*OV%<(i2tfuK&%pCurX*F8yXVhr7Xbnx>B-8IilET}0oisXbtFJbFSumXo zt7zzVFi#ZQYZFH!2u%{?2SHv{8<@bb3Obl7fC3hc=B*q1mW7U$g$ab8jcj7iiywcK zMJYs&N|X{wj~+Y<4ID$=l~~AoLuV&}`)}<0Y+R`O&gXsGgV!dJb$pzEg>~ycyM^5H zF%WMB$t$Mh!NwI(YZ>7VSO2!LkG8^&6l$1VjW&3B^CZ`gVz_ky(Fy8(gfKTQ;#$j9N$T3MW$ghNCl+u7pjUto;BQk; z*-8IOWL;FZZ*!td%ekw_^0T%{zER9+{ZB;?BI{6OtJ9z%R4n=asugyCV(Nk_`v!{Z z%A97R5FeT;GR>eSJVqFh6cS{BPNd|+_>8mQ4Ck7(y)9N(mnMrR8P7cqAZD`~FrqmY zT+KXadf}DroBW}3yoD=T2Zsz6(bfznF+ zd#$b_@~*@KkFzU7XN@5pI|$O8g1e@c0d6<(3LkZ4VWVd)Q)%{H5-63{(LX6ie7tB# zbMv~B3VDoaWx+SLq_wn`he*!e^ne9}vMRc#$$15nD4j{xc~l3!W3+0OA|tem>#spi zGdgU>S*W4L&o^R_f74V{7#j51yaG&*CP%y$OKbzoq!#+nBzG}{YW61eTy!STG{dG) zI;vi0AG+QSX&#&?bJ6RZC_iYoFGRj@`7D!>8YHzMLj*k!6rU8Z1R|&?p-?sy8|xX^ zxXd8;Sk`*T0hrkq5J=b~34oolNwHap{2F3`&b`$F?>SiUrj}rg7)XSQoy9yb^|zfz z$}z$pnsW|tVM>wnMhG0Ob5}D@M8dWxHw8C1&%M>1jq|kuT2vUDJq_soRH=J)0Q}vR zzY(+}H6F!^r@^`xX3vVDmW$xPyaB*-j=WZRx}&*lOmTU(JcpKU{vBeu^sxtilWb z1-&3>5IPDmrf$W7Ebp_=+2F)Vg=wzD35SpKD!u|ThnTpFShP2~SBcMsk&G;0Y}wCAh;=ZJ{81mZ zOS2?vSaKU-BpZw2t$O{hA+TRd3j=EtPMamtY`(=! zlb0nr25PKf%g|+H{nUrpPj6kMLByt!$(0H8BCkV(#Z4U}DAA+Kkw-2JzqK{^toU?# z=-3jTgiN1LvSblMa1g}Y0o1BqEr1-r8swU4Z!sVk0+Vz?U*grt5CPQ6{yW@*?q zOkBw-KaD`+Q9&=Uf|xQ@sp*j1#apJLT38J`Z1_J8C&1g{m%}lhA00%bd3UNg-GIG& z0?T5`WJr0lSyWV-F*`AiVmPs^;9;1=k-KtLyoJmMid5Y?Sp#*h;)OVz?nJAdusQBt zDDn8{?`^ep_vsg{qF|jB)xs)HX?ciM&l?+1UQci;87XWqOejM8Y>m69J1TUkqxB~~ z#9+>bTT~10M&S~o4+l6FE>HRFLP*Y$!x~a~t6ZHlRxKx)kfuTT|94B3Q_>1C%#KSN7CU9p8dSk=ZZUFZ$g3BD;P%e`cna!~x zq>#EU9IW-MK0zOYtb+k+6tBJu<@R`$xBStWiWW2iJF{Ys?FY~z;tJnB)2ml0S7GrZ zpiCUbmUUf*Z!dmeKw`y(C6L1}+@o+=hR9mTxwQGigi-UFeYI-}!{DUkfGq3@h!xZY z@?Q(e;lhsI@fpZT33IW_Gq^3!)3~CzFXf6vLglatx+=Nf93Af+Xg4s*vNIFS=`sTp z77nadQLB@sXnRf7wUu%Il`5TOnYlVRfMj8=j2fuF*&T*y0Ft+`0RSOxbLwr!3#JPK z26t%k{F5cInO)jQ-Ccpes3`|eKSeX*=L-*}A55rueSC~SOk2PyCF7%9KHaB4=I4B#6~xIwK=uJGDvw>lVOgAM4Kj^|^SOLV%t^J!?4TJ$Og zCoV7fanb*0)2jWoY3+)&!T+yK>ullwY+9%PysXH?;P(ms*QSM9@oUpEU1FOk`?YC> z)znyh+S2m%izNJ=VB6Ix_r@q?8T!wr#kt+0sBC;@e$Xf>|Bd=<)2jT-i2R>T3pVf9 zrq$sq?@NIho_gAyipmFFk!;p^Cr)d~t(GP=)=vt{n7kVtwQ7U`ps4H4J3ycf{Df{q z0&C>9Yw`;H3E3Xd>%AD4HIck$Zu;8JJSa~Y_TFO4ujh|usr-4)(XX2`i7A>d@o{5$8d}W*d*N7GZsaa#j*2q4t+- z%`ngVWhHj~>vYjx*Fw|uysxk(?f1wODYyRzW)jT;o|PA-_uq=8ysMA9dsHaQY6cg8?tu=-g`ir$2MwjNFT z%d6k-*z&lO{8S?eZY7?~9Q9U@YR~4p-R~@t|IZ(0@@MO>CQIhqI^~CQ`i2czg&jkz z-7Y4r8FCwD$IOo+TVs4AHPY!M^P7XS=YdCYMlj+^eiu97!J|HIbuot*+fPzPQ(-wU;t+KcQc2j&4ggDg&6H(;$wo?3b6X%;P@ltqbE8PmNolb$+PgNmFbG~P zv|MDgdn};#5&*jt(oUqQR>eB%G0J-qyIHEdG6Y?)6%o`i%sn`TClJs5B z5yP6#0E>RIc4)#;;ksPUtvdoK+g4o=s-=PIkQd2Vg*mya43udeav4sNnpTu9Iy0_A zHMEpEoa5~hQdMm|MJUbcm@A3<8b%kgi7Q}M9|U3`YpTvmj~tc6*N3X?aNtVag(-!R zwr1|^nf)m=-upTkdqObXTQmMOBL)nWc`O)!47z{m$UjCUjSJjJ{UH_vwg&Gl5n!i> zFOuX!eBfus)P_MBc z*stS(R-|x5#3Tzlv;U8_dy0~^+tvl0wr$O{ZQHhO+qP}Yw5^%8Z98+OZCCzlt-a6L zRi`fMqOL~7cNx*5#TdPh{=BAnG5#d_0y#E;YAqey$vV)LY(xdW7b*kkcG)wMUoORI zr%Vf1V~z%T2aHNFM|+1Dgyg;{h+P^^o7VYy-kI#{^5DMNxZm=D{RCh0z9J6RUNO6W z2cYlFk-awKSe?33_)>*_<;iOt9~bb2CLM4LZgRlF%oMKOOzOI|`%fZ+h_nN$?7&V| z1pJPlnSWi3Mnn+`$BGX=Yl5PtPacb?Xl#j(-!C~Z$9Vs0tWFHsfYnqvUw_Kcae775 za*HYt+QPt1p?Fkv%xOtpCO9+e&`4ct%9cWfEaeUnhegQ}O5xPacw4l*LQjcr`gZ)D zn%>^1rOEP7*jp6Q(lG(}Fl7W_<;_NysxZ}b@~p|}m&TIMg{_1Arg+J`_%@jM9o@je zRvhxO+LuW7>Vf`bp>^{sXd$H#sok$I-EU+2O@7NJVUSA?0%!YcAdG;b`SYV<@papX}5i zLA;16DcUuj-r!rav1)BZ@GI4E-oQl)zO%Ff$`TW&F^kjxz4oSbRyh&#j`Z3&8*4*Z zFV@d){!)8}0I_>JD7^{G>N9^50qgJ!szSgC;XVp~`>Yfsj& zY}bxdxo2%mefW!B(VEVK`Y!a%n#t2G1ua*&5=S*vx}cPwVA$d2q}q2r=p|xA#p-#hSo`v46Us2`dYoz;yD)1HgCz*E7X82pxiX=l7@y22 ze6qQ%@}2}T1DcjMOngbRP|fWj(P2->)a2sgf`}l?h_P6uUclO3Nd=4yL(t! z<;)yWWFXfho&Qg=mNVfWq2m94WvyP!>&&8z>5d}`9UneUF5JTQ_|{8rx|qtq2I+Bo zsS)F=;Z8lytYm|GdPSFv>w}@-X$kS?4w187lueGvmgZLbL$KzxEwJM9i@m4O(NHyv z;nkL|X4|2SIFm=XVDhwxt$s%(56ET-6bAt$>@B&iKqlA-KC)NpYtL8M1ZgPUT6D-y z$}8_eSK8NAljLRPOtT-tbeUz7XvyKT zgP8mW91|Z;`I3>{A@J9$*9XEnR7rOt``-&j9i>{wWqHY5R>OHeXwO@1KXXFFq^leq zo-m#ryhN~KL7n0`B2h`8N;!(?5peRiDvpHh3F(r;*HNksDvK<15`Z}-WvyTXHiUym zvOsKHqRY`1`{26w)3uRpy=YzOE+``FF!;NG?T0Y*r+|CfT)$m{>g~1yD=A&4SaWn{ zV7&}tEaw6MRk=^VAcCkm2(sww91#5^WRC+=0=>?n(Y3Xox$>wI%vD&Dy70z`rkguE zE-(=X#L!H%`7X_x&f<&Jt8na}ov8PHJl6mNx^$st~xx^I@u6 zI{_O$LaPi6T3l+y4QNyqI}TwdS#`oEOuxBUWF~}`lZMUJbyqq9gJ~}pWr}?wRH6N_X{nBzW}9fy0lZ6z!;MgtG8bmYT(|vIgFm4kz7;pBy{+qcWipEaGEfc<|_J4(V6(X z42`jK9=V%^kQX40r8&sy(>2nj#KDaCWJcLnq~)#-$5;v}L{NFI^k+0`prOFh zBW4q7{T5>vRx>Ne%l^G*LvMrFfw(*ZlmT3MXlZE@xD>7pG z?-YCF_9_T?ROy32C;jHk09pAxP#!y>|0k>!0quYi;J}u)wj?q_<7AlyaZ2~0hz$yT zlZ4rBC1cwp>5B3_E?2K`X0U=dGzpFN7nXKpRU)f3f~X7IAy#HYK_7bUc&$OD5(~+c z*lwid29nSvC~uh;huGN#htV~I2cKg}U{{CvWm8>tZ4QCFYOLdS`JdTC{Udaf7jLdl zafaAy*o84jO-j+eQewuRr^03XWo5spwd9(4`z-TfG_tjPfXf>KSSO}b0ue!OU!7gc zX@7gz%x2`A8wiAKjTY;TXMBdpf}IU+{&d}9Bmi%~l|^DU_;Uj26JOu1?Z(8LLwvrcV}$qN}hy+9%KX|HCK-sQCd z8Vj$iwRKVwkJmK3I=g3*%xPNJ%Wm&+r7Zm&nB3{8Ix(f)uJ>o!`!W~?b2JfD-y+`F zqJfvGW1#uh7Yu^Qn6>ws$p-VwzJ%9FvB72qQ*@0uTV!VyvlQ$wvWB%7NuNT3!+G0; z{IU-%iV0&P)tFh7-JHf_c2u|FJvv`cWkmlSLBHtpqZy`R^5IqdSUrgUdM4ZaBJdHVqCg0D39z=Z7})tlH?>2^y3H9LGD@}X#RS`qxVzKdF(S3fx)O6F>p&@HnT1c?a6Ae2$(;wV8iW#r2O zrQknF>~ur8KrY`%Smu)?PJ&z@&3Vm{F7Qk;Nc9~3Bxi=Q*5@sv_N_VOOyK~R z2L(q0*BBhCec~W=OLat?+z3(s;K7{~VMejUHO<77w+@k`H9kP}O9_uj4%fdWJipHd z9?+RodGUsNitzm0J5|tB{A7Z}3S@;g!dvrB6fY9hV#H%c#P6WeOseD-Z#6e6s2?_V zlhHw54xcV=vjDPS+4CoiK{vb6ypKH=8l^X0+U!PTM&3;Rw)EkJ!%fN6q z&*7S{O=Gc(Le1luKz4Bdl7K3yGCY7ZqZ&1x-K^#NP z4xu6|H~?yvM#E4 zHV*((6L&JigaxxVh68JITIALjdBU=n_@v1l#KbAqX{s*jeIcv2T#r@Wd5v0bBhCLWpuTi5`Sf=}FBAaaAnxGVTFW3B9Fpv2b;Z(VU0bQHGWI;`=#0;!hKwihGp znwC${_E)X*>#z*^Ov}5}HE+EP8u%BDcW#@?t5TX@7R2er*&g66Q{y+&C z{Ahnxk#5Ny6!Kp>dwuj2el5P?G@sKerPczi2T!SLW24HAWSn=0EnI+uHMmjpt7f#a ztHg=OM*f?_e_3S%gmCha)1!v0Qp%2QqI^C82%A4vnJ>FBZByg#f2^`x=w`vOeL?*s z%hZ_zd=z;ntXLdca=w{;iCi4A1L1IJM-70DJh{IdI2ay8o`>2+sOr6%F=rXpTjpCt zmNhI!zPL}!Jax^R<_sb0t?G)+e}f|xb~OSV9)DU(yUEPx>KP+3ZDqdT0Ya`avYV4u zIBwtjJT%SJ^t2o1pX7-9x$*1TYT1cFbdzC%#>R{6wWrounU5pZl~uJxQPl;H+t;{% z&1oqMnOqpOt|s*YL2bf}I8lEfL0%_#nNsnrSJ&4Kj2Z0YIqUS-=0K&2sPr)Hv8<~t zxizcYm2w{`Xe^N}Sv5#gm{kxHsz96_z9>g-A$CW@f%3i(LDDOtV<>Ave#eJ? zBukr04cv~UA$xxdhb+cC>evgvW^AaO8^<=0@go-UHDhL_kJ|uoRDB9&k58>>`&a~o zKaaJumx{8p4%4|s2)<1!e|jxchK(5=fb7eeKlb?->*&0`J|*av6=s|h$~+O{%5@6| zCQE@~YL1=gO(%Yd9akpwFvL8t%j${ak1}~qdCY%LEoc-u*d!wEfIU~wFZ+M(F!8?A zNkWq}wEF4jPv>DUVj4S@IMAEVc_;hth1jLPhB{6CErKc+7*0wnZDFUn#ND_>297{(qs zaDH*{;!4+z%#~fnxeDQkxRYSa8D?Tf2w6YgMu<291EZaV+*_RdIr(EO3emTVVcK&j zP&=LoE&*!G$JQ?)KNm=l$2gaZav%oXI}_W~n8Rlj_lacsID>w|l7pF}R4md@@pEqe z^hg3Va?i*?XSK|`xSkztxwsSWrXP`n)kf_CPZlB(z}ztR%R~4WI9|T z()a2@`%oMAr1^H&_qrv0!%*r)Ry13uF%Fi{B|r|2`5Qg@c%s*Gr8g9cU%75VGx-Tb zj(2t}o3as#wb$a3wMlQcZAhjt_84FpzzqoyA@$`$J8dnltO-`Ygt55Di(w9c<2FBL zvR3$-o7fk+$jGRb+18*fdaXAl$$v=y0t&43Aqf@)njc70r2m%_a$U0%anv7!Fw#lI zuU_opdd&F2=+jGo#sUZmLQJC{*KEr+?s-b;iMvTyT5N3%PItI%R_F*eGX2Lit4XpK&`}m8ON*Yh z&aR4on$eIVUI4L4HXWtW@u5JsO@N!Etsu_$twT8m;R)_;mAXLFV+&h2Gf-c0y)69~ zq%^0ZYP#CK?{Y`lvH>k|TS-HjZCEkck!R+{R*Li8oZJ(Jp!jm+)``SZU|+T^h@={1 z%d1E#_=H~VArF43x#x^gQujB9w8Hq^Q`ZjPElvfHSZ;*WgIt_UneM$D_ib6_lm%x_ zkUPU!roUClP7;i6U#gRF)ii-Q0QL7UkAg?Nm1lu&ho@Y6miH|R+xZBElUb*ay!C*1KxjG1l0M0?WAJPnI2~|_1nKLFxTjf#bdGC%rKfi6ycQa%^_~CWg#(o`y2`GeO`dm-%|wJfYrwW z%<4l$)afRh&cKObQ&0W_fiRjs<^Eq{W5N~;t6=)Ng$jEaWx^=2@kkjrx$;f9I%ti` znTc=r)C|iZuP$PaGv*L0COC*3>mr84!zmc__q$JbFGw`D*>)kMMZusW!Dm-OsUu~; zL;Coxk@E8%gO=DO4B6b_iQH0g$7D4Z7Rmo4%H+cEfekdOmz~+OhaWjYrSr)Wc77BF zz2?Wu;qAM!koT2yW(_g&zyGwXoKF%mI3e9PJeXAsQ^=?RpoYgVw4=yw%i`()^yknP z*TV<`a5d1KH2Y|Y=u-@~3Kg9i+hxfL&=#F5132Hz^7W>JKj2m>YX_DC&~^(UIN)n& z6P_`E6~Z+MwyU*%@(8e;=J33cqd?p=&}xN7f~d#%1hZxX9m-ji88iA_tZk>@Qi%{E z`Qa0+b+-k~{u0s@&- zN*)Mtt>hPp0eN2}>saj>1u%DBEVbSXyMmTk^rcF< zp%sChy+O+oq;q0-J)xfE9Mr&x`1L5(s8pDM^9+#cHV3aGOid!swtf~RdlTeTS_Ipm z5$Q4U-hk$y_`u-R`qR6Lp|WAFXlh?ZX&2Qvu(N8cj2E1C75A-ZJ$uzGSR-)8NSm#_iEc! z&#b<4!%GZ!(!ATj?s-=C_3de!h_B4`Tk+*o( zT%EqQ5t%@1m(jSu5_&RqNvLlhRo5{tGy8evEvJf(In>xbdXu{(GJHm4Lq$9o7k*;AFlTI!dSdOvvVm zKYty?5X;nGCDiCyS?@42s%#2ys4>Wg?e6|t#I@K4BPcoa)`9usBoIH=h>+{p5Nc=~ zQ%bhRb<#6m{wE44ClS?lqw`-zoWLON?4|rB5aKy^CPX=f(i-n&UDYSNA-G6QZ%9L) za8w#v#|K}aT7lJBcHhq2FrCQDe}FhNo?S})OFYq8&hcT0f(8{(sy+6X%CuqzG{+;jPSBEKU?KA-0f#N-~#K76gt*P@R7pmcZSy{gP;WmBjjzLJYi ztIoRGcY5Z;GGthj*Q|sxyI4!ooZlPErH!*pNE>8|&1{!(x6j^Xx+3nUI`9In-`iqd z!(=}9*Ba+P;qzK^yWJl?Zk=weKTqe7Z@J%;ZZ25CcDZ)Gp98=7d@t_5(W$=tuxGaJ z{T5>jJ{%dP=j}Z`R)Ftvcv^?PC!W8P(B<&#JU+h5cfaFojR3muKfei9-TweiEB+P$ zyI&g{{tmKR#sld%ePEQ5oiXh@5R1zL^BWjK==AOCc;f$f)115_9ubBpRNuC}fH;!) z5bALb@)Mt;aL3_ITmhnaD_?q5kOx>5nFXe(&tsO~+wvb267Gz7@aB}AeW|G>2p1<8 z|A0>rkDG%6vAlXv%s4&mBFHod+5cNH2-mvWBn9~4~(4H6rO8jCJm0E&)zHnc?`Cub^17YCZ60Mwg0a-YGX zUg2Wzrr+r=fe^GjEl}q+3-#6R^s}Hc`|iBooPXKj2ky9S_w0DQ8(c35)P3`=Zuz}C zUJq=4Y2B{S^-XVlLwV_^ zmHK-`vN09;O6CgFX$zi5y?-H&i!{;^5J=$7KJk!Z?!C-hq(EN{5_E0%PMsrKrxuPkx z=?p04{Aw_Y^lbN!pB|%^;p-Wq5}NI!Vz{ z{l+ko@^^KpQO`nu%qNl9?+fcI=p+?;kfx>ThGB)~D%(Nhod=Bmgp{nH10x$^ z^n)>flj^QGuPiSk@RV8f;i?mQy|;e|hMOC!S^wy8_TcGTLA z0ya`&By*()9*m(;Iz`M3jVDIz#$-z)PB=u_XpnCuZ7NqirmQD!#&=`Ma=B$vUr>xJ*DEUVK@&cJpMQ# z5~m<67pm6-_H+Bm+!nqnyKsAKws zH$y{aPnu0D>n*v;|K zZZ~c#N&LkpbzH-*?d8=K_S;cd8u)5SBjFO(gQ8V~34;ONd+g4#h;i4+CEt`I+z&T! zmHDtdlf9Pi{3#Fd{BT3{=>PjbosOy41N)?q2$%qBKzJgW-xi;JK?h2Q8(qzLV=;}} zmF|o|$0TIOWPODQHktpddLu1R#jTPC6zgmYb>}+i)H5PwjAA=vm{^fB9-iLxU<1TW zUPI{NtGZ3B@7SP!gYZ^)UW#M-RAs9RX8qsx`?-4mY*8VCq2mO>^yg#kd^=VPPn$C? z^f?~|#EG=;Hi7Ci5PEk1gi%=61mNjGe$~!Xo}chKQh9@ft?tbOt?x9>Ls2t%O28LpClOE zM@Qosa0&g&@~SV2F=)ov{fRO~NCqA2C-)s6tu2D8FUN{H;hDot`3aq3g1>nQ*yD_q zZPDMM2_4r9G+nYZkT4}^!!6Nra!(g4CN{t^Z6Q~$P3en~!j6mDm>FNt|;U`Afb&|$gzLnz~VAlrC|+zA+=tqiP4pC$LtXfr~;34|+8R6fJO-)dCM;@4$I z|FBZwBItFJM4Un9^@EG08fkiSb=s$yl$mTti`xn%4Gy1+MFyp#Jo93u(${FouIVdu z&kZx>W+QS^etQ&O(@XoUj%L!ThC3Z4RbHzqj^crI31!YfrL4UoxCR{{KOS zBj<~;v8(erKJDfThQCauOYME^;lfG)l-Mp3Y!v-{8hd;L;VX9kh5!d(p{6sk=q6W1x%NM z8Pp*;hHy<7F?nL*V>|NLhx{kT)MRZG=kHqOp%CnR{E`{YFPP44!U>mknnUN~xno{) zRUg6XlemMi(+lZvJ!~!9yb>j(hHkRF{m_uORS@GFd42W-0qpL0u#{g&MC!t1jqC?# zP9GeI>p8#3g`(Z?pLFo`!v_QH`g&;O567;VlIfKNZS1)G)170Yi4WOw5CX6a=YU#? z2n%Fm!X4MXTKbC1()xv%Rsp*V>a1w?>5scAprcZi?BHhNgc>JQU{pvPw`ou% zt2F3{r!xv`haVkV^q2it$8Gv)1K?)TXh$cLe^*Kxo%#H=Bs9FI8YgXrp}F@H$DCV$ zgKEqCx9Cl+;i2a5?DI3Nf{#%09tR>6E)UM}%05Dq+t3cAAOvXh8~(Q;f(DW3tag7( zku|wGfP1b7QPk4S9)E{Ghw&-`kt0<=jB-~==2dlTX=p{0t}#`uv{5SL3HHA7f}a6l zrbIEQ`hi36J#QqFG@p-Jy6P&sR1eFraV0M6*tm9$Mpw)@#mv_3%qaGA9pEHL7LFQG zNQ^l;G=8086_!vi%;#v@3g+}jK_<=NsoK!jF6JmbtcYXUwr(sc3p5vj8Wu#f=c+LU zdn56UX0ag`nJ_+@%7uez*|_4?r$DjsyT{E>j>eb%p3p+G)2%1iY*96Jn9ygc+F1!b zb*1XYrpDcz+2Doy(`;pC%38y)_Hk?>K;--oxnXQXy^?b^OmDI%Gmn!U298}5`^y8n zIMU<0mU0RyOOnvvq>CRS`JD-<$!K<*7RKvN(vYiV#bg~GJ!wA$da#4adh4mH(IF`A zc5H4Cwrg9&okp8Gi)qyc*bCnu5&d}1^~RNNb?bYi@>vy{xLC+SVa^-n%dyq0+Msxf zt>GkXa8A%84wR*FtyOd@u+=*NIa7T!_LcfxyhVC23@xalx!XAW@Qr6^wS8u$tM@0o z=xV=*+wZ|WL8 zbH|Q_3e;h~$0HEp1vue?1O2+y<<*u&6JsU?A!!Ru*mvZNdQ3#aIHH0lRTW|`kS!iq@e{iqi z0-bU?Gd&?mLu+mr5?DWpO9yFi`E!5J<; zE~ZYdy46{c-AMbL@hVl1{^p}gB3ppF3!d$e4=5Lf0@>O9#5KQ; zs}TLwp8>J%W-%#cY=3tA^d6_iM07Na`Y>R(Rt`BPQ7@ zTZ^U%OO(uAAYX*u;>7t_*=ZVoI5~znK;digl>)WAU;I)-_wM24Wr<_<-1rK!YXiG3 zo}Lx`)%g98a**IGJ^nUn<-zXbGH?x0P#jVhLEOCH@x=zRCUUL@WK5KVz zS-Ya5Mn?^%rcb>hM*d}!*R(w`nvy`-j$5|%*n9*IcgAfa%VOm_pj7XMZrP^I7safe z+KV<3mmCGs?KZq|^4L0+%w@OIUzXk@rF7F?~)IKi|#qmsTmY^qRkmeV6%H`Gj( z2B8Y<2!&pI6HiRRV=GtOps=z8CT0eKVHl1zg+4W_M?iej*5NIj%xPg}{)s%(iY@Pg z6}PpesgDKxv6Ts`n)wiF+sJ(3$A}Td3JKh%6R%ST(-$m5UULtIXr8>EuCxws`p;+1 z9d00uyxU@jn%rY$ZT(uxAh$8WAxOPAD@dz7j-h;L;_-d98#Fxvq;~!@8VGpgmXcM> z%r@bNd(jiJ>rwxrj0h8c;MAfImRfBuB{d#`{|)8s^ONupH@@CduNgt zR*K0nx@JEhm{u@T_`$iE&D$D6 zqHKq9@(BeVWid)^|##*AdG-yx3CQ4ZU6qV;1}@VKjIuMIx_*?2koNJ-ph|TM^(od z^ETdV{x5NEPD3dAcVj(rJ?rOxi*x>Oy*>XC=lrJtZU7S>n;%1{{v*!4|A=$9v>31T zw&nm?yUNX1(mgn?Hy()pOPo_c()?fIT(OaGhkoaeI5$KBgH+Tnp#Q&%bGQrth;zjM zCC;r`{D^b(Z2yRJBp*^*ZE2wx7{6dyCPS`Wwhed>DFJ4vHlE9m+tm>9>2UpowD=IQ zW-rP>(hK^A#A~Nwj#)H%>IVP<%X`z<5eEB-bppIWBf|>q-b6u-fP$WS2CUKrr%4gT zGxT=yM~&0^ye^4C!s5d^igWvZmssXg%`xtx$JI9NuFM<2H6lm^DaG6yr2w1v)-*ZLvRFNlT$J)mtO& zn5t3*^BZVe3$)cvs&LRYU~)5A7QE*wkAraFfkszc|8Dk~C!OOG?i(9Y>7|k6fH(5B z$>;gU5i!Y12MR*NZTQzAfLH6s0Vb%w9wSPPiS>iSB|R}oJ$wO0|ImzthP zZ^-woB83&Jz40JJW+YO~NmJgRRecQqfK?cHq4uExFdjl4@-HDZV<8ZPY zPmqae!+L{=3xkd71{vnS>{@WVBZtSz=v<{3;l4VBR6>VaSH1H?XJR48$R0DqV5HjI{J0$^2w54Z&H zS52;(Lxu8+jtP4V30{tNiT=vSh|Ah}ww$X>dSXZOjyZ4-(x8-?^Fg?cD%SUfwGz0K zjhGvC&{dFpeI8fk%n9|!_UGj59<&l&MvG8JX)kh$IJ@FZ%_&nFG(c9hwQ=v=T_l6> z$Vc7G7R4^uHd9@3J+dE}5)z2bPz|W7Ps+b;)GYkk61@JD-1zHnzEc{@BL*M%jg*<) zejp$dhEk|l{es46q`CsG(s=1Mb3O`~-UeG=Db1zRxfQcsH3cVn2K`I2Pk~70Kvhi( zF}?V}#mSCnhN1pkAr*}Y`gLg$S0`1LsT0tJs7(-a|IfWGyfQ&_7=>U@Hf8d2EDakO znJ0?SD)@aTJPoYx8K@jSkKqHpb?OF8C+a{-Ik@z@bcYU0B7nQDkfmZDKtom0g?+@S z!*>PB4-4ozavF&ki1rT)IHSLsonH#Mv|X%4?I7>>4-1GP4&K(pX5VG@qHbiSzNVa2 z)}pTdcYLS|vDUCpyR+rpVo|#jpNi{veAdB_FHejYpl~u#)%cm>}zm5lCEWk^6@wqgsTgS)|b`UQ~v)B8H z)8ZG?23qDYXUfA>%;B`?K=;IHIR<7+khP2%5y-{*mHS<0k(D<{Q%JV0rJ=vupL^gG zaC*OarGQEh&P3CaPPj3jhOX#Vb5g9UrXN@KI7tidR24=B2oK1^@vy;j z*#0WY(x`;HyR`*PVfjY~WD7~~Y2MV6Tr_9iCT=nTb;d7F;s=35lSpk6CM87f4-AJ=PpGk(XO z3Ndw1-yW^T@SI%o6Tn&W5|*Lv9dbcD&>bU)RE}GGq4R3Q;2dUv;R<};$_PWYTY#Zf zQwN3y;J|1&qv2d0(pz-rU1hlOPNHPwTtCyyu0%CiUTGlvx}fq?gI zS=Yh=>Dn7Rba?6#_T?2%Qi4I5_bWrCvY6z#+F1H0GLpx2fSuvBw9P!?vcJ-y4JXm% zkInGOk`(adJnM)j_%WU{JO(nBOl2ilC-%It&uZ}QH{|vUh8|c2Acc8h((YCz8=%g@ z`ly{@Ez>`BvjeY$=L@_SXpv+mC@rQKG(9kF&;1@Oty}$d(3adO z1H;)!$(&}u0uzrvU7b>Lc(L2uk%E+Nd_iJ#u?8)DE-=l>BYP0ER0tMq-G4*fn#l>8 z!^Z!}ri&1C6cFmK5`ZFIA5QY~p!unCSkdCZX4WAR?H1L+j_s?WQWU}MkrjhkuM+ow z|B{vo0NkEX#}PD%KER5YQDxJ)jT4VC}IEufWn z?uO8g1M-weZ^&6K8J9Wmq<&n4X=ch0DuDj{E9F|_KvMb4jpn}aX>Hq;^7YAR+3naj zaW#;ExoK9`mSV9XYtU*lr)t2brBlj$U}rLoEI?n|MS21D!4@Hrbrn=?P>(7Gn1<|^ z{oycIKQ_K-)3Z0d!|OX%l`P|Vj@lS3q5;jO(QTB&)2_o~bB)8s@L^ya`!?H5pn{8w zgwiAsA5+AMIXJe&1?metG8&tpc&+02NnHR3M|xCi-U}Y7+u`5{((1&K;WzJ#{&()e zD}ARl3HWU^`tU!MHFsy-!+sk)_e&wK1<+>N@IqV5cUi1iIx>jC>4${DPgHHmy^5}apZ zO9yM_QQPPa1bfFEYlbl`Yq)W8Df5=w`$d5qqLf2dBV)eP#YN=K*nlZi-{jBfa;E~= z1f6GGacys&Fy$Ky2&VbF$$od^-2f2UuNn38zr` z)%|}3f_}_cX+M%AG?v!It>c;PpyfwIToBSXPAbSOL`s2>A<8J3A0>D+%6KSzMDIss znl1b5ta9nMWZeF8FtKlS6&s_B)&yV%uXy$H_DC=-+)pgA8YL4MS?y3-zZu6;ApinAEEWSyr_OIZwZQ zfdjs7FtjcdBw0Y$gPG$V)h*ZV4rhM+MNQOM|GNa+S7dBu@9H-1(+jc+j zpX7)gw7PDMzoj^od`Iyg$=EN)w#(G&q6!5b=ap^YjoU1BN%BbtmdW)CpN4>oDw>#$ zHt`NDy9JU#G<3{`m4DVqUcE5Wv#T_bEg(pbnS6+^>U^-RCx&eAu?&>ENAvAVUi@&jD${`i64)n;<|J?cZ> zJ9CYZ-+Di*{s-UgkP3J=*WBxZx$ANmbZvq5S(ZBIPfOA_?^BnSW+cgC6 zfAGLCr<)%V=&$Uzg)74dWGCd@P?oknmVh_BCdz#1%| z;kJp58PYXf_T@`cHAIPVu5->jRSS;yfmyvh=#DQOOudYFMA{#5J@?!AnPY6c*q4*H zc|X4Fyl+Hk-F`8!gu{rat7hmn&YO`iR5r$yeIg$<14u39+t2Di56&$7`#VU zDq733e&9wfq*Ib;=A3P{K+DM$+vwZyA*B00SbE?06jIxe8;k`{^DgDsvq+sTO(&eN zCoJ|)PFhYg?C*)ZQY;>K*vR)?O|)x?rS}IcM`5;`P5ZLdUe{Sc5!$V4W386v9+53; zRxPSm9S!%AjExj?Txvq82C^t~Ct+?Je|*2z`+TS{zkh30 z12;9siD2qO*I9>%yU+G@Y26)np;a!{(6dMbiHni#9p`Iy1tu!R4L=sZSv& zOp*_1AzHrz3HO|~R~{&=Ew>p&>%=Zg{t|2 z4@d>A5c69R>~wvahyMoHbE{^novhc)^Av~IhDhcdCQRXIRpxqw{*NBFHhKV;FXWF-eAS)&wLXBZ61c(Z$_A<$(O z&hr&$^%XRh`0l#K&pQQlZv;FjYI%945nA;3!8iuASnr{$LQ{UK@7 z*psSrUaxjZTjyLh@a>B2y46sg2n~5yrRCs%&s8c>lLtVIn!>Q)cq11|2b|r@4TG*`Vx6#b4Q^L z(>!$y>n4<|`roNs96Xc?9b_qSi9LgxL|Ib+RDhwU(*-htACU=;Q<6BuX6PjYsHL}M z7=oW?P7TTz0qeBociRI03BxMk zanYr`1uF14dX!y@}^_9N@;xIHzKvIn$j=Y6LzD4Tnvs_setl@}PdanWbV*N`_ z5j+|dyV*JYoAFnjvq>u}wVqWSG=LjQH~2!XFc$cLPA;54Fea+2z34fdP|COd#g+JE%H>i^aUv19vUpb*9Wr4Q=;=z}~CzUoK% zuFuE>vVVE*e}aTW7H-ngTT<0pyOFp?o|G8tqtNog?Qm{S-?Qo{os%dnr3`YsOJkXL zPMr8Y{BmDk=(MQ5^ETYCw!e=*D|6E9bVD@0#BjE~zJGq8GlkV;Gr8|yd~~W`e66=t znDgJl;+GN9kmW%XArSJfRn@R)36S(z#GKHdE^7M*fwBb|0)JW%rH@AhTcAVD#@tbu z32g%^VT)LBf8!!Z*PrNW6|j$jv_k~&bm2Is);NHlt!}tc#$qjPj;tg$nFAJs7n4#S zwNhi-S2?gozA1P}ks>dS5if>R?N3$0_gwYhtim$i{z=8bFVSJAgd*y-Nm zX>OFQcq;?iWff`j_SL2@Je+;cqXlx+a0*NVdF|VvhTpJXQt0bC4Qnhhno(EwTT%4 ztWt-Z#Q{EpWh3q>mU+sQ^T2`a6RC*+#rd~&i^d#}d-tkyHlawcusl+Wlbmy@!o+sJ z?LPz~H{vCw!ev-AYPY++TYH|LfOAy za;dh@nxX-os#wmz= zs7hq3m_Tc}Kt92e*G=S-ms&NjfLEgmD>Z#F#j>I%&{X7Ch0$&`~DoZ>~3RAJ^Tc6`FGZG>6R5@gM%p4yQ zER>L|2EDmm?+rr_iKWp!c+A&Lv@p0o-kH}ZM>HB}4#rxYR^$#zm>HFIZ8I>i6-G_* z&_MXeaF++6ILrQ?M5Ud*-xq&>@$HlJe8Id{TmDP&4s~bJObJ_Ps zAC-yen$P3cz&4%N|3%n6w&%Gu+yahmyRmIMY1G)ZZ8f$V+qTm8k8V|(9SYdv_6 z_t<-Xn*ShI?lI>$N4xMfUg}IoZwaOJbn-W3W4gMoUDYKR_`@}bJq6nC2P2J6zUAkkY=)cn6h&xq1(sHguw|8gi}~WDktpe%P14;QkGc64 ziM5>uO6w-<$4K}NKnT;Ma5^CJip`;KmO~a)$Ds$<;(=u{-lapP)>&niRaSoZ1T*=o z!+vtMCT~7WY$o2j^Gj|UGGD~b-cqI|g846hS2F?8IMi&Lnz?&;Px{(_Qe~YPq6FZy zQZTtAu~yS=zTKMYAnwjoF0%p{LPt@Ij%D~v(`5rJdesLg|9H*AbM44r0ZU5REm~(q zI!9zCek`DVTZPkN98gwXY)i_`XqwInDMIxf_zkqpxE+NF>!9F=-lS$BXj$1AUaBhR z89s?iP7ppt%?>ak`FaI3nO)e}07P$4VQC=+3G0%8y>D$o%yVH}NQYK~&_=(6fd-H( z@KVtaEg0fqSLe!Qa24oR_{+E>;pAJHg1P;G_{#Qy^Ep(Xt^t)(;5`HSLc`iu5F{8_ z`$BMAGcsCYU$>dWu}KPsl-E~1KCPeU0seF;R?n}BRQNCg(ApKub?_@Xd5PF`4CYPK z{6q{u2u6(4pqxPWs|64d-`}tw+?i2V1M|g3MTIf=H{_YYdq~S<(hiOORXt55G!8f`!K+Y@n8xp_$i ztNwl0*J-+(fs$K?M08U7&lde6P~__=ar%ef^4NmXYQYOgUvnTJ`8k{H0k3P1V}pVZ z{>vou8rzXAnS>AVW^t0x(tZ13gTK6D=dm_TxEYK7g68;7Qi*N zpSPQdZdO*n5SFU5%11vcOIz|w%NM01@LK#((p6s+Szgr>S z+DLG~nMiEEP*5V?Z81li$hSE+_c2cuM{l%m?=vr!-V4AQ#*cxQJFTFiggVfys?+F0 z`o+H+z30IF_OlaThCxh@f<4lk5Lx;5Pwx)uni4CTCMWU$f);|4j?oI*6&g-5j8_4| zu!0hU%Q^2*iox+tNo04e=G*Ial>fo9Dz7<}p>6DzSljXTBbfyVRv&>KbdEc;fpQ8KUmcE@zE&`Nfv$X;X-SKyWl zTRV^=TaYQupBZsZVq3OhH5}X1t3h?+W*IS)PV78iw1T)E?GNyD4#{k5A_Eqn&J`=4 zd`M#Y@X`@MPF!b}gs7iGu>AE}A7t-rRtPU|WDSP~B*6 zjU+U;E9mv`B9u)4o~s39QW%P;Cv9+J@fT+V5M4JilE?vij7?d3;YhnGtNjdjW!zr7 zhnV$@$S-+S1GxS&WfY{I)u#*()9-v~QC+s)z2e3xf|+^Qsg%I00%nYU2FL}` zWhWhmWs2e!`9edvG*GNTngaXD&BMpU&M*PQj!}m#(;CZ!mF}9M$e||v$S%!+DNNfL zQa{vW4#1C9Zw~7tDN7QhbHq|1nS#i<<x~bEAJDdgzxi92m+vHl3d5OI<;)76ruS zy7^hk%93Mm;D|Q`E6LM{kb?&HDX6HrEj1F#nUfo9SV`H{(30QlO6gu?0aKIAGFNOY zT~%ke5)a)b6+$4ZIkHG=La!PYy-PW#(!5NCj*1twMFrph4ah1`-l_v7xDr7jsQ8mi zZAjnMNId*$;SCT@w;i))O$y;)yL{V<{Urgv1e#KRfQMbdk{W}V?7Np;8n%(1UAk1g zi8}b3IQtizVUiT5d;+Ryo-zDsCP$r zc(=tR>6Oc*xvvGL;D*(GTu=*=w99vK&`2JSR@9Xho0XW%zr1`QLoK?~$My4w76*Ld z;#E0?rJ}fFz)Mi8%u)tuliY9LJ(97`e!aDkw3@Mk(V%=4jd9)C9M=X3Z2z)OfG0hz zJ&9EeP1U+Hz3FzrZ|o7pEf4o#fK%D%NUFNV7`?L}E_jhzG<1uqM!+Uz1NO-$7xE== zM}wBtixZEYFkP<_xq$SMY=i@c zidN-EjJb2tUO`MDrFU#PC`&>m*cmRj!SCXd<4)wIuzBFX-ek%Im-NqWQD!-$BsS&s z9+IXY8+)z`ua`>UG08E?@$gogA<+52m|uUvbx{5$0xc?MT?)~BeNsi#V_$pnf>;A{ z-)`4Yd_1<4wI9|lx&f#L^B6|a4Pw-@^ImdTyx~l?#zhw zYl3_)sOmZf698+b62rA;VM;}ErLsc)D)xmhRe7Y@&flWoplG3~c%E$+$5+eh`iuRq zuZh$>*PgetOw(b$`OMXynrpIGNYZW^Ib)ux_%priEu7e|9*Cb~I741{40d-HWr$>; z*C<(64Zo`7n`W&!K1$)mCg}zj^apEpER8IBt^t3MNvn5Gy9!ReLr#V{?HSPQR1-}) z+B=DME_@$8<=-a<)HsiHwid`nX7Q4{Iev6BF2#Rt&Tfp{D7~NSmTEs6cRcVU4`}tT zOWQ9oI?~a(BNzM@p4PSaz<7H`)24p6RbzF?!%Z8g7B+5CO(D9gq!$4khYf9T8eJ3> zV{yA0Iw9^;r_9DK*!69200y{_v$+l7xwu*+c`+clok&AhqpMFERWZl1=G$>60s7No zjchVI%p1|A(taim2lY+lLRJI|B8P9u?B!QO_uVKY*lG4H&2jc+Llzq+^zZC($bfs6 z54f4f0g7I=SaN9>1R*zY6FrlcMP zyj^bu_`csf{RfGJ{rG$nwXqzjHbYio^93I zZtb^zx!KxN`8eY7w3YtQD)Q{gnaUdT)zXU1=Jx^oy1zKq81bcfz8u`|Hhs>Sd$VN` za_cRTZV?~Hx#Q|yc$?;~tB1G6J(%QpcX0GR^2o0t5plj&-j5I;7X&3pC1y5706(&j zK|+P6DTjP^cN@XLF_P_HjzW!wqK_kJ?+E^eYO<$V!d@2gf=5_&>??#HWH#W%t)1!7O?Qm$K56?QK_h_s?2AyfjhGnmSqKlI{nn}VHFk(8*<5O zWVVtmU^2ZufO?jJ!qecMK)I8ow!h3%NNOc2{k|POk?0nWca7SZAnaxtCy5^yDhF;UDBPApiTafpI=A#?uroIdx-`wh zbMf(@Sf-6FpU=bF$zBPA&!1fe)1wXD-nFYfz487I&kSND%IL-{kO~_Rf1b3jbK!9@ zL}&f1RB`8GDYT_tM)!*Tx%Z6Y;CceG0-^L+TmfeScU|mn4+Ay-!X$q#`5ThR;*!X& zZCwE{$yDiW=`0&;)*WXL%61IZOXcwj(HfXR|2<>H-A9^du8e3yx9l8s7y_O=4T$U? z*z`G6g&9r%V3M^z|KFHo)&IaG?e@7uv3dR*laz%K3#zBDxP&lW5R`{fIq{}uuj2|T z^_58UsptU_Ny{wdwt|IbvgVEnsk>BNqt^Jjk*m^FZIiObmQq*e(vr%(94&N5px?OE zjPczC0dc$l`uGDW0@aXI@ZWnBOf&&;wYy=&Y8}TXWeQ<6ZubS>)=yKj%k!n=Z-VbpR4tj+k{|7(dezyl8Aq)* zqp>%=FFo)}`7|a@LI-C{1_kA0G??0L?WV`1F zr>Ej-4ys9tZjx$QWsQ0?U~5`g)l7_@R-J*@JGY%^Xn_Cf77DUiD&9%X%qRAzGM?p0 ziycbA{p5%pOwFFAkc4&@E-s>jIC)#fZc?S}8&fXuyt7l21ooaPMiwPXxyRl)#q&hEf6foL7$GeGiNz^1k_(kV99Yk>Sir zOStj`UuRoEil5R$MYhLLX!fmJL6ZE!ZE!MZB}7SrnkMW8V^6$2bx)B43(XEGe(bIc zLf~7+ddFD3${gJm(j2V-S_94J#fUFPnsmc?q%2X>qZCVtCm0L4z}B{C(TW8tQ55Hj z$!*2~`9z^So6Dh>A;^S4qy=mDd73XRbCC}NW|n$|oLahW`x4{GAqNNNf^fb68T@JY zn^7xt@h=r8>6$Q$BDsO6Sxmkcw;vvj?X}xz<*IrX56<2CyT`G(nGFuyte9177N;!- zhw@3f)+ih*OxIa2>P!u%N!c&8!^S+{_3WEnK5b3gqW%4H=JnLHVKQIfRq59#alVP0 z#;cTtq!imcewX|GHgak^u{f`X1JU(3a1UG9I3HqLTZNk@0~&zRCz{3mUXVB8P3eq( z`<<2Il=PRgjne*$n0r3p2O=F_tB?)%B5=m2s)0Jzi4`ncip`qVS$)O3y6R=_59TsE z8&SR_33XgHBru>`c1(Er6fGH%-6=`_v36ZyLsF$&_le&`|5J=iqF?L}+WAL}90jiW zON@+D{3AvdhdulwMq-CqQbYnsUrNx_Z)&~DQyb--l1!gxv{Hkuqfp+&h3^VT6L{Mj zj8er=9k3Tt8Gi*-nse)!=aHlqm)0qyMvpSc#-Z^Z6UgVox-zMfscW{zKP7_<;WrCS z%8F5i{gf#47Md|YK^0r+2?z*&eD3UAAJAebg@5AVQU0ANO6>`!k6BCl3y%7QJKGoQ75o55+8N?#nni0gB{ zSw#BzO|-B=a$0pL)lvvQV3{Ungl(reOdWbTZkEOa=pJDk#Kn&d@$GQ+eF=WB%LTT& ze3@;{*_DsucQ9MI7$k)HbuP_Qgn9Vy0P9~pA)K#dTv@QHFxf^dy7ms8mfqE(`6>%C z51yovoGBI;^=6`QU#Jpogy`@iWq6C%u91*V=kLq)!U8$XD!yu}I7>n382)a{Mt6ct zs}#PX45ewv}`S7v!zqm-dynl0%<7-*76-a-$ z$o7bTagl?T{}(P2c>8ZI5(n{Y6=H7oft~Q*VB|ya-v0t4t=s-57&+|xe+MJm6q)}w z7%2=RNA-Az&Rq>JgxiGen9OJyuVHDZl1FXjgi-Mxkhnb>Fe~fl3o`#(o;`J^0rfP4in>JLDsl?gaCM$ryLDB-3LlwI8v zR*$L>-oY-w;D{At(D_RY(QfN+@ad;mk1(gmCsf9ju(-1=GQ#`&+rDYwgNE<*pS|mGab~|PV^tq;u=;p%6 zx-q^m#!%QCB_ToBuU0SN74@LJ44zC@KODmrD3C_&4<47+kK^a;EmKmV| z|2zVj&|%X3l@kIVraeUlgE47`6C?1@6&^A$zW$UUAzb4gWL(G;&ZQiysBWE3UCrg& zpf_fdZh?%UvS~c(kS=S6iOrrF5j%Igh(w&NG#pFwRE*&4&S}Nk^nPJYa#H*58yEvc z)dOb9MNQVIK@A~UP4of^OUfB$HH#h(kqAWmB9H{qK4n_v)cA${d6)nws~j_~p6d!b ze3$zyuBRpz#~z$hAe)|OUP?)lAfj*NLTM#BHNOd;TiS5jlt;eIpepGzU=^LKBHL+3 z&H7{a$eB$+oj`Q?xa)&9>oZ{;pP4HeXj%PMJYD0wVx{Q=I&hzF%`d_BmvKJ69lCN$ zE$v4iv)&VIVe50AgCAs#qbkaN@%Skl$%7Z4iCbS1`29e8C(^`fc0)k4j4g3*B~?p! z!psJWd?T-(kL>NrrkR+0OhN_bW%;RtS>uu=M3mn7o~1{Z`xo3h&^`DdRB^Rd$T z^dR~GAke}-J?5m z0xf8XYSQJQYyF?&9F^<%rNj$JYcsxo$GxH19Fv8o>2mF5=-8BYl*gQiGZklj7W3qh z#6rdYOr_B$a!ej9OnOnirWWi$`zD2#o$6R`btoT98kx8vJ&6&NCmb?;M=GHV;hHID zy4iTo(Ng%Y&U$-sXcx-P*Z{8^i+V3D%p`YVWC*wu3FF z>2vwiDX|a%I;`qT$_NJ}J`U1v$PwP@xG;@}*Kv4EjX=XyAXhtlzdrpVWStrcu-p~u zp+aGyqm)YJov)ri5}=#J(<)D_sgDr-w$2hl#cU)tF>E%Sq;bbIc+V4r`o$RbuGw^T zs`3;t6yzMYCw)XMUIl9A2M0XkMplDNB0cF{g_~LEDd;o|kKLQIBJPZHHoZfLQ?eZv z$EYzbbWTmmRu=^U%E=4~y2@oqP)qCu|FiG|Lv9x?W|kgDNKyZdT7x5daF}>nxIV_` zHD}j>`=FjBlB1rmQ=Yv^5b8uDQAf8W#~t~n(r+zU;>7%8$;2p&h@G}?-dQCH)S$xA z8O;{LEGW;8CPh#?l|kZ3xjuo6NLXP5Np)|T>iLzZp0}rC+B0L6qR*8&UyH|**?-4Z zuZVOQVDUZ+>AJyGNoT4BQd_JvqpB=DtvciyHaR+GRMf$!aHZdfn0vL)$1yl8>_UWG z=U?2A?66z!Xfa$6B&Ur;_`76muL~MU-9Yww!?;fV7+2jQyM%>%P6rD)wlK+2jeyIT z=OARUiuZi}PV+mgyT?FV8N}utOYfm*OJ>8;X6B5pNh;dLTFEi$r%QPknaBDAhEpt=EJc~y2 zOdEI8LONMaH6I(IbroB=TEurHA{7(a%wxLliD)l`aZ4bItk$^Eb(QgfTOKI*dLG9B zQ{BCvV+fZPWhX;|rUmx}qG8s;H;(V>QV2DSUtsED6$Uzr8*D5Wzcf_Ucg52;M=W}E zyQS_ml}1etc#@os>sf;Hh2nB21^q=t^87_a)}0|teT$zFPW5QaX9p0GkSYKo@<0ke zMDi4WzlWan-Jn-pfq^?w_Aq${x=|I1iOmt?%7(_{s;isd7A8W~jk^8Og~etR;susULivv=ss}gA@AYm;R)?55dBD)UEr&#g_Ypr1$NFmW|0fh z%0f3iqgIf*D&J32vrY6sjES$%SbR?*X?C2CD(oGdkSF9dm^ROfIG7z?oE#QnPc80; zwqcL;)(1(MPDxZVTou=MCJlrKVJUZg6STq{?vr9>fHy);6Kk@A7OYBTLNVzmz*o+B zjG}AYb5nW9eu(Gdhl>XEaGiNhLsj|@X&t>Gcqm0~;V00hP=rBa0U4o0#w!sVF+(R; zdk?ORooJnDm0XpO37Y!}#@x|n_T11}qn(<_R^YTEx%R!t$vH*0Ovk$VRWZ!^3i;~$ z)4}DSKbvp^XMqL_r#*~fZF4EtRP3{33hPkdp&M9#0*LNv(N5q2AQqt{oMP-SKyUJi-PiiQ|PLHLhl_OSuw( zI-nYhRLZK&-CL`o8_=C-X-l#`>f+7aEHfA7qS#A<+t&C)L`o^svEHaFmyI`(`As-gk;9{+3vG$Dwis;L*Z=k2Oe}ms zdx6@6EthYkdkUOLg0RF^9}=`Uq*oBM>}SK*>U!O*ODbeNiKYaXNtvSEYoo2&4_I*l z>pt|ae2ZuL+fxKL=Ely9EF{sjyjX(LqTP%fNouqzm}acj_L#x}jGl&n?8gZVCo^H| zoXp1C zL}2;j-G|nm1@q!pTerqfOjy|i!oU1!@?a&1sRq}mf*>T*+d>V&1^U~415u)0tue+V zX!CGjXN-)AGx~)2Vv8+HI}X5zsws@@mD2kQ_y^zoRq0Ec5Dj7pG(tq^QqXp=Mme_? z%IY4f=LXt0N81(z@h=0f3G9V^5Y85g+g)E?qh=O)XSX?>r8_OXZ4)m#||EU_=8GzB#@#-3aOEPbhjehe-zBh)7w#Q>VU9wBSZHJC; zxL~4qKKlYc!%2E_V$+J~Ca-SI!9GW!2Y^zqQ4!y05{K-9IAtj0V+&hpmG9Hrp5oZ8 zx!hDGDXGsZ5=ZyG=OQRK&cQiX&>-=v%cfALZjR@x9_OLCon%XOlfqv8vhqu5#Nj>g zp{VkPHnC$-%`iwOMnC%Qmn+n;kqHV)eOiYL5zMMp@6pvN*@&VdumPlVK*G}f^XGDwD zTTg86LH>{6q~}ZV3E%fFtTRp$LWoABCTccKQ0gr~&sr!Sc0YVU?h`3oNNz-gy*=}% z8L?}uA>{r2Ou2qb9BKX<_7TtOnlgMNWRtPwX6%8FwWZHMg;M=J|J>giZ`hN+!{rB< zlWYfFf2@BJx+ZaQS&v``b3p4*Hf{Xl6r%mwno%X25N@w|MATiGr}ONQ=&@vp%5_OZ z5Vh87hf$?>^ivJlWBq#U^URowP>la0cGqg|QnCH)+dyF$u%ho@w=tofFYo5O7mrO& zRud>E)h>%4cN@GrrazxkmV`Hbvt;-;0lI$zqb3EWG zUBACg0NqTqU)-EBWv`|BF3&S$^U-X4UU{6IM1Gz6B7ixym_xwladS7aCjdV6w>Rkf z<>?b3Bx-+r{vNnR|Ll%FLU`%H`b zB-j`P@;-X~6soijsORZ`CHc`U|V~O zAFTVb!?*kPp>MMyQ2+CLZTsiL!DeXZd&_Q(UO-mMC+gex%k!~nsb6Tm5P~F8@^boE zJG0PmB6SNuF1^z3z9KUS-AT4Z?jMV zSXC|_L^-2T`gGmVT^e#bJ1<>hh0x=ZG0{(RtyV)=cqv}ssNvb6E4pJ^mJ;44Uat#< zk|m}&!A?jQhkEv$2vbrP5iG#y23*KV=UbD$ZXP^#i>}nRr+%zQ09MB)Dbk8NRCys~ z;X6rUq=ktCN49tG>KFbuN`!W$w2)t^3TGFB&zBZp8brU;GqT7hZ*i{hhxK2celtBq zLWqzB*z#+eb-+t~c6lKg{d}MmW1{yD$?PA?#qtU=mHi0tL^DEs9Lh+2I)5lulGo>|odmSeIzMAe{)K4P%oy2>vgyP0~|Oeq(S~Lp?E|Z-0RXi zC`GYQo!4VbJHJ+s3{06MlnQV}`O#ArZ*<*fG?`$0;; zgI@P}m6Ki~CQ~)jC^{>N?AV3F;}jV?p*3H(cu>j2c^; zwH@?LM{#zrRuk^ZZDR~8?u3aKe5CsL4J+5-%c z0|uc6%cfdVmbi5U7EDgw@dCwoFJNF(*hMQck?mQM-Ca{he+EKBM(H)YGyF`iTJ?0U zFXPoXRLF7U?G7axH_)3v>&6RyXfpeM^{oBxyb*e<&6rqC*E^bs14A}7b?>hd!<>cM zMdJgJaJ@1+SCgP2qQ?e4T5r;n=;?G_sA)=Kv$##m-%zWZPg!#mP9Rp^h3#IW%3a|G zz@TD&O;zIaxwb3@sRTq?N!c4jvz0hwv4l&7rjBk+8FugmCs6na3e4nxzPy75)7#%* z#~eWe_N1&Z+S)V;-)&s#qaC_r>Z6Ox*g+nPXRUk3T6yJn1D5g(!EAb>Y1z|T!!y~3 zNg1ovqe_b72g)6NQXh#6H@WN*uTONbA>GC}S~dMcw+n2%0?!@g+}4P^&0DD_;MaY(M@~wx!m6t_gtY`vyyqok%M7iAJ zElhAw5BzzR@*zntWT;K|TyS<4hY#66L*hAw3EBrk1_!j}icIf;w#)E`Z&r&y5j8PA zKQi#1fHrVjf8`TNXrA?8z+rnvi;A5}ZPY8rjvs(H3dT~+J@^x+N3lxjkqO+I=ay5E zmJ9Y8&n85Z7=ZUIdF_5$dvs@gfN|J#p1aIk3}<6?SX6ZpxI(~$BVy58{vsnEAuE`f>+L)d2>^5+{YHtGk>G=C>|{D&`kh==B&%H7R=+-8uO#nMAyxkuFc2`{1s>y8+4kVf3*MJ?$cb_}DDHO$ zUaqVx=xZyZioH2!DPfR-eWmr@NLm(0QJg%l{t?>Ap96TlvO%s# zP@_ojo1x#AK2v1~jg(+NZ2XDk__Omw#gHw%*8Keotc*#Cx=(__K7dAyHzI<BFR(T~E3L4rn;ZjgJZVJ_tie|H;8-&+F$ zx*i^DC&VvgtyqF+av#inMYjFYcIVF$1h3Jc3+n+g~_O35Sfu}Da?X8IH z7AJu`6?B7h{X1#S>5k8iIVB=4UdOHT?GASO$4V8p8j7_I`3`R~#jCHUMZBkDe zYx=JBG?CZsT0ufpCO;zKas}dO=sha5>#etFhbg5;*5PaRQ?}!O*E{lUk;G{5LxvO( zGk8h2h$(@zfSqh-$!pF6D8fPu>Y87?ZKu21LQ}a+;vpeON_iQ~*r;TGC_+6*&M;;D zyhluYFIMXe%_v&k{KAHT_Z6k;JQ$GhB_rGw4ZKbSEd_S1iB|>jo#wWi1$9+Zs{=!j z!8v$>fFbJ^sHA1~G{h2DTTsLd)0q>GM*NNqMAyg9>(kB!5XlpH>XP)%9=(f;(glSz zZ<0tKNm3FtB6W4Dj0%f&68AAoh1~F9&iEzFt0lVe-Of})++5K6pqFqH6-e?&nn$ruVUsOU!{p?}gl-G>XVca6f8jq`NU|Xf>=6uVf9}3e)0% z3=*>C48}xLdC4Hv_0>OKYT=ine*b<+%I1PUmj#}Xe-dJoX7cU-A)p=lL-e3)<~Su@ zK0)E@Xa;mLag;qenU^Y#^ir{e4n;7-4LwPn8hV}P*0zojQI)S=SV_f@_eJQ((avYp zm7d*6E9g5S*0t1QJH^z-nXg<+Hgwk1!e=%=fF1-?+U~lOKHN}W^w3eVU*ca__FLUQb+)x2UiOIrU%dS2L#b+>6skF7nUgKnjAlG26X!L zm~Owq#}^cETZM`5wL`c^4X&Yd2nHKxe+6WRL!@2h9^3%%b# z*!_GE+j$K5T)N)}8|&S>5SXODF#|q|BrvodSRJx*aw-xBBAj(D)Viymwb9H;Y0}`F z!raV69O3ubLq|Y`%;Vu8``C%t_Ip!3S9{LcS|=}I?WKR{!E5!Q-pTy?13~`LlDAJ;G*djItAFQ($>O?W%YclR) zJMCtV7vd4A;j8BO5r1C#Hnbw6>?>`3ysqg$x{7Gb9;*J*Zj&^2J=m?-v>aK2>WQL8 zrzD0U^Ej_(TA_iVZxjACQLcNRibO<{>bj)EP0(J!4m; z6=}#E;CfEUqvN9AHg9Nb%W+QC*40e1K8&oZLXIZsE~~BZZ@s#D7e5Rs=kh+ZYqIgi z4~HB%Ut3vAtY0xOp4$frl6-OcIyc@>+M0!eX{XiG=xZ;xy1AcnnJ#yv?r5bca+NEu zE^DHEKlLDA?T7>wXt`BLA^9SP2EHb~{^13cg99&Nwq1pWRpmB6vKh7iix+guY5<|N zEj(d2l0NY3rMX&0cmI8}U6(X|uqN!)gmjZG+|f*@yWC5^I$WKnR<;Bn!4<;o)nTnE zS1GwN1U4W7@`Aa|{VIC%)Ib)GA1e%eRqX>_T5&mrjIp-3vvW0uc@>~BzQWkwNPi!K z?W+Q|19fOLIbt-_CDC*zXlW~5(KlccVociI<3yh&wcv-Vgu$?(8tXh9E$YFz4M#>R zg}b*f?YJ@cJn(sC&a%$TiP%A_x8(jntLVSY#U@S+OI>3`2#0n#U_XYqw#MQvv==8o zEfypgtHquF=?o(JiWKl9h=MDzoEU02KNq@O<}U8g3t^GaId;bMz6TE?u|XN5R9Egf zFccy$_fqvMN_wZ%xo_*%MbS&!Tb_jH3*?6_`F<&|94(k*F^;85=@d|SuiE|ub&3=0CLH34j)?13s4Q zwv{-`*cPq7kZHhk{rQUdA6l>=Me9Gb;K6`HyM8=?7Q`om!%2qGH~k;9pu-{b=+S({H&2-BqD zCyB;z)b2j6uK%Pn=Nyayu1yJeC>;t0IoVV=^`6+kdd_{nwD+$&LVFX0nO@yzU~vS$ zY>I_+bfc?-hk*0Q)1Jn=W;v67ermeg>~)4hDTkjl$or||$Bq-I6{kK1q{?F;53)@) z{az@5q$E%kof|D3z>HMRpwf)^Wv^d{1^@~Un&D>206;+!g+HJm)KxHq;YN#SYxT4S zIBgU>@A#Wqjl})$Q+ZA-$2k)6$RQ}CuZuDM;NyE|kd{IWHf64DmIr=;kjD?ur}Fj} z719Vq*}dc|&10xpW0b*b`cg^;&jX#84GK;Vx<)PDyEY9aFAohyh&O@T-Te+_QM&G# z(nqDEekozaJosK^-_z}9Zv*Y zO=je_VE<;`|87_el&XhK)Zm<+7rx~12w(K2W4drBQ^;)em%wtFu#Uj0x2(PT!Vpsb zV(T=EsB~bCXYbtC*whBdj01Mi37?;{cYYRTge?^io`r7bW#n=)+H_`4&F6PNw;GK( z`34WUzOlT;^tmaR-T|}LVe5t}(CIL@-ybE!Cfo_5N$*}$rU+v$;fDApzD5lNWd9%;`(BaejcH5=jOw&keKUH7!sP1_KPA!AV<&h!JVQv zi$)H(2RHi7FF1U2aUtH``GMVBJR!|kCk2q;lzU#zZ!>QC0VgKoukLkeuD(w~5%`#t zl=79|k-!VaB%SGl4C>Zk4h@KKogOnMKiD+_I2!O7?2~e;+J$02jV3k1pZCd&tAO+A zOLIfMu)rRlaY9j|=>;P$R)|A78MI#DPcOoJp1cnFwt~J<$hbEB@@@M9Fr)i(|lB3r~420MR0bURWQX#1h+skb!s?z%tfJOCk5l~IcQe7EF;eKC#{$Z=2pGAJ6j|2trhP)glB^4pTAD2&~ z%o6db=t>2eu6Yg5;xt1IlBAf45lrfc3A2{?*@)HF#|YQ%|E#4^S(ek<F)Zqg zhjb$u)mw~(kuDWNj^mfSNmLAec}8?SM8AYwBfPea`acRO8rY#OgevXLwiYd>ECgck!&2| zHM%(e+Iz??&?i>~C3>kH{lyd@lF3_ z)j=;18e6Ktj+_6_JP2i zhR1Y55(qDIC!FgGLt9(s$+X+l2D>+Iii$CYo8FpIS+=RN4SG(inBPLK@-}XQQ5e0? z3hEXXjta4kw@g;j{XRxtQk^;^gH59)tFcVHO7}Hy8=W}E0`(EGtE=jXD4XJ~f=G`h znd!b66>qks<8lc~aFD<1Tp2pz?kr;YhOlLfgK<#xb8J(DlkC++0-!dAsf*?PW&sJ;F}PY?2J; zNI^Fp`8Z^7au*SD4Ol&l1i~)v4PH2a7BGmDKYvEGI}Ge7Cdcw+ei5?WE%J}wL>5>>@;D4){AeCae6`FE%OBre9&NiS;VNR7PH#v==|W-SdI#oiRRcy=NQ%R6}zmvYf57Gp$eGgoZXi_-E#AN z1#5vVT9VTTzlQo|A4uo(-k*BE2VRrY)q6&4F^L4D_2$8ueH8HN5na(m>iB^6ps=?0 zdySZt=?5Q}X);&2g{Da|d8#Pux4fjUhic3RV%IDY43^m%psog&ek-PfvHeNC8>{$a z6^xetSKmtyFRu^8(xW4!)2oSc(D02eWi9$>yp$D4a2GA>D48N@G0Pc?HfWrZKLS(B zPwJ1LQeCi6IP&CZDS@e2rBEjOi3t9CeH`j0#OZuI1{(kN)8|IcJko z%;4OcaORY?1Mfw7ZG-oAkE4a#%W~a{uXs@bEMqLXnZY`SkM7?$l0qNkLHW=SLi4A( z${A;vg*8mmA)P@%0@S8Klp3qM$VTnLZg44fw|`^;o>_@-Q}#0S5E}R6XXIH8^9~r| zMH^}Nm-0ztL%64@-vAOJD=OADU;lWZl0rZt1V+cPIp-!RDsC5XpkW&Yl5e>2cPylX`zIE{ zzF7M!779kit!Ym;6k65STM+p?AB)cSgHPUyrS1?H6lbFgbbRwsZx+EY4lgpk2%)(-vy~iFZw>3lBVPW zJYN+%AJIfw+(zHeLokAlebCd^K**(Lp25eJtKR;PGCIl0@yTIzGmCnMZM=xV7aJUx z)B&TxWUu2r%sAEZrk@+`OH-Tf2H5Dg=Os!8Y-5fO;4R-h2=5Bo@rw;_e-+*>0Um=f z^=mQ12lH6O+xSd_8EWB=Q95=cO{|8cSzwwJ-qO?vkJNIoQ7v`hi+o4JK?_hI+xS?J zariL#+P}8h_BwV(SwD!tqrCuXvC{R%D0*f!P5~>xIydDUs*Gwsb0=rW_WzKKyGh~T zj$2h*No3)u)xk9m#|Amr{vST>*s5>$6N+~oi3Ypcm3M9pgMEh_Ixgt`IckRoHLR5E z=e2CIpEbBp{L8v(PnE`pOWg~lga|C7$F&xrPVyy*kHjbt`b*l>&fO11p9O#{9%@WO zR;z=xsVnLdI$>{#QQQ7n0JV8NbKxLnKNf?v^#HOKUXi+-xD(>E66Qyb!}ZngxG|p_ zfW{tRXUhrli-3A1&g)?l5)fCq-*^tV{S^Z6qn;TD7#{%~g1!jmZsQ*lTEj&g9^%Xs z!TkdOwU06OnI~W>YZlNRRR+u)){p{<+nW=6$5$=+qX3j2`_G%} zC;j&3B>z8e&Z79+o7+J8=gsXjf;=_;Z*NZYKi*s~+_yKk`5$kNq59jK6NUQc&FL|@ zH$J zpz|=mpiB1cW&b!9i_s=J6*XM6@Q@Jm_?6KcZMyy7rU}P3%xS@`qBRuSYOI5lmQTVv zaxXI6K1BF4&xeKnYR_Ra+5bw?`&!+3`4FIPQ2J3*iak3^jWchRHpqFbNU2*z7t(mI z7TLz~N&7&sd(~E$++cd2#Fd>wVCSnEt+_KbHN6bmfA^%~dk435mCt&;c$<BPU&PzQcP5+6`oBSkkTRDtC4&*FU!64-2Ul1G%scT+czbi>ujLx`eOed@Vj+ zmA%>B=(j&y6#VI(!)DCR`Ee;cPNR!)z1``VksnrZ>!kv&6Ydc6c~1dY{f*CGgS$}K zt}U%2B23c5B~l+Yi|+>-z!o`n|oJMg4~O?0x|8`-54*b;JuLIlSTGllTr2 zYkGOCQnoT%*hrI8bg$Fa3G5a&fR3UWs-hK0U!m#s_;l3q+4YCu;$s!XuKv1v5peT& zs$+$lKo6ZGN?@UIsq#wv6r--J^Bbiza8OdCC$L%<*`lNv35 zI5L6SgJkC+iR^?+Ns_o{DY~Cy8FxHJaE#EZpcrc(oc|9wXQ4`C9#KIBmC@DS@@6@v z`N=IgA{40Etu5wJ!Y-{$Uue{7g_i`hkaTpG zmRP@zNa3%Zg%}005JbJGAXiG&Maz}NRe;BJECGi1Lx@@E^(+6Oc+o;LgQY6Z5o|n1 zp2{tPZzu1uRPL|Uz~dC!&pD!Qs&LV_C21W3=UBH-^b|4zrU7Y7(_1LzpI6ah(3~IV z7x7%Y2qE5Br_nn7V`SmxRMw6~5Ge6*5DKJ*Xh$HspJ7F)dXMvzx?qMqhzSIrzH95u z>tvWwJu=>kp7lfFxwEZUd#D^jM&TRPHR5G$j=U8m;5KtCT8XV8m!m|k9w1E-C-Wp$ zI@N1K%QUg;LRMQ z66P6XDiZl!=+V*n zKIG_MXd;aQKbVp;=rckKUy|Us{Mwrzo9@CLCo}aF3K}73hKc2xwmkTxXFyf6W#-6i zxAPy0Lcb6$hJqu?+AhVWizR7viz&%x3gf7?I!sq`WXz>f-6KSo$4HnM3BG$$3Aqpf zoLpS%B|$$=G)+A0s=FZJdG?Q*x$QcQKU`^N3o5(p{DrynVpJ~&eAaCqL-umIBKel+h|K9Vd_cL zIOI;k41(|`Bai6Az&wqgh5K5b8|+@nfA#q#cgM;8i_En~Z~R}#+~;*I7qOh3$pH%~ zWmR-{lk3V4;tVEP=20EQ;gPCUif?32KrmIyZ!0gu_CJ9*A~1=GPG9r-UVQkW-7IkM z@}WbDiMlEm!Oni=NQI@buE6P5%2T)j&ScHKW?1jNM_rIh1s35*MBN9q*^MxJuH-kG z1Jjf`6!4^%{=!{jR(~`_1vKKtas%Zg+xSVA(IA;P-Bvq;E81QM33-rRHqk%})3;q-nxRDP%{gJ{81;O%)orK{YOn)1lmWg#?El0O;K(N z?yye#i)))l>%CMMh!*>*kX>oASL$@co2$`53}f}qd5VX=8W-kwiUGLOpaA?{;L}!o z*4dhanL59u45U4D+Qd^-ru?(eL_UP1B9yL-INdGLY%0g?Zv)-Z2&PVe5QOlZv z>R>u*uZ~K}#T}D@OZo4-My^FG)NtMNUP%Im>9OjGEj1p(w@9DHRfV1GZ!!z5`cK0p zZ=mLH4sMnZ@uJ6}4H}wuvyozMPa{58MZ;77mM|#4h}4sdM|V-VS+3m}(9%YSogNa# zaikG39f-(&N7!QiMcA6TgM|qOVVmd~Y|PXi>~jUf2Q=DQ6P=*?fO0lUR;ZFIp!gPbJv z4pc2;m^Z(&#h8!2+!m9=UudyK8_l)3Yw)p$#lX$ht{AwCZKAu8Md@vbHHlj^Gq^GW zT@-X_usf*X`c!$gIq*vd;x;z=9+VzTjqaNuQ8MU%lP*|9&l(0Yw}LclQ1_zxvx2y# z5L)&M21lcq5Sm3AB?x0yAgFkv{vyf0AI3k!J8ZzqE+z30$%mp{of6ITaYl`|7GSJH ztW?6vVav85PlB(Hkuy$QwGXR=BWwA)-!ec#*{mRgO5;gUE4h@AEKR9(huY3dzO+nK z88cvHKNzpu%iFY()mwjhum^?V!>Rso8T#T0DwiRPHR0WIMnP%TcwaA?e$TGzn{HxT z`qWPG6086`RB?5G5y<)79DjGL8>Mc-cCTll-1)h?v(ducy-Tc?oOwdb8KWe<;W0w3 zaJWxtBgv_JP`}2Yss#JBG2*g%SI@PY+Jo#EouLwDK`mkcgO`sf0`!!xBJHaeE+t=z zU{vv;dT~@=p@L#oM9ZM~FRQ~w#hOkA<0|~;1foH-+$-w4@cv>J(Bk)TN|B37jgYU2~tiC3lg(EMp${4TODCP+>;ffg~uS0!# z<-+kp3^Zy$iR5wX2<#?f+5HDCEBB(nxEE$Y`jKp~X~rC%6pV1o*o~GrKKf7;7~+X9 zyQJVTAvvn~nZ%gh^z*h%0+ak-V5b9LQ!=X=OSw0S>O(kAN|yWtL(}Y`rbQrQ&fFj7 zAUN8P_9=Nm9@d;JNs%}mgu-ytI68oWjpQaUH6*DuKoOQX&L!)L94j(?=zR8;Q2H)z zmOL4iKIJAwro?HL@n2%6QxWOteu}KAKxHmKo?!r^GOQUQ$L$Gr{A@z=_!kAPpGj%Twq)oAX<@PmT-h+(d z+{ut78L?m=QK3S(D%UYf!1b2J<=L(Js}pr zPwg5VR}eR?bv^5j7;e&7_RI%CEQLk%k;@*MqnP$(@nXdu17k}%e>E@afpnC)mGbJ%wsd4YIUjqHXfR04C@F{LcyM2j0j0Uxa!E6MAYKRAp+J zm%{|j8kgyMRC5q%P2DQ{2y{mNhIPWQ?vGmbf-T?ConUe7!He{<8_XBfc_6>%Cw$Hn z_-fvY-O8C;dpV2|XB~R2nk#Y8eq~)H&JoaH+L*f^8|4G4D^O7f)J&;(@PA z>;P;$Q}q_m+hzv0*ldeYoU490XVH|-?P0JhKA1(~W)h^$;~yBM;51@-Cs$#wqwyr2 zb83J6G|1Id5YMf~aYaDB942+m$KTqx@9*+i*1h>5987|k*V`KUs;%v_;iu(24VZqX zxLj>(pHPv7A49ZT_FW;^ICsA&TGic0J$N&j;vG9^OK*9%nPGe`#{`+|KN8IIojx)- z(}aG&QsWdb%d^`FUp$jA@;Hdy@|&AkE?EuIvT>t|e>5U%qxs=KnS~Gk;jLx{dZrKLv1fW{e1Uzl}Pf{1NaR+_bLD0L7Jw)*8#kJPaer?GhDJY00a$(j4NKtEEr*<1Cd~7FzY=2wiKav2~ zYybH}WSa)4E`N)(n_VBz`yufkI0YcLjc{DD60ush#y26af`e&AV>!_3>imTFB9*FS zhN8Sa-1BCy#!-93g!c3`0nX#O;B z6WAA2*&%hR`Mx>mFuW*SBw-Emi?tV{uaY~hqmKi80|JfegLZ3r*PW|Mi(g#adz^yP3euc{2N|*wC1Ila-GK;g@PNx5v2&t^KpBG* zLx`lrA32%q)J(yDQZR^05To4Y)WB-cHmW)Dt|$bOjJFQ!L>d+~vhGik%!Mek6Z_W7 z0*JIDW<-QI6W@LN0nz6gf@k=1DVZoNTbvGlUd}o+QKrY0nxlkH50ty^r1fYuE{$Q^ zaHp(vMau^Pnt&qCM#7=4@u^JRD5T{}FC^}=g6rC?H#zz3i6(c(kY-0wMm`*ng&S9n z=W$p!+lyRnq98_R!h{T)!8ig$x{k~V`g>Hyg{U1(@OIv9y~>E<{)TZN zMl%rlWo7!X?Zf#eIk!N2FJ9d#xYAZ_>xU!D)J9&${`1D%e!P-q#uzH z!F}@QH%!ln`oYl`JB7PDU}NQqH|}M0T{#11h=N8!rD&<`z)w~L%s)QrU-hi5dA&EApfcP6+BAYI zKQwk^e5>Y}-RseWOF{}y{$7y>yL#AG{o})o8+!inVUe?&Xc$T=8@eo&7aHGun8vg5 zP_8?1NMJr@)BvIM2e$(qoyd8Rm~K|e)SPJlT2&5s76TNWaxScKdF3~L>n-} z-Ou~m7sms@@f;T8%cE`bOC!-jMJl4&GK|S+XhoYiz;!8Lnq7;$wkZ<<(C2F0*xUwA z>Qf1Nok!86?}WHZBXlPb1Qulb?S_Q}`wo`2rd8)=OXq9Dv}m6D0sNk}o7!whC9$q% z-q1BXeODG|vNW`7ceH%F_zU%WONmI(l32=MX+X5+4(`71Ss5;Qv0zYt z^GI>RPuWBZ8fvPlI+bUjewe+E{2t){EWWSpEkGCLjuDOLxs*5!i_d}IXRI^S?_ORb z%YS)zj_mH4Zh;=1u-PVW4xm5XiR>!c@p=Fhvn{7zs{T=*K6ho)qy_SoC$KX?;K zlS6-`+f53=Ay8p2(A{3G*k_@=>whmi^V)%dtup0J>FqDsk<^JH)H>n+e(h`@m2Qyi zZyPnEzTr04V%af-Q#Z9QT;H*Oo%>>z(Zw>-eStB4t7mnx7;Qf?c%r>YQQPja@o{XK zWhzv*&UMebDsVqzgfnI5bxbf}UCuvY!oHlj(A=_;%WB*3Iz?;StO?pl3us-3m>5>| zqSgwmG8Ni>pUEz(FFUCJ&wv-NnC=i9veKM`j8dGm51zw9qx&w&><+rd>; z4>R$&qGnjl467{}1Atw4PC;}762d9NiQq206?;faod}Chz0>Zaqt2@imC44mR4;$k z{`5c|SwAb_9WZ*aSYAb@2{sOh7@7AW8g$kl|GH$~cg$ifo1YOOk&k#4CYKW@Q!6W)1TOSMCXT%82f?)8E6WmgAQyhYXB;yB+@)Eh!Nn~OJ@ zDbR0F8`AEA2|>^(!t4^KJK3kq6@{J$l12wZGgJDDj?QDNE6=Bx-Erl&QQF3JNO#R- zb?Kn~z4RP`j{{Sz9Ot@bUu4RV8Xym254 z?mT`*yAuV{_#TcZ=z+nID>*6G=J2}(0SBwIK>7u`lv+4(pTCXvmZ|s~!_}6uY7thR zE0Y;c8mYhFk=|vu195Fs9ZX{9ZV<4XprjE)$sFlDuqFdC%p;N;IF;AZ*QPVY|NN!dJ+Ss~!;%Y~7|QFU z76N&v?P5UeDf~dG0#M`*r+eVmX?ZRMC3A!)? zFU6-V5K{^3J>V15h^sPGwnpf=fTK3fjgukE>OGV+_9=5SRhFM8T_lQPR(=(qJny1b zQz7gXiJFsOHd46ehJ&qpu7a33nqzz4wtrx^aH(o5@Eur1ny{wM-y^EKvV}!ma9W)s z+wk}11?qHYT96fReDhCsH2Q~~%7%G|^CxuDy{`^$z^u4u?trOfm&rA4pIKW6vF9oOs6%t=jhrleDE&zGIGbL}sZ2-~x<2TqF0S$& z;Q;iQBX9Iyy9F;O!E1VMM~w=$a#vFsZYrfpKgnahUs|cl>Kb zKQvN>kzX1G-U;_I5y~ZF7I{IMT)J%794|`LsZ=bAsIuYg8`4^PLy$FgEr=~|VOjAsb zBH6Kisy6z&G1AZB?Q6YU=MF}pU!-bwLS%`4^H;a45CojsdvB+d28~feZq~xyFtXpU zwU{Jd_eF#8_Y-Mly{llT+J!R|_NEVfnP|LJUJVg7Rblc&XK2c81N*gA$~7kg)=8?_ z{gE(P`HXukHK70HTLTe!N(79vu<~2euS*>Xqp36W~Y6?)>WrOKd-P^XzT9UoZvG=P5J-E}}q-Lnt zqA${GkI5NiDOc4{x;cLLhwpJz+p%aqqTI6pQ6%9>+*$atZ@jd zs42TrW?tW1HVqDBa0kN({>$d-$CGm$8<)Iujs`jyk+E;<1NRF9ZnlR9I*#RP=eVm{ zonE&h{CW}d(Ys9`qzBAPn7M@FZzgyNF?9Hhf+SO6MXTdOrS@?JCH_EL@whLV21c25 z#rvx2bp+JPEEKJz@&VbsQ%R#_;Q27;AQS!KMrjOR z>`_jN^V3x=6BlXAr=}P`^_x+S9J(BPSJ`R6b2PEKQc_IaQ%!AUjn#sxK3`v8N}D&| zsi@NLZ2i6j)n=3xk(~`XKH*^qn9dd?qM(viq*M{QQfiCNBFH=CF0Dd?)A|JH2~&z6 z@`yH6ZmL3{WnQSrl}hzFIwXgF$vBolPF-CQkB{%V9px|T(N3~757cC3lW1Mvyx@0Tx*~?2phz z*D>KSer-IMAy&mImDbRv7PS3rHB#GVc#2<5uS`AO-DQPTS5y~7_wjdp9axWLoR<|U z*}2_SoEwvDH>a4y;8QOeGi0rm&e`0g&16KN6pd|NaSWwkvLXvhIO0g*dBZ~eLby#8 z_YLeU&A4UO;LV;ftrIwq9_cK&>D43*B6`prz^scQd+tgFmQ(7=`;j^nbu;rHL`%V- z@U$8dcBnFtdt=~kz}*A^;_k4_Cok3-*Iw`wTYmqCUa_u{bCJZ$&w6YvI!Q1K!R0YT zfHIF%)rj!{5kTPGCX&U?Gvo6>^+DYmG2>81P3Yl@+khxG$ZKJbNF{#F` zt4+mNG*zjNcApSOx7tRk6heWrdaZC5K4;{2%9_%GnPU&X~IiGp`yIe>#V@eT?AS z(5pM@T?9)?X$&)U6W3ZJ#;q$nE2brL-=gnA?@ti&YHD5z3TrDAtcw!WZFOimYxo6$ z3i+f(YBQ~Tf)8-|-2znH^O2VZdT)IULv!iwZKZSzTwR>R!ff3l1GCLeMw}!o5}`RQ z1zDP*_wSuLGX`mHwq5_${R|cPqlgNiiP5w;h7DUL;KO0*10k>JwQJ)(Gn!304=aP- z;MK#03vp3T>KqTOYM7hn(Bujx7&EJe)>sY!e z>6VxAhzr}P;w{P8s<6G?Z}P6jwpf#i{Oh4xfiT>=)uzM>866Q3EPjMRgeAmm&A(Vxo)sE`Fn1C~ggQCQEHQ!;_iR zde9}eK%;Vgi2hVZw`AZ@IFda&nf`wU90qRMktnA+UF!bbF%w-es@VQ(~l;l%A8+@yNqb&H_yV)ogzMPj*4Z9qO#2 zu8~&p&p!v7;F5jb=GB%7S&Ed##p6gx=rBW+vfjWR_0Kcd8RvIqyFJpR7@`c-*^^VX+JiHT*Ic^Ho5h*D`+|04UL8AW6TY! zKhuohlU`E=ODX5Ec$2UEohUfiV0>Lor25(*?Qh~syI2n<&bWoP5~H67EaR%5NrmkK z3|2hhAakj7W)FQ(aU%|>oaYS3e2Pzl`gLwEK7#XR)oQRig1@ipZGa~gfbqcXez_hR zK&sKweP3X+H0A9XhMNrixBR6UU54J!G>J6~ND(~FI#H(7A=V8=Lat^GY!H3%HBTc1 zQ{6RndW6C-AD=6eC_m6N0Tiyr$DyM)pW7hl3qtyAO*sS;LUUPH8s>Fika zjW|PEeVq!gj;k4%27zV`-1NxB43*=RLIODQm10nD%#MBc9Db45c3;c%wZ!S~%-wxG zcsg}WVI_OY;%faZ$e9R6-|>)7tPX?BXraI%!E(htN@h3_yNQYK_&KYyw{8jjNZ{l-X1!#jAcJz-!^ayH{4W-UYrBV303BvSl$@>&(msYAgsMjL&PZmYeBw5tI$uS)g%)SY z*i0R!j{*l0LkCK;ox?4HrnBX=tD(Qr0T80dI34Bfx8L4Y4B`#KC{WVa)N-Mrh+-!~ zQ^qh4z+Jj*8lx?4OF^`yj$B?TS`-EH8O#IdV^Qeu+C)MEq0dFB23;pdULav%sb+xWpC1(%BPJgM88}Ey7Nmr?# zgRLNAh>3uT3VzZcQy5c53daQh+M4IHJEf6+y33jyQMq%)s67}A(oFOjWJHehD98Hq zi%B%c$@CJjInl5*K#!QQvq~6WT{uES&Vm-^i@ph-*+qH@C1Z0CC{we1slD3H4|S9z zqWrLbpG4cia5k{WG4@W$o)En;Lrzq$VNzXc0;hpRU^HEmV&`&9?D*-6aR3zv=Ud>4 zEh3wL29xtCiOe(Vts~v1&_0NXcx8p>co~P@gzWto-PEr`y9qnwm|vHI?#6Z-5vusUIg7rH++a)!-G(75`$Yr<)>pMi63 zOV~V${(MO)R9tAdq$vi8^qG@RFZH2fF4Jo9Vf#ayv7xrI#;!ih`qd&=5lOKtV^zaj z&7#oP!ZXCAv{@LF>2c$tvzG?O)~DEH z^Z1^uK%#Y&O=@9KK?eB}!0tZ2gDNgq3t8gFDYL45C)w>fl0YbUHQ3eQ7pXP*=Tzl= zG>-1N3kH9SbqTUU)wtM=qpV5{s1f zhJi0OlweB%CjPM=1SI7OKMGbdA@wmj9alxcw1rE&gnY9h;_pAoN|Y|JEJSc|^k8OG zM8-Z%)mC16rppfs40^hLN)K6{%4jI0Gviab?wxba6X7kVNitA#!=uZu&Pw>tF43!K z*EmD}+}LK6|D`J?P2sUf2i%B-n8*C!fct6|70>oig^eo2HK$46f0}lU`9JyU5=6pU3BRAt`M}umAob?B~pH{`a#|g211Z8vfTG zA3+T7?x59V?)8xOAHNO&`|MVPf<+4xnvR~SkTbbFUdSI(qez{;U5!srzCQ3c++!5& zE@%^$m-eLzT%o>a5Pq1LS~oP_LjCr$iTur6{GedYJ45H1rs|2W>9evDFH4CzoV>qd zQSX}Pv8ka+!H@uCf<+^w=Y-FUT`B=6cU^?z7QHWd&Bj(v_xtK9KLyc%yoObP-wz6e*j&B6UP_*S`3L8AGe5d1a(pA0X?@1O6Nf5N;v zAp5@F4a@+Sm0bhh{?yG1ec#gt0Org1`m(ZS93RV1Y{tiNM#}z&B7MZ2v^Bhd#hkP1 zwF3)hPNDB5n#-@z8*pVf+c74l=zOIM#ee#gPUd*0q#(Oh3A{wPRx@POVKS9|qLM4Q zOU2rLnrN42VZ@6N3s}o)osf+@T}MEft~_=hny?5xaXO0VHidjt4O`QA@PV$)=Ou)w zbOTjYzC*e@>xuwPG=igy(A?%DT=ysY!!`AHa&kP11Qr)QErjy>!is(ooE~xAmF`yF zvpUF`IY+egWDcY5ufK`kj*q^dkrc8dZ{3kcEla*-omKXjLx8UMUSRp|eDOwQ@;o7h zHSAg{f_#C?`0E-?&hK3CAmGBBA8?UKP(-TGmC!C>nd!G=&?gQ4R2dj&&9t5-R`x!X zDM-SQp0p{x8_vdfXhz))LdZ6SlEa>nl5|a=>q07%i7axCkwPZaj~OTK29lcFDQW~g z)F>Cza~zr!t0v;v88X#nH$)I~%o&r$#+{2QF`5uJbqA~|u`PN^lGm0iEsRx=DUydv zUI$siJ|cewV9ZWWm6IjJt0J5SK@MR>oyR!j{TY5x2T4tY{U*x5Etqap z_(Up?X0WZNW+t3Aai$T?D>DQ;VEN?u9SZXazZLXjZN}WW1=p-obp01&T_K8op64`w zRjj##v0TW*OMoZP+TUE>5lOu~`IJ7LT(L_>ikQ?${Ja#X0~6(4#3bm~)9~2~IxA*W zEztp0KT=SaA&&IwWwrJ5^;7BS`^4_l%uSiewupKOf)LT51iZV#w%ptGKaa4+Pk+oh z)!;ugI3v2ddL?SrK0Ixb(m<3ofOYgSA43Uo9%}EiwAOO9jQwE7FADfFGYx*M7N+#I zyLM36@wPoUkGWFBs}(^OM6!2Xp48?`ch2fk%em(}l@whK5e9c{U16i#y5h*6nyUHQ=SK~!t<|$ItMD!{LczU$+9XkS z5FWdnr^CM#v!`uo*znYFm?f)}!>*6engR{V9n`j*ioyn+&%7e z^L(bQt?<`YZk8K4_PcfOgvp0ne)_ItxRhpN{%qUzG8!#JcRbY7hnJ4^@$R5$TlQKc z+d&NG{<8>+7%n=4jsK~AI0x%&jrAC+s1IC7*R%)MVSCoqqngXxuYEbq`D`>mlIB#q z8iMlFwW{#8m}aPWHW?F!OuxMMbh`&akK6Jav3GWQJ~Y{gu!?;&1qRX0M%{;Ert1da z@jCbn@R)xARPAeq0K#00CfKe$+oukAD(?WVXCnmCGyLD}H-5RFNFS|{;4jlNfUZ0M z|L5TxpcMX7f2`5yO&*wF@SE~GK=MS)?RW-wf5G`VodTR50Jb0eb^wbHejLEe#tk5O z+GPxE@A$9$55eSmzKm?ZQ6<==QOH8^NgSm&eeJca6y|~^PiVQ8Zy{MN<~OTR8qxC* zRa>)LVac8WS~0OwJ(!-M+)8_cOQg#nhJ-q;Ajms9%uSB9k~6P?CU=jT>;iWk=I?q- z(}%QUUgblR^zh`(1}*1~YvLJGnS{->r;QTYCIT0&zh?$7o>eNXhxXRx^XY3+G8D`9 z>$lNly)}-(A$~~K-&0PWYB)j*ibOv}I_m^F9xS-@6-ZE-u}keP@mooz1PF?XYNEn8 zWD?rc|Io^#pU{ZVoG1-7zZNh1y9cY(9Oo)UdNPK&hO%*AM8Am zj6R)EBMXn`V@RRP4gI}R1R{fX3Z$>wLY)XE!*;h$sWWknw8Yx|o&^#=us^%KQ#?Jj zY)XdNhQ1djL<>G(kMRDf+>$!EJ1VrC3dzaX*;ej{H7^3k;WWN{T#2MQ0PR)WQn&8yG1DM$c%r zQ|_vIRtU~jS2MF}(8rD;*&qUsoa0pbp#5f4nRdB^^)*uGX>aOiqK@wUB2R>Vf)rg2 zptRUPX-hUf9StEx*l7I4^D9q*>@Yw!j6WobTaTJ7j~s`hI#N|)Ed8yn;mkmI zO`i3~IC6$8qh_9584TO;mqt%-#Wk+=_kd2iJT;oJ$`tfN`I&0i(&N;R24xNVXhDUf z1;r`>8>6H!^2?E~Mi36HxzI8a0scNOc`>L+hy(nr z8HNR$eGo)%K%;Aj1|n$vSj%ossb>l!$cUx83~@o%d(=p`#l(z0x-$jGe3ffHOR>CGY%@%X}y%zx-#4RF3onJQ;rTP z;Mw*ge$el+bnNbujt+%`;JE}tKjW-mXpkvBu^C(eL-hp4LUp-&eMLO{0v+)X_el&B z*A{i*uI)Ql3A*>MHfrr1gDJI)eBqB-+gEF7t)s`IZ#ymv1>+5IZh72s%ABg=&Di#i z3onxw+aotDvYu5#GpvaR<|%xCJ&+JZe`-}EJ^gigJUi_sH-;PZGgo7?u1%g=WT?7J!d;%tf{{kGf8&($t!R4i4R4UR)onA zGT#1LWsxvz1u-3+KZRA&BVV0L=@zk+8@|s~;jg7Mbd$FOcgM`%!0*ksO$P(cT1LmA zhsrvQ^+_y!1zsw4LV-kheB@VYu@WSXaU5d@Kf)$&&1jZS7{=3^isDXc0E`(1XfCh- zn|wn0EkjWG+tsZlT??*-^`E@?Otdu|X67fZAXqysw~l?s-Cc+Lo7DCdCd zm@_oy$l^{jZ5s)sDVpCL-sYl9g#JMAGe)YWgJtaCjS-Z$z!nb0QfdRUf8~oe3_|k7 z=lAX4Q>$J@6H4+?h>w3+>%S~rLx3a!Anbu zq91uU38z$0DQG|-I~YURUoI0b)7ATC1JeLBPBY| z-C7gw%atw_!dw19l<`ga){5|TOt3+7!(H<*FAz4BS`GuZp*_;UII$ju8koX22y}Z7 z-dt&af~;#dQ#;0yim1Zl?TK`9qC~U`oT1wfqK+GB9+tG_ILQ||URQ@E9VR-HOz>fH zkA7jlbC+&rs}#WG{;VWp#^M=QHzt@2h+G<3ScS(goKX35ld{DmPdeh3T$-R3=l>vR z|MTr(PoIvQ_LtK72Vs;)1Pqdb8*RJ-LYP4{bobDXc0j{ACz{0tmV)~Xn=g}<<6;ko8NrERg2QE$)eb~9#}%>MNTwXHt1j>9iMYY z&9Wvu1d$u;41r6EKYCAzk4W?89mzqWpsQcAr=>{HQmcQKA-#QtX4o1+gqQX%ytIyw z=a9!=bugZ=*=b)aomCl93vy7+1q-j<1Q*!_+T7}p1YWzpdfq)^|723DU8sAL8$ha_ zh<*hQ0L;$-?hi{t0s2FYMqhs4x0g8EfNdVP834(`^$Eb^t!fXTe#`RVHvrgy0O+Sg zh+&E;eAGreMu|f*KJFhyCeVM882fe@9cNQfuxDMA`XW!zsPAn?>4RlQ6goZB*QC6U zdPX&re;?mKjCJ4p`}Dg{Z4(r8b!5aps=8Hif-UODx>4>aa~a~gvNoY*Wm%PY+I|$- zHXIuhB|geJGy>RP3QKs*S`PjW3>5TPY+pK!h1nK6pZ>M-s;PEBy{3f`#vo4jmdsPG zwJsMrXC?ZPfL4x;0l~N~`}im+ZFr&I)7tvp9O9@f%Jx%ya=tt>`WoZVglQWMIi9NK zfG3l5;T0?9!BRt4mqzd?<9ZxQQ1c;_aNmZVTh0+K7ixA&USrgaUp!qc;%b4&fHZS4 z?BG?xvy=}(ue7w3itd1Mdv!CQi1~#fIgx=P z6qmaIX+rPF8Bbw2N)Z{_9AQ}mHa9D3K*11}gQrR)RHGQ4F%rW(WV>Awv=OdoyUgLB zYA_OK(uCqv+|U(t91OZv`DAxgY~5xtg9snR|7^u;Yxg~%#H#KAk$Sp2wF&z$F~sN| zC;D)jAGV$<=RmY-jBk3gXrUcJrN89YuWloK+5B$WhDB^vR4foD0<5H76Vk}0>9JdV zaVTRMF9}FXmnX-{rvSed@TtYlR&yx4z|t>&H6l@29T%g2`H)&pkZ+ zETT`eG^ci~-m1}7Etgv(YEX-!w*sLBclp(3*qJqiQ{?IbMa?)8~@u%-)Ekx9hzcWi|&w_mX7}TpX z!T$9}6S(_sIs4)t7F9QDysSP)0x-lXQOz_BLft#O9E)p&iV5Cq(m&mo*fNL!p9TQh z_A8LsGV(*>akJ>6k2v{((oAg3TzT2QrDRDz82PStv&FX13Ld*l!$yP!Z zhzYT;jHHxu#VRGs7mHNdJ*A4J`tRx-2{k=P{*v=qYCG2nD>vQah3J)Tm!;x~m~6*| zobee%2Ufgp*c?9AIXYlbLf-UKOB(LaR33Y0lH$CzWs%~DFyMQp!Z#*(WQ`jr_H{{@2!97K8qna}BN{!K&@iZKkbr&g4b3P?&8f;ljfm(`X+FD`eqXkGC( z3dW$AQs!dT%t9A~(+Fv3#K!5(D=J4^0?>A6h|w*S;$VaM9u z)?1->TW<=~dU^cNGCz5#BdRA4Ju+9Nu1?P z$>Qc)qLgn|j^z%#V5qY}*V!&uAT)j9MHTN^;3#3|5!0bc1$<^hT$F> z#kK8?sO!E2;o=Wv{vpW@|Ej1Xv^M+ey-c%P?H}xFY6y&w)ZxhS2G`HOH7gkZ((3f| zJ@vFI1#JZ29R&PuNu*i+M(!B0_oa)=eP8qvJpVP@h#pL0l!Q*|i2$>KAq_9WI_8m{ z8HBAGB#W87MzbQ_|x*=FityVv~N>-YhH5E1|X)A6LfsD*svM68he? zdaQa$#igBzJJM2Rz9W(_KQ{EIF^fJQdlIi1fVHCOE*ppd8dkl0O@!ogtE)vC5p0!e z&2Z}MbN}4h!d~EVhK{DarguP6l5BIp%FDQ2*o_r!zFw-=h?kF); zCaP&xtaUF~0MrRQ3+HjIX<$0sGg%`$VH#Mmq;R~x8-qx(;^*|jS@cq6Y@9kpHo1VO zNTOUWM~G6!Vo2lE`Y7~RZl+N<>>-Z37pBGSiSF(GILa|mzCrsSfeN-knl6J)wOg6x zA>$oQpyeh5lrF8~LH6RAgI~q*-eWrWIqZVH7R-(avk@Bw#F24$qK-?+LKR=0cXlzx z98JV%ku-zgzb?#11=BAy;wA(0nX}r(_9f|kMg2KqkB_J=h-XfMHti{)*oowa$urU) z`D`|bCTGATBk9`#bqHl5EVqoI8|O=eoN?>lg@%1*;<j?Y`gjywl4a-|QYc**Bn!?Ar`Y4h66{1o&t8byFF* z!>)a_NfD|}Pa^td6AYii(}wTpEY#9*;}mlR2G&%kOxalx?-NI5e9((#^82@*R8d|c zQ6R6qO;J!z>FcV^(ImWwngV zR4JLM5=v7=1ZD1sPH#m77ENXN+k1XR_`32?S5{>DvCV4oP&HLVh1SnC!;4Ep)|Q5B z|8upBjPzDkjEpK7`|L6Vt@B8qQc{W5qA1c}b2YA1R!#H0)GySD1TMA;zwPcP zs2Z4(WAddycYiYHzEpNTM$0dEiHAiH77QpCa7gRBlRfv`UtbU4YBnT}GpN%F7YEi> zNEPYDyr6EW?UhHZktA7vBZ@PLXye4=EbgOjnH%UW^EAL*3vT+hOjqO@se?L~|3E7m zJO%~~tWEn3rD2>|D`Q%8fcq&*N4MlmfYd!Ih{Rb#=86>RV`xw*7f5!hozr}URSuZD zuW`a27n(n9#*?QW`YT_9jc50h;@JXxU$p=~#|~T90yYZ6l6(IAQ?T$qj?um2aA?O- zz0}R0(jn&>&$Z)YE-x>@xja4Y-$xzPyjm*GE#+)mDp_{4vJ2I0y10eT5XHX9WFTFg zD?RUPkc|qK$N95i-7;jLHoyRZ<(Cm`&oq=;9~rN?Az|YuhHrd zV9W4xXFpO$)_I#{V)ngUW5^SfU3=qPG;qxst~QI#-X#gF#+YfCYu(pUbd#{Wk4i|M z{qWi*b5zR|7T3Fv*$+>wP(AEk0K1I)_dNw-u72k`hH%+=CfXFmiRZ{1Zzdy+6Xxe;NF4y zRoHpg2!l7D1qRi8eoSbf#}#7!zKDr2JtrfmPL|Y`T+-zg>7b1^QJxo-x|G|C*ZU4K zWnvmm8`8O79f4w%{j*Y8V7+t+$tPpri*elR{bN**9c2dmZu$EmTuaO8wPm%)wN%Bc zf+DDR;ze^7S@4X?1Y7|HHA`?M(Ou{(lDX9o)w)sw-|@<%B4vJA7n!_@hK&e6v)ZQg z(3`manPFJErH3+V^3xVr*GxKJe3K#Ufbw7A;To>o@d;5>*dz1p%qz2Bmt+!gr#xd@nS!1 zb9{#>VPp)-(lq4tivKX1_}JkI50T1W)YD2K2XwCI#`|?|piE-_{zNYfdj%#kS9-8@I}Pd304q{(tr#c7H;CS$|;4 zS_F5v+q@&`PgLt|=o3%+>%L(;PH7=ecT_I6goLf>8ubQ0F*V+?p zcmbxTxu3O?N(cR~F(~~O!&#jjGrGGVS3CtTA-d;R6J-+BYB)FeT=X< zJ(;Zr9^-bmw+(GKu+nQ9XAjTyNQ4AE!j1&5!c$N-gBB!SJADdz)1KMLy&Bx8)mh3k z1$3)L>w>P?<$UndGspBGsXR4@Z-BUSL13b-T5~vhH;&5sV%N zyEz!rtyybYR_ z5)oZ#HvGf^ZMcK~esvcauA^0sMXvL~b{16Mlq^pFvN6=3rFsJA68cINQ!h6)uYSoU zhK)i*T(Pe8tij0)!^Gg};igcgn9>*vTefZfG$QrAH5*;nb5;*9I$XUhGi{bsT96 zvDP)-!dt9#{xBE|y0^ofCzeOSjiVkf+B1Yf^~G{9^~jvCtP`6o{u zz95EJ6R5+1iKT1pWs)ASI$5WovSy6dtSOLO1()x=JKJ3k06b2$0r>1L0afm*)&RfW z&ad-nTaL+|;TG@k*{w}L9=Ff)XNeuaZ+-12YN*DtUIASz5GPCyIR5*ZcYe;J$F{SLOa2FgpTx zVEg2YK)@+IaG*iCkkIS>!s^0_n_F$-N(sFMr|lBj5f%>K9n4-zz1|6FGZ!h18Js+; z=}dCe&6*Gp3UxYzK7G9Mh0B{$aZiG#JO=lcth-jWBmqF1FN; z+jc33PpSFkJwpTj@gUezHpY7qanP=JShAqhgoqQG)li>asYf z>j795t{QYd)~MspOZ6GIlB~3N(Ou-wJ9>dN?ZSCE>$cCw`PTRLrckGK>R9ojo8CG8 zb&to3=ZAgUSbh)#k9zk#XYlnTdN6xf9YQLIQ48XQI`27^|IxH{d2jDl(1Eu+O1h_( zbq<#wW_#4NlBhdvnv4W6vlbM4f(6SY%as;#=1!|ojLckURZPA4WXuCq{3HS7Yv0k& zzTBS2=&t=hWgtc~2Vx&uP?PBk5?qj3rZ^(@sxZGZRf7jKyeK6#I-#~Oq?*Ci&@%#J3&cHJOK$y=dUs0!#7xpCN zKG1jN{+(+QDu1ro^FTjZ@}X>PUQ{IWj5KO3uXlDB7M8*TJ(-=olm}e=j{oKtj_3rA z^-SrDPdgAPjATNuff-db<66m8&+=^9vQGs`k%8U^(ks`6^z*1|=%n4V*;>%?nDmM@ z8C$+xB1<0pkDbw&)bqsDMk>rNK=Ueq*;&~Tx02rij=l~&>lsr}w?55EE-bmHz%rxi z+=W6+{At<;K=Y|W_Za_<-IpVJd>vjaqo=AP6)QLkDdptQM?(KQ?0T$`n_HEbED5Ev zKa2w{W{`c;CrVanF^tQ8=8!owfTAvH>TwHI)N*oHxEY>2=34TE@N;hYGhlyb63eLh zI6FT-pW0>5l&hRNyCR6FVqTA_E;7vktHUUmwvD(BCY{JyT&#*B6)Q)VqV$*~gVB_D| zBWLg^};sbDZG@^VpAuA?F$pIa%r`IDhCX^tW*!6;X`$9^fL`YYq;V|Jr)vvEr?!?NUn zOh!n`Mvs^_(U{w=tgoA-Z_=GHu74e5=mNN_PAGAU^!1s$GuykBak?e<{l9-RbEwj! zQcDQvZEGGk)=^U-abli=;pAVQ3kX$ken*?JjR&x*)svLvio2xal_xhjB>e>*balf} zPzCR$o-IX}%doI?P??!bz_Zybc9{BkH@Q|?4xD9(M;9_G2~r@0@Eg!R$>`mae23j& z8f#aaxo}Q#uh@P8>bUwJduAFM(Ro`d{0tKGdwpy-8a}199+kQ}fMbBl6Rbcqfi3ww z^^*q0@fCyxLab`R;Pzdkyl@yp^0}JeI?5rVVgPB$xNkhV3mCLs zwG+s~RJ!S0EZ4{LG&A?$$M*!Z?dSxIS0vyGCmnu!JTj8~!`&B&qX{Vwxr)o_Ki%^V z4S+S;E2q#AFiuQ!(khXtV}J9sCDWT_Wx+d`T69OHI^CagjLzTXmn$@;X~R?@y>&@V zJr$SkuaU%QBL22Y37iADI+Igzl$rf*GSz_kN@dxBMk=DJ-2$gUnn1a;6!}Z78!`Ly zx=XnqabDa*Y&JqWD>dr^mRy+GbWBt+kotJ`2dhk-P3!L+?lKr~uSgL^Tx&DPIfRf) zxgu)opJ-!>u9r_RV(P^|pYwF?zDh0=gNQzT2Qdc@T%UjcXP(^?C99bS`E0dOf+=St z86O%lcv20btP%V*JiK}=IV2cVJ;glql8hw^=kJf?!=zw0r^(f1cU;g zRd=@4b&E{3*Q0#14-W~lF1dU-ulT9I>jDH@!bJ1-f#2LFPTtAt4`a~h{H+_B6TEO_ zB#H+vhzbUsAQ6XxYxs*K4=K7_Q{omz#duwCMx%E67~}1X`gV3|2!+{Rt>6Ba2G&m2-3ILf%?vs$Igc$4%tsR1KSDZvQDpz;_d*`SLc0X(=v#%MoJDQPV zgE$>J4e1#20PIT1l3|h*05uZ>^Zn(I7v)<>zD#zY^Q?j%^pZGJh>)w&Fe&JjBHgcD zTtuzBai7(nk#^259+n5Y1;{RCWwR()Tz1rGM7qIIRFK5SK^{#!)E(Wb+-{r137z2v|MS9j42iT#s&YL1^vT87Eu^m)YHTvcuGc1 z8&CkJTqu6fo(AkC1~d%@rXQHr3CsCD0x}HVV7t4tCM5{6twAoa8hGI3=qvJTVZvEt z2#4R#KzqP51Ipiy?{Q3*lO%WLWOrcmD}?<^d=0c;teeV*)yfh-`xRg&KwFCy#gibZ z7wONa#AS2DakZnm)gKoH)yIvKfkFh<;~-NTP>07w2NoI=Z*1gug|8F*7QI3Yf1BNL z$#SQYu8ZNI+?Aw7u1k?Ea^mq>`IVz#(dXyBvfZ^`6xvxT%D1 zMxo>|+8fX30>p#R$?dFKMTdAt1bLyG5PLD;+v5@*8gpkp7murVfh^)!afjn zJ1^rY5c{I|-$Lnc)V1uI)JU^>S4P5McB4WfOpcLxZqp?ha_YJCYbpkfnEfqD6_9`pc=cp{RnZud1Ld4 zAx+QI=JgVgGJ0)HRzo|Som+xlLex>UJ(EHZ!)lQ45^z$HYLE)4Npxj; zq-LIK3+ASwQ-PyDA2u)U-H8ETnY-C5sM<+`0|;bwiI4&!PQr6jQzA5tE#9aI^_;O| zSILR#gC8WCdMUGCI4{HGs2tz7dL{sZZ}W{Wm*?$l7@(qz-adv;E^~9@L-Vy zut1x=%Jn-kT{HISsGFsF_EY$t#gO}a&*SSczvrvjx47qHeao|@1tcY99d+l!yE38P z6=o2{`)$R8r?cGRm}{^*bfd~9;eYqs`u!|Fz8THSe7~XguzmTqbM)PQF+=;%^Z3r| zdA;L={ILC=Et|#uFK-+Kuzv2~o&cnqI;TN5;6fEj#fYg@OsJ<3Dp9O99K;oly%+Jx zN8NJCAIX@4(d9&Hh}w&l46pg^b2oq}Uy1`g<73=vIRuTSNg3Ggd(itx7m8Bj z>TL^`Iwuo4ygik#go)EatG9n#&yW9H&nj)DwhD&6*~SpKwA(;O%)BhA5vpHmCk8E~ z|Eh}hj|eqV)XtA=pME75+pz9VjRk~T*`blmV`+05;M=oV9!$76gR6Z?vdFt-Z_UAX zasMoZLt<7)H#UlPpsr*nrkG`t8#$aKIWH%gIF*^cetru7z1H zAA*un6q7g^ly8v^%akHeZX-vwEU__R2kq-0 zHL*ANbQIZPHB}v)^FK}r*%M~0DMfiMSa4L4G$!(NjTAQ#JyC6U%O)hydsv*5_bqC* zU7F9ww#bf*$LAtJUxbh{?p$$20Ta^GHURweDJk6LuA|1{Ul&?ZHmhA?DwWUU)-|ZEX)GX$$AKuIfjY%E&I~ z#b5(2wd9HoZMbn*rxN&QJ6AbiwTbOCP3mU7LtBdQtnaKW`gFfgRd*9<#0l;qT@#$axPp_fTAy`!0U{6}mBB`!h!!$E4z zE2nwd#Zf0!JgY71xUqUM1dER6P>1NCAnQC44Ss6kx6NA^0WcaR0pr&CxHostztLjE!3-zV1n4lV#Gi=}ka(zlnI4ukqgr%6%$X@l8w6b>}#; zwKZjVZoCG)dSiELD?FB7c~jn;k+%K&rP%Uvzibl&EW2rVl7sI#v(wVrV|gr904%+c zbJ!w3paU)pR2HN)1X>g*ujSpd(G%6GvPrw`Z-b5>xrOHUGQ>A|S;F~j(k37KqWP!H zH24o0@6Nuche+baF}vC(3yR?KO2$n;c%~ovrn&DXGeF%`>Pv&JvtcE>wx#>I+97G$ z&eox7I#JQ)ZFHGUovn65>kZnv>Qni${Iif8pks=EMM={hV!5=s!NWuUkK=8W_BumF zYI2?BX><8mzD3s-gJ(uA2XuK;Bw1?xU(kh#f{0^c z$@YIhm-qi0bdk3De}gVj-v5Cv_WwUX7i+!V{4i;pd@J1bfYcm2~Hrg7OCz02^g?W>zUpreRGYmcU(-6N%ZMjpaQMV#EA9M z$>_!fDJyW2Zo7Ip9~ZJ3(B4>=NTW8Ukyz!MP+r+Z2lhEmrmHM>LXRf9A}X$h5}jnb z%dTy}m&%Sq_bz$sE*HJ{qv{nEy!IJ**U@6qZjci#&N})|Nk&*D+8q{+!}+891mri8 z9b{L-BnM~&X>N<%tKxIP#`yj%PQAT`u?5{*=ift@m%!(g?J*s{NFCc=jE;Jywp?Vt zX?hXA$Ki1fE?U~1u_mI*a!IVGM=&m1Sb?l!th1VdWdDS^vkh5vVXIFd=yE3h4fs>J zsSYkw3wQb%!vO||g3hEw9ooWA7Wsdg9lMjwQb*K-3VH7|*_kDytqxV1NhAVa=Ybd=u(mf!Z#p>BQYLhj2Qr72B;hS<;<7}5T`bO7*oEXtD&U*D4Ba9=Q~*@k-Mmj(Gaxz1xd?o$?|{SJ9cQs zY#xGTg-H#M_L_so{>j`eD14;eJg2*9xtTuYj_JnbYPDvEKMGiC4MlcVwKA2EWn=qcC6)2 zJ!D|=A_&EUA1PoN2{#ZF9A?xIzlBqqV0hemj&n2tAW7L?PKC?fdpki}dXN2o<&&J}E!yK^sB2q zev{H_1=j9nI++J_^>`#L?^%%nV z#Q3>#rnOjSOt69a`-Xx<%cf!(@B9N1e%OR$hiHFnjfe?15Kt0Jc!jc+(?oreS97@Iatt9)_A@Qm(un>GIzvuf0gi1)FO@KVcsE0 z@gC7-^Ypp0B&oAc!8ahN4%~~kCh;r=gOTFN5wc3UE^b2QLU@?KUrBNxQ=yGxC>ILG zu#&~oO))iuam%{6GDGJ~#kEn3q{GZnvLVp%OAZOVltg<`vB=ZPs-$OQ+!6HA(d@bq z$(o`;fm*ky;o$%1C2FhEjB0o_Af+zhMotX_?jMIJA15ypSEfwS({vjlj||!ztCcZ$ z&_+?fZI6nua!WF_Br;Tht~z*C(g4femqrYk$|b+C@D&$45ADyDL9ACDQ$dZVH)2vv71DzfdG+uZleO7LwE@ zu5HdHjGWROH!$XuC5_`93GNl@T1f~XfG{`xgjGd2VW!FC=y9GRfkwy%V{+%)>Gb*) zrtY|GMFt>QhRHMl8-@gA+X$C6#2&Lkqj}ZK`%TRIOG#+XPDXi(6`p8R=$ zPP~V#-t4FtZKDrXo@36KKsyjWW--Q!07^lDQSTxruo?y+FbXb43I{&TrhgYWB zot9_ay+$@=lDyZkbq5NeWk@Yj3w$J|eR6gaS57Ai)$F%PYn9>Czg%1`29;r7)Ty%a z=%L@;eJL&_s~{noGQdH-&5|_KgdsI{*y1|oiJm34)X6@*yD?hMfkt1Lde0%f6GX|@ z?o!(3cI+Qtw)W93U1-d3IBD@o-b7#J;_M|(P({nvPIz*Sha6bs_B%gt zO9#&n+*16i0nF@JEhRD{PYdxR-C-SFD@@YDHVR>OGe)dM6eD@0trtV?#n1+IJd$TJ z_{iUacYDt?Upnha@-{vc~Xn`v&)TgoZ0gO{XG|`30#8=pddO!u5w!YWK3?l-ZbS zYk@_`y&xnOW#}{&5maVpyva>u*I^c0x5|wwvhfmr_L)~uLBoc9R&3{flX$EN#fjmK zVk&&W;ouOpbZAJ(;Es9t)3Wf_;dTJo+{Q{B*K29mF@M5VDiyh0dQwLVtB!h%c8H0t z%6&W_UTS*La>B~rlQn6h=jd@LnZaMyxO+SqZ!T8oG%2uRE_0p;qENA1atogf40S>- z^8pyx@Fu0Vc_jBmn%HMK%30yjQiq%ur}z&~UOmHTk~!5*%xer*u^8^VebwUI^>P_L z;E&vcI61e3=qKjCHc7FdK!@4a%U%j)H{r-{2Z1N@eVU5`xGWD0blS`~)IV8RsQW!;kBQ*Lx2qf&901)eb&E?!=|Ca_bC*m%MsS+U{S;aUt0M8u zbR!1onFHrq%EfVx7)OW59uHovhjggVDxgs`l=k2wm zRD6vF80Iw?8$yYDkKg}=+;p3r0n-d|{+6uLW@G&S(dzl8WgERXSgsM3v3Fy*VGxSx zA9Ny~UrGZ%MXjHf7+Qskv8bknkaOQT32;3}y)j1m=1PvtuCXrx52>jyq8DlJmVX_) z{CZo2RmM@)Oa|}d>?pc^ZD0)Dn6l#7$Oud^um)%r#tWQbpFL6>a6*?Fb*mI4?nrZT z%ACOkg|jzl1F3#hw@PZS>#^R&kJZwnV>!(HC7$L<``Nqep~-t@GWtRGjwyA)C155B z`Eo--JfI?Twa?nt;*+CDgACaypdYaXo^5}F2?=EO93o6 zt6~~F_%}R~2kGySD!v7*EC>)B=&3MCBadlC6X(RJU{}!b+{CKDpXgd61k)?1cx{26 zGYa>is~qJ-1O10$`K=CCK_ZPLWt?=d1dAQ4w!X>co(z7&8A7T| z>#1bztMEN)OL?pJ$5H$~j+eHg4)ZWf@T~f=Sk!1eG_}F={b{cp z$H1~j&dz8u2S8bR_9u!$K(7qU`-Ugk#{%F-+A+T!sE+#*8ei@OH?zD0@fI@X)^W2* zSq_6ZW-W%DD_E*G#{2tcz^n>+!pegU6aq}B!El47@@0qLW|NQthB;n=9-xnvbaG>UIWK+N`Cv!| zWz(<)xC-e=vu}b%oDt>Pd_V4={dmyBlVSh_^y|hKzuYTCF(9?45t5!YMBFzFWNz{) z3b>)h3&!zIv`pAVOxDL_T7{)ir?IkmOXAmA52jB{*jYpU&pBn6fF}VbL#k=fVxg4L zeMb4P(ZeKte!=XS2X$e)fFT5&^|2|zxN>(q88n55SSr!M+~|2R=;u1Qy?}CSpr3SI z91u%WQf9guc?w_haGOsfFJC7W1|&oFRF1^8UNO$gnedHqvHU*j5**^Nz;B`eA}zeB z9v(PH=%CZ~xQWg6lGy!fD$S(wFK76I<4!--7~es92tkjEj5$MEp(;nCQ>ez6!7@Kh z9G3nf9q6it}c9o}a3#q243%u|=LG zLS?E=9>5l5XX{)O`v`hvWM^ehi4iQDXNGkkC6sFIxKced*lTEJ_sBrf=DLePGaBzJ zPetKJQ|dY|DC13*{z5CsXMsMhxbqmkY2M98;}0~~)`1|ouA#09U|=vvTvY;%umpRT z(dtxOF3*eZF;hvZZ8xIKEMJhe(NX%bS@0@1%DLQ%7K#W$xJSqA7S!1yD?}Mxnj$H) z#C?J~C_^Lf&nX4yy=d?3Dk3GFsV(&CO8B-rWGA;PAj(##dZ%k^)|mv-DB6ZfSCs53 zph?vYe`*gTH*+VB=QT&o8ivU)B6%Xrwt5oyP4+P`Ed}a^J4r3xDW;Z1H`7%8cXeT! zOz}SuZ3$(eiV4|n9snbW(q|x9!Z|LNDh6>idcfQJL1k+>80%jen9Wjo%i`qkfh1q0X znpKsV%pB?Y`lbq7C4ut%q>u{h@3aP83R3?t6E~(NwsSIctDqzCq8J*{0#>y|4gMTV zQaBE;3Zyb@McP`0sb>%)N3EBnJ%@$~uki&&{zXcT!S-1v7 z#oT9Ig4y<7!Ciu3O|%>y8<+4msC8=jx-5qEI4ycx_h&(Uqy$C{mowuJL^qWyY!u;o z@N@W4Fg^29fMDl!%0YK+D?bWAU+D&fYChhwP#5qegHLlN_Q$Z}lB7eR&D0P}^@N

cGiH|zAaa`C>^>i?mb!W8+>h*d0WN%*(vZon$I=+lhl&p z6EORT%+fDaJ~q{<{gkfR_O-=Z=n+wh%>3*u%&YEaDZ5!}X-lxSs_ zk$&=b&_W#=lE$Yaj6FfR!c)Cmj~91LnWy<%&6}e!AbAy#=#^rVR7Hxdy)=?pXr{!5 zme$=iXV`_`;Xo0)E8&mEwjRwl@(F~pu0<1n>ndRZhMMK$`stA$1!I3@QCC2ee(q_J zy<*zDFuV5L+}=DrBLOQg3i9?vkg#POUrbP5Z5UJK3j-$X=fo?o4{rSipJtWbq^GX(C<3)d1{Yk3M_(+(X=V`CN-Tv{Tcs$-DU*e~03p%)x3Ins#w(HGS zDN$rUkEZ#nvVl=O) zsP!*U=O@;C1Da+xpw$Jt8&&*h7Y3Bu1)*(#?6Kl3E)e<7!M+5aG?wxv-NcikR$ z0l>h)_s8K`+_2gE_t_%;&$NBm?h|dysONFt_2(O!_atQ z_R=)PvcDC^Gt*2NPD=v%9+LmdIE6KRKbGO=_Pm~rPnyy1dAtuM zo%}FPKHoyO#%M6NIeC8Z&G>ftP~h!J`nh@5pL(CBaK?Ggo}5y$v-i8}NoMqcdQez_ zt95QGc>Q&C243Xqn31mphNP`~hGeuzUkh;Gbhbyk8n3}5Px+*NmM*^FkeF7%+~AUF zg_az*?8+$eOA{rDN@s7*+47tsHQY)3f7p0CcNOxcgv%#YgGUZ#@ z*y-u$2ExIyOPdy_8{8Q;y}R3*KA!d6K)|JCeDk6YXp~0qs8(ZvotTQ>)elYsD=~6s zj3o>(`-h|5Yi;98$T@Gl8TqkD)gNEobG4#MMAM8{U??kN0#}{|>fPp`zgvBNKEN>j zE^)tG0Urjpqt72Nn|25 z%Hi}~rou>6(z>#$8xy*{~C!*{fm4cM8lWT4P$7>yd>nwlGo$vByZ9c6H`X{{@78`;?qt z7xWyB0gDZq7({x64#T+gPX@K-NPQ-ylnZcW%@i&^n8O^x^)>e1^wjY&mXMaaFII*(Jh0aJwhwzw5N!qEA;3`i+l$;Y~jyX-e(j@6v z&?`T`lhH^ut^pO&uvDt}Nmy~-xiE0}BCvnL`I{5wspqo4wY%a71pf zagYUM=?PJ0tE>i3EihAd*Fw)|+meATv<#b9N1_lcj}h;jH@{mmz+HRx*!CQ@nS zQfg2sBeE{#^V`lygxK-fWGMFw0w9^f$Z{Gq$!VfzmkGO5haBlLI$TP_g49sFVaDBr z1L~Ho%t%L`Me%enQK5vL`=bs#LT#%}EZ%-zp|;C?i@zm5VB2?hAx>7S)@PJA2P${p zJImQYee(Tsc9tBUmj>PsR84W7=9QW92Hg0)TXHpoffNaMWB7>a&nqfSqFQ;}=M^pI z0nlxnw?}U!*WtF?g2c72O54kdif4sp25D`7miPv?MKMqlo%kYgxjixsm z>)oZYPA2;58S#KpT=_iI4r%HOFze||e7lgai z!&XPaU>xP8+3}C^ans=<`uZg7oT*K=(pmvq2!J@VTEOTexg0hiPKCS83b5*{zkaME z*X*(OGkFjf_FjhXN5cbnU4H_&KktX_j;he~x%qzIfPDeZD&zoptdD+ZvlFL$V3deX z$;B~3yWJkDB7n(RKoou+cX}#=4H{R^`wmG^L7DK6X_hsk=Nc>pr;1B|PBEY^$*VlIAGE(3`6PI6M?7|1$7;XYBQY>mXrST@AfkzH^sqUWW`sP*hOM{Bf+ckbONR?+S0Giw#1t)-Kba zIVR0@guR#^fD}cVq_BKKNmQ|!uky;nhd5$HnY5SV7KuGEQ6l%DA(t66RT^5I3z>+o z3N}zttPmaHe`=?Yp1_X+CTx9D7U+|K$j$6F7T6QJ%f{Id$ga7vcdGAKx3^ozO*69# zTv3?G#X$lDARB>ByCQS`0;QzQd}!zr?*za;4l3mJVD9AuxOZW%oRcS`>*({+23hjX zsMF?pJ(3|DHLV7m{L{tN4-^7zVMZf!M0ri9KYbEB{n{!Sa3YM~9ud16y7XZBbM(Xx zX)7i>lk*)U>Fvcbi|M9;|5U2t{YJ6C<>mLWB_`TBAE&$AohU>$3!bYeS`NzljkLBa0zHCbwmcYeE*14 zw&|F9RuywN&@409Lk`l$a;Bt^t+K~S1RXE7tI zF+zdLU;$@qK*ySAN93J&K4+XNaEfwwF4J-a@*Fu?NQ0E|y2jX=__}P@TdR{QK7|>& z>TkjLe|IO-IFWen5D>sm#Q9NIUpK!44(4p-`d}AQx4(P5+N&Rmd{OzbQbGHMUto zOF5x>ByqE3Fgf+7{&H#ustH}~){-wuTMNZhdh)^Yv!orhj;s}CU5Xetb51OJ>=#@y zr$>E^air<}P}tDN)}wVVimoD~+*OsXE^NYDXvy|nnx=;b3_23H#P>mY_ZWqjPVt8U zD4K9SD#7%z(3vzHM@MwyR>7(Z`XUq&6%+^oK5P&;Gx?4JlX=;fH65b# z{OtRKT>`2%rPUwn++q*7ErC&}GecrA-Qw0ps<7YDd?UD{G&l=%g(44&9eCzy!ixy! zEY_!+nQghrcC@|g(9&r4xm;n?I@&QW(JDKORyG>F{Qrtr5#DVZpg~Q~TjvTt9eo_uT4uMW8K2B?0Kqi4xlqLrckXHQ2oqvLlpnVieu>IH*q z63ATo)BujC@rg)wIsZLqhC)BUfxPFp(`N=eccOHZEP}1VmY`SAy2l&M+)xPW^T;h6 zAz+Uq2~_O(E+2@>hvrqu)2&{&ezP2 zwr$(CZR<~u@y)sBTvco9-$*u6l~iRTZ{@w7`##P|EF;HO72%$ZM<+?DXMClbdzeMb zL>R7qxQnEzq(2hAo!A;$UJAYZUj(b_FWDGULP|d4QrblVbs|K-x3Ub4U{q%@Ng_SC za+(_Og1coH>Ew5;YWjsWayD9SvgZ-_N0WuPlZV!md)!S!&rG?NaljlD&uqlxp?&)` z?5xbtHcoOAX?$Fh8IkG{oX;`NIY(V1N^UXEM9FH*=weWCmV+^VD&a~A3TlB#r#)z` z{XgzgSgjhDKY9~MFU$5#I*o%d!wi+G^%ze=d&Gaq1Tc{1=~6yNq2puJc-%z93cvbE^l0T>z2=S4kzDmyKjk(Q_@jZJBi*KG4lpH zUmBc?f}1l7ErE@bv6~o_?gb3Ll=A|E`0eUOh%$zyhQsh!Y_{nUGatM z>fh>2v~=RI-}>!zP7iG%v&61Uv9r7llt`bPnwQ|ld{z7~ry??CoeynVJrVGWaH6~Q?MBNHfv)Ue*njeX$D8?ssMgoSY!B$k_ZVgr_5fjars>7~ZBH}I-W zhHe^et8HL|RmdplGwcK$7=B~r5Ydh~KZ}MwCz(*Dkbcp&V(M0G0GTHC7q5EYD{fst z!u|j+sVd+kxFwtPRJgub;jWX9+B2J5JSDzmO!QO}d3XCX_r0M(NCO#;3Kmz@kvalTS zRz0yCLjSY#Nm#u$4JnO2J*{32vUG#lU-BAv(&(@}cQyi=qX$#$2z{A<{f;rv^oIWh zYH>OjWttG`Dw$Zsc`Z?%7%4l6NF17U6Gh8@u_}Ujq9~6lrf{od;UbQdp%yb=4EoSJ zu5bYAfKF8)O_?{1x?LxZdBsXaJWbM5J&Ktj#r3;QqSnPY%ltj!-R7U5G?a>@Ic{q; zhi9M8kuua{){8~_E|MZH-=uI-Z&&_I`Q@imeNIRSG!i3z@B8ZGEm{gGc5BbD)UZ3(n# z4NEiK$^RJna+s-iivPX44n4py<0j^Bz@kOb!4PA}VZWERzo13{rcgDCwnAmrFMf0C zgTP^g2}rHweQk|uARgPIcs%w7ulvSoRgHK~Z`IqTk@giQ`in)@&r};F3L!iI=cE>afu0euv6ZjO}v8a7-8t2&9cek4N z6(2hHRk^!M6R~-kcJ=Uw+PFl57Aa{&g`bsylgIym;2Q0ucq(Y_Ho}= z?w9v{+9ThidoQSQq76z6V@qxyO|I>^dU-KvA@YZxT))w@7r?Xp6AeZpotws8)iI40 z$x=(MJ|HT~yr=6idz-5qR0M=ynSgr{N0**qMZC)*jMPp3=oL1zwiQ)h$7d?;hog-@ zg;x6s4Ixw>1V#|Q(KOj_G>tMAtjwHGLZkG7#&4U377AP?8c>(+p3tu^fl+)v7PE?; z5bCawrS?`O!mCSQ=E(c{OY-xn@N-B!EAi%wsnmS_`t#|$#p9b$F`@IhfB8b2!u<64 zdnTRj{mbh5ODT2Oi9sdtMT->kUo(y5Bk8})wEKU|v<~KpwkP|fvWT?*sA-Z8a#T-V zMvYFIOP#|tggTB*#amy*(oEIMv6b6>eqDUQe5z8zrAeg_hctKF-nzVL-oCIg0MF@ z+y61Y^;FK}#r^YG#B7_C_zY8d^2h%um6<46rMq9pe^vc;)jD6&vTgx1HNp2a8iUUqrg-Mm{sk+A$K=pvds$^RI1Ily?0OcqSzO!PeZ$5~Tt z_6qNDbm~x5@~xwqYaSuo1VOm!Td|8X_?-@5P!r@bc6kKuur(L?6NF39C1uC;R~!Wh z?vJXuIfX>7BZkeLzt9@MA4=Okgj5K$P{pEJKez9*2tenPyAG169OJ|wj%;}XV1~$5 zzU-MM36DQYA|GF<2c;(jS-bQj*tts!qe?!a85D@*;ag+lA$Bneh|-2b%b2ATZUmyt zy{R81T?I=p5T4$mstlILSJ6)dUNk(6%CJGK>eBfM)?bol7dIo?_iJ7h$~vQ`8(PU7pTFgYue;-IKx&Ki$OTM zg>dD3&ysn@rg(qlC)BxD>7iy^@|_GQEqYd~4KEoVeo|m8%BfyVm!71`r^&!|6s#JQ z1eF?*C)^t&l45xPk))=BHnny>QjB20+Cy2(-p=uK@eBz&y)~|w9pVVC;6Yl@efD2` ztbp2W$YOG~D@OKa9v4&_X=OFdiw!E4!N={El412Qp~ms zR@Xb44sc;PJj*b}h8@-s#hMN|mpnogCTQU-_XfC?VZ+$@7P++?em^3|Q7r97ltmw> z`mGM1+(W!CjM~47wR;ZHpvL<-bx>B+WS9D#Enwj=H_C|9u!y#nbSmFM7cG2PsKIkS zHA`){hmVHz2VPU@ajaeziEr8}vq?Ugl^rc|6qMDTf()BQ?{wyEy}CSXi!GXRd1k(` z`ajb3C425`PMZJtaMS?mLQ3(_4gH>8Dy56B%$}tOwqBFz{8nR0xOa*STM9I_|N3yg zMVK_x2t6><4dijZHN?_J&o)>ZrqWhTRI0p`#T0OrYZ%MAB{m?9tinN@O~ah^YNyZU zu@-6rim9jTs%haOSiv`)NE&{>yDenMD8PvDxG2B`gAWSO1skw3 z(#fYTXkANK0vq z;_xXP%(jo;g~rPAyW!` z+0_3C(4Y~J)m5r`R;`ow^Dd)*7`Z2zjjcHf&wFfr=6JcVpS^EWlX2&}$o7XbX^qW; ze89mMA1>BBMwwoJNreo}D#*GvR0%e*YWs6aYL7N+v{f%ki`*vQ-eWmSGed~Z<_mu_ znR_l7<~n(S-+=ne-=?(CvSKqP+WPhF!%gMHgkM+(X=@h?prXhwZR$)mU`^4!`Kvao zan|-CNpmyS{k|iS23%mx>y&r-{w0d?B zA{|=2aY(7}-0t-J0GfMSg$z>AX#3;TjL)ltSV$TmZq{q<%MhFOzU0GqZa3wK1uHX1 z4kr0Zids*TfbVRS@>DH|%0#U>jeA-3r4alRw38`_{g(jb5E3RLoIH1Q(2%BpqfY~l ztVd;ZS$g1n~ zscL;b4h}AO&&tKDxky~Fs|FtmIfDsR7%);z-Oq!tySIIZo%;q`_(JoxTtx6mERZs& z1XP22E->N&byFm;A2$?XL*U5(r5*Ct32`-_%MVY|W(^}jH&Y=UCscG#2Jw2({U)&)MhLtt`rD14L6#hTj z(8LWYmW{=sQfu~oX&47VrD(g0_AdPVXthRXlCzk^;gD&jd2meag&Amu?L+zTtC{ta z=>OI580+%N+XEQd_9bVfIYgt-Z0~tu3`*Okb-D`@>8l~GlX!X}k zWNUMI-F|hrz8rt`sB1lbPSxS?p|a*iih0%$@P4{YUwL$74&S8hIaG_DRW1YopN$a; z*{;z{2?q5SrRc6+9&DqJC^k~X+d+E;vu^#g1JtpP+J&dS_X)vI}-Hcp1Rw~dH zr1vu9U;Sjyz{Laog1w@cAkaFzy`(dGuVmmwlDq)K{UhK1$IK`~>ArxT#9_vw-`!Wz!y-}U**KYIdylmN|H#0FDqt`ps{)WqTl=Y}`wx&pwzBQ@&TX!*Vr#F|$;TY?KMK zj3(fsmJZ`6LMHm{+~S+X<8V#GFlxfb==G<5ma*G1UolRnXg^1n5Yug||B< zENB)`1?_n=1afkuii$dAMAlp!$~ayr49d7GvVD3OYSBUFAgB#OM2`vE3#qoBe=mBN z+Hvj?&zR3f(3gIP6|tW?1|O43)&NvJ6lIv}g^m1cWo6A;2H-xpE6f(TYsmvOY8USM zGEmyOCe1eC4d3IJtU-c=25MM}&wx~vNz1UNe?)nw>idtd2sD-|5R-q_! zZYXI5@fsjR3$E~qdJ^C3pFXeg+d;G;9zDQu_-H#(7@V-euMGPu>uxKjR+@rugG6qu zs9TboS|)Sfe&@y+nK=5v*~3Yi_^mC2@?_d(TIudz*uZ_zESy=De+(HiQYK;VpVPSD z)66?#r0NClDb@!6cJCYM5UkSmLQ|`4A3~*WN}16phufV0`s_UWsx1FxOVYMH_1S7W zx;*pga(&&Ck!gS3n)3PnTGg)EsSn#jmrdShlSXA~3D^ayzqTq+YwIja(qn}Jw?=Zm zvJX~4-&ocf9f!4wC{IBy9?&r#>t=~>t?~HQw@7Ag_?B2{^{IT|YhtPq0j$?K}Svumsw&VeQ_fo{+m}YFa>ZFiR7{xV_ z2z)2-;2OgSy@$vPycm_^Rv~xq+@HoL=vt z@$6JdqeY_M8*)Q`3rgV0-woLsosRyCH8>XEA6-#i$;ghEwsh6tdqTGM{jUi*u!kkK z%uH&5{8E5kt%^Q5pX@TAlJ^agfr|%h`vH0$={XFoz0jX@w-;3K zZp#3F$loVf3;tZ%Q4~Me{6S2xe!=~ipr+_HY==gxXA6AweTiF-VOmF}ZM7q>PuPiw zpv7+olP1(%?SIZ4A+gj>$YCA6(jxeGt8k4kk5{9bF_zt>tYd)|l_ z6H01G#DukR{ZWm`C$YFm?`? zWD;}CpAU

-k*)*J|}!Ldild@Yc~cCjBeKKg{K;ZA4`dgNF=aCB5~vsfSq7{Hzh8 zH;VTLh6CUzfWGqz7MtnOKs(gO4B=ozW_tb;=#1CqHDUIY;qVIF&-}^H-+_g}8}Ev? z`M_urp0^#tLs{Z7f0%eN8E9!nDlc?HxKD$%x4nC|=F4L%1<^JlV}048hJg=76)B>) zaMTgTiyf3kabO=_kHhBg{8CXh6aWi6e}-*!?YOq;LdHDgfRdd@5MX9{&5?Ic$%sd- zt3FBaszaBmkx=ifeZYXlYtKS(qS$A)o}>zL76{5LuPA|p9CK6_6_=nd z=txmgvck#d;rC*zgZ+20?aPiP=yJe7)tj-G2aE+{dhIurkp#I5r)SL6^+Xwq0BoyB zalN(O?;XH(+avOt3&Pfd7h&SfOGS_zzI(?VysOEDoC7t|yUx_E4K=BXgMFDu=3;yv zRxQlZfy2%I@4+^)6m$h|D1Po88ofHQNYb@z4w1c{{RMf+@|=A@-SH|~jaiAHNL-{; zGMY&B0iScEAY~8V;hh8UWKu8jEUD$4D%CAg*OTZnk9>aQJlM0+xQ#h0ox$K1z(RvL z@`!Tqufb|I;fl-i2@ce2CQM2dpWY;?5|>TwIEcOzmSio3B}9H#>r8FcI6F!QDoZYM zx}5*%_OwV=Pn(dIEeo{^m^KZlvH9L#{IEwdApLvF!PFW4*_2ZJY&O1&E zW4&TiE(S6WO%mFF<6XqlEp}2kD7Mhznrxt7b*+T!S{zU5e)#vE1~H^_Yym$?X}w3m zOEg(hFWPArJBirK(@%3kx28s9qoN;v{TGXdmm za=hpaw?T5MVY2$G;wGiSU_(O1D;wf;)boDyg8X!G?q-;Ap1UBc)9i5L(k!1>2PL?5 zYhLXEAs94um08PLK9_-spYtpFkX3vs^;1_e_d`#=!~nbz{S<`N(zXt{pQgn+^5NCOA+iKCgQ$UGsZKCIS#9$!5-LWxk$-4jv{r ze--YxSa|eUo3HBy0wfp zYtW=calsI4%5mHGXG=>C-{j*`O45Y|fl}t>5T1a+|4l3qwJORTlhE-^aJcuHBs6Bj zxj=AOF!vw?KET^WC@|xpjpxL&v_#fTNFx|Bl;B!1q~60tJQ$TO#{KhzCdM6;(NVx~ zxc7!+<22ckT)3M8bx@KK(6A0^ObKZtHmgaiOsGX?uf^88xw$?)hfx9B4r`Cb8T|^}Ru`frTb5u=k4I_t4qwSg^0^fGEK2tN{*d}C`tDSWeF-`NPDfXZ z0Xb!7wM~89pC8=e>A1gqznii6A1nvM7gFI$rL^b1p-GzXiyGcX>md542353zQ5+G` z)Kh~4;t8^dCTrQnh|!XSSx~ukX1}saa*-H`x_Uykk6j}P2z>iDuCGaYFuTSa-86nL zd<_WE>lR_pgiVQp%kGcFK0cJJcm2~EPjr3dz_2)Tfbf+n9nS_HJ>!UYY|qrN(5m$c zBH{Bd$8Q-?9*20cOX#UjA|8MLy|yfV(Z*o`&ThT!GvBQ=X9HI7L_d_5AcryaXiVwl zZMGg!SblrI$SmQWf$0DaKf5y?cXC8h(jz5H34jYgU{H0;8zH_CecqloXm%J?1{-*q zTn?I8!A#6PFgf*mjCBHA0#R;Cq-8!S4aYTXtYPg!J1-tINXcCXNB;DBdOyISf9+u8 zp4fpf3IZ?7rq7~}WS1|}!e^87#*gHR@;kKc)So^*Ix+9>9G>ehDkOH8~<(03S!$#XerY976 zKX$P}@a0sXjD*#wLI@ib>DBOJW9W8Y5B8L=Lx=l@Xgzr$(81?&)q(;OE@1V~M2y1d ze=_~h(K=tC%{{E97_`wKUiBnbRv6ItdfuI(Q{qNRK`IaEN5?J3rh0EL5loUQQGI0$ z@-T{fx_^r9qQpV^0d{6ekbz;s`C9_a`F_5=d8KBQ>#Y6P%bw62aewd{6uZ zF^XPTF+W0;Xdn4fH*7hY?9M@MzpNkMh#DQH@ep#M)YPOZMnM7&ORisavGY(r#Wz_K zSp@Sm0hS#ZR*WUwApHk^IexJ*98OVV`pa7IVwdnE%dG38u04&l zfE4^@fr+~s*Rw=b%d+*ZKGG(wgqGFt5hhxC>(X|ZM+h3)k=y+r+RES5DzQcm9#>Rq zi*}+gQr4!or~_MGLm(^RqZY+CYyy!Fo0}@~md(#B{mle}D)@s9C_Hff=uDS&FdU!8 z!!HH)b$G*5r(*yE9o0$Wo~D)a4UoNcF*0@kjbU@sJ;^9d9Q-oHO4hxB#9G z{T;@N=+Z_z!dhE+ranTx%uc(u7V2uBvq|rdw10g!Ztm`jl4X3%zv=j6vt6IG=WLCL zuh6Jq%j$6OeLTMD&!uPjcTQo9B(Op8N`5eaC(=wJu*mfk-y>>$G4ywNRu=_ANE`KG3(vIsjRPB50 zeDJqZg|00M3Spf#K{+!0>9YGQFv>YNo5D-#Wagj^(7GEb!z&Oic2hBK| zpScD|E~XAC{>z&8$YUTlvN+nSHx-Pl*D0 z=p$tD5d^bA_*@WHsPTf-O3!Pp8JSP1M|~&94a@DqOMb4{!c_uD3LUX$tu7pl}GB_W9t^sh6Um(gqXaK?JmgIoGbbDX!T^fKvU7RltlvU;0 zt*NVH#H=B|R{dXaa#HFyoa|Veg#-n_nE4N!d@9s@RjUoHH7^=!l?z%iA6pN$#lO4G zg99_g9B_;)Y0|5jFoiGT{nj{QRZ3a$YJ-EZVi#5WlVVqY^yClMra$@*@`q82S%Rj; z)I%}0%MP`IrStw+8>ysf0T?KLmDgN#qed5(2DEZ!sJuw!PFRV*bTXBt>HnaUjfDj< z9tXmY_^{@ru^o{m!iK^^MF&AbH8`mV|2LhC5w8KV@S6H^&BoS|orqU$D#=Kr<0+%5 zW(?6uW5BmLp|8j@Sx`@;QD#YSiHX)N#2A}}q(T`7cM6H}JA+(35S+J>mcmD^{&A$Z z_2zD$OZv!7Ol?^GrcXLm@N`w&(kHP-13>wgCl$$~(r+6;)tBoE#a0!JPEg&0KDKyA zZKHeRw?vrFGk?Qe)q8|45zun-yNJ^TY8=8L4$5+rh&Wvm2wv#*c18s|n&pRtC>oq&(R3qxna!vJmX#wI11<6l!RjibryM;u$q4S{hSKPi^W zNG}#Onn%>Or0pL;-^TNUE9*`)U+>a2!%GdPm8MY(es>!DXn5QCdgy)na-Vtjsn}IZ z{aSk4xKOci?o)fDsod@Jy4?K6{O3$$yzk$;vN}xPyOh6WX8Qq|Wh)pK$2(@U^{^JLCKOx=-H;#ZEA=40b9hSt4PInyDkRxEh3Bq?!f zsAMD1>VMhHH7Q~bXj5qzKogCF@QPPN-7zxaFOqHu6w(fvTp5BZaQDQHgXP_>2FZP$ zX9CwaJWu{#Z?Pp`HwJxQ6}v4PZ`s3!I>jlNM_+Hx<@#S#Q(tprblG3WcRsG4Sf5vq z*@ItQH(y;aUq1Tq!6&ZRW0dZ*79KuebVEe<4^@>#1i64=$G&U`2n5gcWCPi6E(kQT za@Kp-_U>mpAQ?-Yx9#ygn~*8jJ!@46NY!DcKm_yayplZ&0g&ZGk@Ns^5Ax(%3$R^9 z_#s*IT2rgbJ_29jQ@?3jKyWI={OdBu97IRgZWYlV+GL_K} z#oH@qU9HJv=Pj`-0G{P4@Z)!TDCx0VF4X|++=!SxXEp)}i^Rg8xpKAQLlAN^cfWnP z)bww*5;?j_Fg+6g8NWgsZ?v(e9L61XslbSIjoyf)d<(kUXgM)GTLo6Tm&=C5^{ z(Kmd_Z^aJB`?%AD#oOWe^$#n^nNf}HfdP%5(q=E%^V=HtAFdzaJH==NtRokf29F5$ zn=FXB^=j=C?b2~Uz z&z$Sv!&tEXAa(1|a6{x_Fg+UiC9yOLLuR-z$L=soL@!y4N4%QjC{@Kcsk%z=&>)u+gv4uKJ%?m+S~BR5KVaWoP21|t(|a@Ab5ho{=E z86gxnj`ext3G}~yIG>P%2tPM(JM4_x|+25Wq}l z3=N3)8YdJ{+OoVxakDf(}WU$zU-6d@Xbs1R($=z~Jh#E)o2UXSN|I z#--4rpoXxx+=yaC(MQ5A3Ru_W)z_Y`C4li}>|s2i<4AN_zr5t!;5f`>=onXe0K==h8yc9VZtuBd zCkjei`&)RBKkwML{30bq9l_S^;-$01sIm8rbSr;k)2sj7r)%{VU7$v+F_&3^6Ojk~ z_%7HE!E3!99Uq%YXft8RP>z{c5QKn-F#Y(ATQb=^J}g9J{{R!K)t#SNXUZ5lB>&Xn z0tDQwI0Ix-ESo{?BeU3ICJ9ZxH_2tAS+PN-X)oazINp%J0f>Se>E&rA&p(h)Gh~6B zi5Oe{9T?0Vedex7!PH#IO;MfdFH6`MSxWiU%J=rv6FJ^!Gg-)ttQYrZgXA(=UePS+ z*<{T@#R_QVP`Gfa=N|U5L8U*n0zG5WIU;2SE$kRkh~UnABX@@_zMqV4GWa(^1eqYM zM8kVp)bGD44T90VS?cH~YI;!-senfthc{~B@`&M~kskRp5LW7O!m_;69qWsYHPu(- z4%(=$9R}jkz)qYcwNTM+?N!{B-!BZthA2cUq2e}unp|B(9as4GdrH?MG*(UB{&7spLF|b%PK_4mqE(UxqBbY4A7^;F4_pNfNYIwB$_}N;VcaSZ zZqq^rU`HWB76XrG;c8H_k4lbyFDPKZ9lpTGg50L$-?iGC7*dYw704vRHl&jAS>Qx| zCTqmji00|@OWNFWXm1rl&mn-n*TweSU{h-8 z{6onQ%Q%AYd*NG=$Jiyv3)z$S_#SSX{)@>d9YzP~b5be2F{&A#8h{XB*z)80IKQjq zL+(vSj_W|o%I<`r0B+C|J;p4jlqDT*Z?pVZl5_=4-v&$=lNoDrJ+W1iruUGCs``N* z@dIwsAUTdg2`*@*_b7~+!}8dvL}5&Ne`$8yQ8Wu^*VqAquuj?@TrFyDI4_!E=Mvt= zd7nTOqC4VW5}FUjU?)9gqNsU;QE#cGB0GO6ecggB-s1xEG~Dj6gbvcn-p-g~Ql>hC zOpY;0Bf=f-857FAx;B*}Au&YVnG`CZ<2;ok*tN2@h(}3`j{9v&UTGw=#h= zy&0CJD`F5=Nd>iEfPTnxLf&I`uYV)E0!0hCwOgl4Wk5D^dqx9F3twY?(dJ)K;~>LD z5e@tuH8PiLb=JB74_YaElzi=y-aaccr5hX@EiF_HC>V6b@kU!$P;BNq?Z@5hj{{AU zeR4<%tW;B>7gD)?GkC*}v z9cPOl0mDw5Q)M)8bX6)L)Ihfz+VMk{-!HJO{)y5k>a=F)&xe}NpJrNMdg{9{s-}vq zS_{Se*jfjH9m%=jQ7nh{A4lUFXr;el{8mcjll>n@V-i?_gC>bXf7MlP8VLRrpy~}w zOt-Q`#IM@S!ns6JZiDKAhq@uQ@#n8Ez~#Kh`eM<7z)|PL8%$)-X7L}}h_t^z2~oH# zcD~*M&1iV=K!0wsbqA(A)TJPV38K*VgCnVvw@j8`FVzV7H<(25JsBFu|BaoO3mD@O= z!Pt>g&|7>wCge$uhZp!il}=;DB#b{|)Z)PVj>Jo&Brh4v?D&7cU57oes}m`AUprk{ zf>!BE4w5fZsE$GHuLXS+OHg2tN#bJN>GupcH_B_T^QBi>o($)9BBRF|LOPunp0>iS z7A&!J|HMb-jNk3Vg&|@kP+E#;R6?N}b^Iow!6a}Al6A;+C2HVPf6uXVX9_8#_zG)j zx*5*OVGDc!ZZ6;>PWV=a?BEsY!(z91&|P(PjF24@3{WC<17iOlTEh@PSkKP3+M#E} zl!i5^5}AO{mzYt}EDZ=TT8+G0K^GjU)d5t^J*tU^8d+G~v0!W-S}v3)7K63t|UrW7XYW>OG9Tvo-~2uxCA+1b<`56`6=AB@ntT& zNanK(jSlaFN40ru^UJM~$UewQ5G(#!U%+u+NBug3K93oG3|Z)&1X}91Sw!PD`ScF{ z_aO2=(P~dZaS1f^t3)I?bJlOQ`c{<-jQ=J@Q6G%B|Ab5A5h1@Y`i6wwmS`>#nM@g6Gjm%(vzV8#|02xsI4LGhhPd_wHUs(9mATfO*ptr#4^QZP!t!l-*h*_8! zNdy@SMCdS5$)|;#h7uP|V4|cj1iU8l&rokHC^>k}{5l${;4?7LpZl96rtUqmAP3ai zL!m$Fh~GjC2p?bMZ}LYBIYrD3FJK!81t99@B#3_}I}L}?Cy*O*E)4H)3fHcuwhoL1 z{;CSA)DT%PX!OiFj1?4`ZF^ldJW2sbK%9$N$^{gHQ_feMoIy5{fu(z&1zClZIH|zx zu#CEi#vo)?r`@~|g%vCn$(tcpC~%wh64+EEZDH8nrXu4V@%4z$LZ!ER2DbUlFPs58 zQ?kkkg2pMzc6AGrS?B;$e8`S+& z_Rtw9S%~Hdhs`G+C%BT7hWRq;w^O3OW34r66Elpu9(8 zCBsQ`A)z~)Xqo5}s&pHP$eiJ5ZPR>V4YU+?gS1PMRv#T|w52|c$hBfq-NadmoF7or zTKmg-&HLuO7^I1n6x@30v3+Sa>}74`^oeh^wUPG9(RFf@tfMQ!9Bt|c<;{t0X|NWr z%choBWrIn2KhY?yI3RXm9~$GFw2E62uO1A6v4}!p=|Bj!6eM;6cpD2zkv$t!m_3e1 z4JBaTNFPSNp^eDeZ)k(!=bP;tr%~7Hv^}R$;pH?V=K+;j*g*<|TlUQC(ll{pQV|itd}fgR_RVsJ#q2m#I>Ct(&umG@W7{1%`b% zE~NR+a8x0m4GqDh=W9_ps8B0{vTSLkt!b1C+ix>u%yyMeYJT0a zyFrj3m#h}KS}J768cR=X6vsT(zDsZTQ)n3v>?4ZIj?SQd?<~y8(04Q7Lf?JV$>UFVeQ=qfXv7Vccy)2tyA zS2Mb;#yygQ=8pq?T1UV5=#@EL8H+XhLui8TBW^)sq~7{OC&r1IKx%NeZNPEG5aJ^z z2W%%!(wjL8x|O3Ym~k)6V6THh^qJToOV?|Q2S=ZB?nfmeDSVbbAIaRK!M6AM&1|&C zs`z_ARKM}(w2#P%@NcU)DG>J>qW=C7;Eh*^I`#Sii2C$`EQ7eu$(1y(8c{mdejyF% zd#}5pY9w7{_#r6s?QH0|C3U;U84D^~5e-O`DfU}hwb<4m{J5)=1E>AuI?oH?&)yd2 zVhw5MRpNvYwmtqe?9dUH4H--IYF}ethy~|3}nV z{a4iZVSPP@MkoICbrL;Aqv?8ke=_#n=K|N>nsqHd`nmO`@$0L!)ReuW{VbIg?&*6X zLd*CnqRV03xR9x)TK>Wq;5TT5 z8ONlUJWjU0cIhbro$4jaZwFVuEmA%*@%8o7HI3t6(Lm+^!Pq0lFzE20z6#PGpy$qx zLQ>>G78imb27&(~;maQ)ZW6x!yqACZGxFq5UIe%okW^eTF%cdfPM_QJ`{dlwfm(Z< zRp;vBypwx*!xvB?ev536eJo)jqEup(vOyKk30q4RW^pdH+#ignIfaD0!a0DNdxVbn z6ofnv3uUSiWuuB0D(Z7AL_}`2F{49C_}LQ))nVZr>$#s+%YtZxaVF zTjja6edsmmlL^|nY2?F)QB5W20nJnMw7(pbY9}>O^j#J z2K?BAkxEJB6F3H!Wb!&+B44&S_Z{O(KiDj|E&BW)FUN4eCl#=CLy`plx!td6 z7dV(Ep<7G-a0XmQ?nL8D!S7kPJ*=U)qrO2=mGhl0{#AKaeQQuS0d=xgc?7xsy)Skm zHuSU^qVuT73%dPGt`|pL{oPqqcYM#a3b}a+EcE*Q$nlk%iVW$rC;N8`{c4#IZDeLd ziM^CX>o&!3Sa1sjdf?lN+kBHBDtk)MkQ{0KAp?NbDdeG&56s;4J8C3}-B$JO zv+6Q}V21f#du8|ZBuA?j#fW~A-?t)xRZfxLp(u>&{o9-=mfflI+PxM%$=xY8EF9HU zl0Il5UE#L56GbHUThH7rj{=bDKVD(IJ&ok0AkWPo*3lv8=R#R=27g)&`Pb>p-{z5QSH1D1f@FgUyyE-ylC&*OY&7aV~?s|bhW>+5sUeJUi0kC zWOF`~HGbXs%(**%`s)k_1z+ux-886L?CgPcp-6mfEvp^T4R}H)7db#n+JT{GiM(8o z5B}T$__0(#iZ2&_+2*&x0t9kMk}0z@ohl*94}=Y?DPH$~>IaP`|I`m6mjAncAZIs0 zBKV*BfvBq}zr#Kau|><<<3ig!%#o^hW&CCcL)+1*I>mW_vJmpZu%zQrKFvg9DfW%Ab6r5~?D z^_ow^m$Apy#ZnRs??=SNdI`j<1oI|A*D&)F&P>$$c1RHc+zw4^aBI&VcrnWR-SZx( zw>^0+~%Wz^mlWMeq}4a zLD=J|Li@aTnt|T*~}b!!$W`KOxse0aQ8p zLtn`20Kc3{X0#nHg2o(E$%n=LTS(|~0)w0Zh3|FjiNdvUV#lv~`?hi=tlMBrYy?b8 z5aH`F;AE6EDogP}>UD=#YUS;18S$d&*gjowBWv9Eie&?hkcH71_skg}{wUTdljj=E zqr2a3Rkn`3+{h3`bXS}BedSS1L)Y_zws>05URBdb3&CZILRI6K#mGL-ydV<~L71D! zoX~5;bE084ZJV1^e9goQRH}X699_%!oE&p}Qqh|)3k_+ZkE}!m(t@Y1e)k}l9>04K z>kLbtoF{l>2GF>(BL0irFY&%ddM$F}d(!^N+EQV+J> z->C=CB4GZ|wVuFuN3JjveT@F2vWqrTjfRa~m}TReoMo*W7n%3EaqTn%9cQQm*Qy2w zbKz!#-8&jO&SDYY*X3#=1?vJFm$9@Tz_*#oR;TaV*BNh|U`Nn_UKEJYSp zRooWqhIi>2>*m|y)5Q2kbf3+uU}J+y9#lGhR*BhRIEgyn@ASsb^SFaZnq(ti)!T}W zg0RTGng_VCiUg3%Dx?&;w5;Hi&JI}Z6j%bT=7+*Em8$ONgN<0%Qs3g*Dvn%!u31ro zeCB_)l2Y0dGMVRFf*LbpJOtzG+}An&!V;fZd0e5Fl<#B;j_^dbF&x!4l31#OHd=q{ zt@nHNsYnp!ZcgB_W%ommB46Q~1n=270~R3Upx#Hh^OFBKIKBwr0Lm8wq3yJD=M$ry z=2VNQ_()K;{@=05QQ?ldw@=%vIi&x&7oR!+89wOe*M`D25NvJ9pbw3jvcL{ z`!d27Fe{l+4P=Xj+E#2C2lP$@z)U$HUGSf`+6FEfGtY#r&G`1TNkXZx8fJ%;yw{c~{C-kR=y1G5oWhK@wWpx4M| z!$iv`kTOW=k=*cn+Df$kb+IDF9@m5;)!NNl)ZyB3jj>+rvn*lV{(R>VtdKjf|E_eb zmPYy+g&V8*PFHA+^jpq-pNTqIVFHfZWLqxk0hFm#PH*Zr#fx=qcLa@Ax(2q?cU_&^ zb}!*KY5V;e!9j+WE!Yi$bZv$3p2O4v!Pi|AylkhY#sKtq5C!W0%5-cS+>3nHizBL2{~Gy1TfAqB-g@8_?$L6SfvoG z{i(K+Qwz8DTpCYz)<`jdM|zXn4De=P9%13N_sF{0MP>V=?YTpu&`)M=dr=xh5L{H0@(P^)$gJZk3bUZYv%t7KnIX|~O1Hgd zfQ>#a&k*>G$ z+am36bUKxQQ!|hXV#ZQ2l@PoNeo>8>3WE$=)UHz)3bVpw8Ip|7W4R|1b5|1*w(F(6FYcblNp{tt51xzL^F0En&EhpOY&K$W3b#;Dp=%gvMpmMw!T@ueBcrtAt(Dm zP4I==-%--}!j!>Ol*D%LYF8DSWq(V@HIF2%`M^)sg@}$`sDA5ixp`shQ4u%MD{yu- z_h3;z_R!HNPMW_;3f+!VHA_rA4oHNL;*Q#rTJsN&2S$3pbyq_IZ9x|5^}Sa05Cv?wKZYA{?Gy=LR=NPGoNrMaH zgG)EQbs0{=xM7b`M7Sa?n;bfXJH~YoM$&b{{f$c;JG>-SHbpUbh6f|^P(B)ibn<*q zmcndF1_@lLX5_>u>CbMHqW%Iu_M7g#Cn#U&OgJ<|O&isex$U000c7@f;H-RJ5E1^1 zMB;su)=vz4lM}Am>5)OUp3{D*%8$X5H|tWTHd-NQ=elq7sB%3Hi7%_r*i0HDAdM#m zy+I?McJiUP67Sf~%VaOl4P!Bu*MobL!-0Ku?yRElj$L8P3<_ZidQTYPN-vM9Rl}Z# zD6v0scSTu|ui{KzZikp_H=WaH;r(8`+Hj}}Lcwfg_5CmqUZoBh(lunpU0S!JUCg3u z_nTfhVSYZC_)u1NNU`y5UaH4d(P8u}OFV}u>1QkQ9tU6&(*iqbn@(gHUUj86ly0xW zz1+^}!5sFbH%3KKkr2%ajNyRDgUdz|&v<*ibd9SIjYs-pm)_&7g}H?YEsWrh1WHgDS`kQB=j*QbJ^NqKRU&7a4CfC@BYCQ=Fy=+_r@}t z=&X$3XB*cv&7^Ln+tP!uolXB5r1l0bgPnh4D|!}4KO`>1agps6Y&86qE6-4j31@0Y zdhD9DJwL})cZX-gvF zG|Xq!G?F|=5O+6ojKR_BXs2#e(2~m39QRzINs_P~?KSGDgL4rz+*d1!|Jup6Js4{S z*SSvZ$%ri8E>@O-jCkF=gsSr^h;97&c`?XIrPEgwNkUH~t9K^JoupP1TVkB6hd2Et=_GsqFs?#syTE)~i+?wQ3+nfAV$L7N5?!VWrz8JZa|0;M?LdpI3 zyWruCpj!0f@3m{EeKK^=SHYtpUXZpB-n#lf1&_C`WzE33qpyO;T`a`c?2?b^K4kgKPA!f(LErp`VDfFUjTq zrQop=A4+8Y?}A5_1ZTGk9mU@Tk7vQHIWOQ;4W}h*wSN^n9NYgYc>GQ-C-sUhs3D+B zDu9WxK^!~VP3FcLPAq)<$Mw!2{M8$cD4j_Z_iIhIj!sL?OOl!rt`@u_N{z`xD(o?O@k%W3?BYZk{@);sR^L(0 z&`$POVKDl7gS4{ap1)yZP{~JF8@CbH3uzMGyl$j=M5GFbHFS1C$)?)cmSO7BLv$J* z)4z!6x#3htc9uY>P_wNG$m{M|5A}qjHx#RDhdY&y0uuFk)}V{QY{HMwT9Bf?JE!Kh z@#d}mp`Mf-J=YinY1icqF{Gh=r%F>$q7O$`{K? zt;8BixXydQTt&keC)r9!mXQ)IpX~(PWMGrg&oSEPD&6d@0`sK(c%fazn@iH$ zQ{abT43&~vH|`BCt7PoA`yJO(*3C)%*j6-o2n)f2+IK8Mf*>-)5OmIYgtV8jG~HA-f+lgj zW+zFlslks(U z0pZ>CGowpRXN+#kMgBt5SKt?rv#PX9c~*iEIfvdh_Y}!;XRAHFTZpzhT9`_$R;=!~ zai*-|Dn*!Fq@F$6V0ud}+gg@~W>&zh+LemSP)S532{~($R!kwQ5^zN^6WxYRYT! z4D*FdqPnzc$#)+Fb?kN`D%wK>10e!9ml!0s#G=%)r6n)TCi;6AdkcHWTMDFkb~s<+ zC11ix1I73p7pCi{PzyR_8lAUz`5RuWZ6X5-m9}B)6dKk<9ik>YNsgp<)G9)jF@ymP zEV7jpf)UMgjeRj}#;Ft`{m50>?CNdRte<=&O-pqym=-k1mNM;RNwQx-)A3dY2h(i$ zL^s>%5^c5iwF<_;Nz7!vuaklh_|;-gy04RhNHGffDo?g3ozNz&HTH4TNHU!tzlN)= zMjCgwu1{CYE?plob-l%A^))IDaSA6>5>CQrH6~YB{(A?14y?tjU-ZV#~C%B_7 z?n4HrVxS1!P9Q}nmoDiTFc`p}bw=)Wb(yt!XZqtze)DCF))_ty`b?UzmF}}KE^3Km z8bp=if@G1i;nInl|E%D9W5tbpKt(%@I@_ffhvTJN7BI876=F`s$J85>D#{+j7!7kC z%Ma76RvxjNIhZY~YnoMSqDZ{1}|5pw%(Dr?;Zh_;#`t%vl`mkb2)sO;*8>VtqztvrTRVU2R~YuOy&T zH5tYTqH4s)f1_dGj1<*q+7?nUZM_ajAM7Z0R;AJ%6)#l<8bFIWbh<+@LfcOR`p}v!b?F#=ryON7-H5QbCn)5 z&%?!QeS$EfU}OiUM@l#GkEO(kiO-fruAS-|8=l0-OEaFbD^ef(ygZ`jQKQg? zh)iS9uc4V+3yqv#=2Og_%C6#3Dy?X^6>}WY*|0ZE7^;v>ORuSU{C}bGiTB^GjiFdS zqh^-f@A6}Q67`2g{)p2YXAaJHSA{Un{LL$_!CEtrb?C%G=v5m2wStX=#v5)lk)E-1 z_#o-Wo{DRSF5_wzrAx947t%`ub_pCQW-(G^3bPRC4>N)P z%8yW%!6uUFj#SYsOS|C2{t5v2;&rb10L-qo4eSB7fQ8Got_^i?5QAk*^7>xpY4ohb zyzseLputish)mNWfVAmG3@2~JfSqt@eyaYjC%vz?TRmPq9gTp;g-v3Y7H~KuX^@Jn z0%=+NPNlaN&{S_eR>!dIZyg1gUfyEC^4>DGEpSb<{;L(kP}Ri2Z?9);vXm}j*|^}^ zJkjk9O6r?c?XzuN-D0-nZe5#gp~;Pxi1Njny^T8Bg_gYxN){ZWMOX6a_i;_=$(}N>+Mai-KLSw=Xu<&x*(^54(MWSp%!nFcJ5!@Z%q2nY{3^nK$UUQ}=E7K<@|KWI zUws-_hsWm!GFvoq`pbZAiaLJ*`Eao4kk+5U)FjSw!|m-^JkQ9PBXsJ9B&$;T6B`Q~ zqV?78wV|d%;63W50B)ZULhO1)3jDqAnfhi%c#a&T<2nF2YL!{>$kED$%#2<7Vo-@!XlHn~EDk+EzWSF=s{BE$LI5vAyb zAwbNpJ)I!f%p(X2HhvouP*7D)kEWPps8*z3Iv@OZCc;y%x-sd0G7+alNr9!QG*hwO zjA2eVOad0>E350Bt*ua`I5ugM@|;7vgEn^$o0FGofgA8xOzbbZ&*{>UNUA{bszFRs zyIk#gI<2Lw>BR)%4$P#zZMY^UQV0QFaEjv4hckjXM~g<~Gvw(HAPaZ1qKf5@3qT2GTdSRRfS^Mi18(QkLw5GOlZwj%%vZ z|1cD>QF-H_EGV;p$l;7pC- zVw`#l$GzNGmnnn?+`KH0z+?{}H7e78Q6njD-;g)tNkpi_JtYsD0jKh_fb4;H2QCSA z92zDk=64$~R#TPPbOI0#L1BNLcMD%HOJQ=t#l(Z_DgZ{%63g1!Iw?Qd%My3S#9qHg zJL5#t3P-zok(%bgv;!zPu4r)~LWu7Y0jbZUMT@g3R&$ruK?Y2g;GqBPR;-= zmkd?&drXC!)PX=v-LPtARv}}X;sSB}y!_{*!oHlKJgI8Wym~5%SS0j_ix`tMKVlN8 zq{>5OS5`%aNuLgz>`?E``#zXFmuhVM=>)bKnecX#ldYk6AUFP0q9cLivIozg*Fj5v zzgy;CTFMxyonwMgJWjqk+~m(pAzrW*x4JCNvR`6wlFMKr1xdpg1d)o1=*WWRFYjDy zBo&lV-VrDT<|C=K4eeyrzrIsxrDdWWKgNws&=Sg4%cvFtAAY^`5GwiBp)u)6?Vnk` zH4Iwh^81HVH%_eVp&r}pq4Gh}_m%aD=?;^tSVF%b>kF0nDGt~9*$>(&DAv{io^q!> zKHd`hh@p$Uv5h&#cDO7ss)!fW`ToVYFBriTX9i4DtF*p|YLTp4I$InOiCwEgzEB;z zcP+`bcM9dqiXJ^#IqF>)=tQWYbd<<0dz`Yr`lmK$@bOE$C&WQ-knBMYX=HKw=TJzlgamym>fG zbwyX1DE9z9TYI38xA=$mSYn?S^iHL7kC)U!ZQtU$3$WEM zqo2%idu;fGfBrh|w(Gn1XdNTV%AAld4A( zH_Q7|*x8$3WSpt>-!!waXb>wiG4h$O)d$ zN%|eh)+6*nAA1lyP(5xEr3)6X)Hg_*1447=6{(v;Xr@a@ z@%t-3yio^`7{S5^zI^HOKD7drISrMT=}kIaGw&?j;&Jy4lD(hSiEI+rRtyYDt$9Dl zuy(MHiTZ_E5#w1QL>C^<%1Qx~UEG0Z6vhNvTmK1r>sa6t#2tD}~5E*;Jycdq-W@krwz1T7MCR z4XCqn{2pz~q+_02rmEE`q4SaZoh>(55pqeiPOvu>)*ywjU$ngymq&(>IJCPw&D6Od z#%>LvaXd$T+m7_(n)u?|lwTt3Uef;^DMwa4k4HRawq5n5vdjJ#QZ7KE4lmX~v&@u! zKd?>K7;s?abxpXoNm$y``$NM1O}&ZNhyub^OM4x$0~CBH6fBi&2PJv`AL*u~$5(V6 zk=qtc4@3x#CEW`tkd9ssgo2sq|D}}2Yc-p`v^V@sloRMHEY>Dnpc+5@(yW-QFR;Ml zR(B5rf{jq1XDlU&mKvJjp6}+Ah9Qrn5XcBipD-0|5F2YwW{MPGUPVRiH6i{wb{#+7 zNxl0wN)FV>sLg--N8+^vmb;xO#>`)wmGm&>=!HM($cL)xbi(u?1Alj=vPgvel#P*L zgf7wQUZ75;bc00Njlk!!&}1Q%8v1q5-6O8TtxmKy>N3#Jz3&)>;;b&b(l1<-6dxjaE zX5ytFlR8enFDFxyEQaB#ntbJoq{MrHVe7I{O zPHDb8c!Ea`&8psyAtza|!>?g(_6pp>2+6FDb)1g;9HR*SY80*UIPKV-weQ?}ly%0e z$z3gktY=h3whnSIM7ypdN0sG$eSPv19{RYamk%x zksQe{X!+O|d~T;c@EgP;?y@CjUP&niI1>g4cKP^pYKW{~3C2~K8tn{Drm}P|*@=tS zp@^SuPu z+!c)!pQ~(WmgHz7!cXMk32UCsE+gVqo<-$<9CdRC$S(FD&s;dSc9Iy@T z1F!OL77FC$EJI4zM80SIq@Ad{cCB_y`w-dCsiAGtu?6Yc-#BH{yI8O?Tu6`=42^di ze(X5Y7=3ou%(LDo^|tC;YgIbHI&*w)Np50~s zL7^mIy^7;|sk9teyQVQg_A#bOp!adOMtEMn_vT5JHeAsYqjgILl#cpKa)=@C(2az< zJfjG|7rfBH`qW}jj!^StJX;u7=>Gcp*Uv)L$cRPz#j9X9U8P%Y^I3U}>lll)%vl1Y zQqZb&XB5(|Q2E1g?Lw_*GqDn3-L|bF-;W)koLkzFEgr}%a0p9$iGH`VMV4fIrQlaw zih}vfiANK9=f>A(FrfQw6X&P@y|6|V+sa^%4o>5=!@?n?Fzmdj;*5!B~++4>45y=-N?+qc96S_wALN^yVJ{>ZX?KO@rg-}xs-A~EoWN=D@_8S9=Yv5; z&mFBJf-Gq6mg{dWP!rehnPp9F*`QXgL03X-Z6X|9yg3d7eKW*Yk7&Y5uGCspp?AWD zvJcjjYz@Ez^J>Oy7^Gm-`NOf~5o%c7rd~ax+G$MWKUK7~>n!-}M*(n71o)9poj&{V z^}t{GZRKeFm#;0?wZ62d-R@aXU*i*>FWh}>7q3Jm zBP;P<)vbyfq`Ee&jB!WZO_}QJbhRXFMC4t(>p+g( zh0m=}dd|^ZIXq?CNq%ckeok;SLzX^S-uDY9riQvalE$_8si-F)V559#qmO2U= zCT;&MP45`)myq-ze{>r$kJD$?O%z9-squ`$pJY;2=ku~fu(W?9e?U@80qf)qrNJPC z!|AS$fH6nkX3OpmsODfvQxi$B3u1IotbYYq=nudZf7l!#B+qLx+LS?kOdKFQ9Q|f> zU6Q-K%!^LU0z*Y{h1f@F!}}F67$&t>{57h&)DRu3Bj4c?m;ZMSF3@ zrTykCOyN71Fu8HkLuo2jhJ~;(Dj_YTIR@~L)UVs^4!6j^t?#HGV4ZGbYCNO7x;zx_ zr=Qh2BSh+54q`Z=R@wHv)M3W85FQsUa0#-OMSRZz`4(r$_xF^Y>-EJ>j};=mEigmM zlTR(nan*U9)4Z?2VT_nSwBU{=9=%}aXQ6Mh;Ci{{`3 z)I>u!(0Vi1tHs0a{*{cZLp<7wC*E4oGY^-z#_B3dO~aclj}5@zEd^J>Dk577uXJk=c_ zIHT5=^co@kR~Kxe>+?Dz?~|1};nvw_*0U%3#UH@e*WnA_qN_GUgkES|U1-aYVLRy- zmq0vp$6L%Fek1oJV7omHfBS;1GAOqp7O!&%{F{4lv`!WM7}Qtr_wS7Btv+OzDSvq< z20!bjx+DAHRJJ!SpOv}*1s63c{?wTV_Wld_J_F>}j{XIF8(nzSff!aujZ^Jo4S?~Rwujb#uI2j7z6nuIB51#`>> z?oy*CRGLu6R~5mjmh9hdYPX63e?EaIg}u&TeIRwU@C&ZO{D9uJ%FN!2 z@CdY+;a^7?@hxMvL9!$F#w$(hkq9G|wbHa&Ri-ePOO{FWnxqsLZEIjE{a?H{%osGE z70)LcBsD!vH;y8Y>hc;B0y*+&gz+@|t~VA>o`nR(=m33GDuo(06ljywW-wvs=M6@p#g-Mr8Azq);84a%&4YHZsnj7;+@}q{zCqK{ zpu)M$5?S%qL_rZOj3inV*IYE7YS|T#QfOWoz8=g(c5XSxv8FVbev?bu;xE`rJ01gK z{YUz}C8J)hBF-xDub07Ftq?(ZZWyNK%G1s@Q02P6F;}ZcKdWoB#X*jG%&3A8ve8)Q znJYGuca4;o^)8P0*1K=c8yGD@GBt>3*K_7c6M?w&ckvW^Sx#wflONt3dD_YJsWotq zB+32JeeV#@uE$>EdA-N0dV3grU9_?WfAdT-l|!T$*jcY}Kh1_dWTPqCC)gXjqlzI{ z<90q#@CeoL;?kzz>rMhWsw>Kl0KYv*6brInb0RBlTNHg+NNn~!rnl-X@7)2Ph zm+ydv`@0wd?fx`=?|5o=v>5y<0FE{_8FdV__tA>JwTzsgbBQ6CL@;-^5dsvJ2@2F{ z=jGzI&FNLEHCP#1B3_T+N)D-sLD92lz~8@G!@#_ch*UsK3}nY*^q!HE&tgshHeKJZ zoF?hDyi5lSYW1KbhW^$pE32X%!Bge^>j0!E1&eM^Bw|bJ=W}NE5+7& zc%|0n?j1LEF;)R3gi`CY5z?n;3uM*7HozQQ_D)ZciOe#|(G8dncstW#z3y$Ekg|N! z9MTgmDp)#IH@)~K5uLNl;b#}Z80Z2DQ49;K5zf6pY#N$Oew2!0nZL;epn@lCi;lr z%L3*Ng*@iys#&gTUO3MUeM5rt_P$|fZ?0EwB&9-H=FgA=gg`XwpdrtdrlDM3)k5)L z^Mmi15V(gkBuAZJ{2iHjyC%3|L!IG)yz|41yZU|9e&_NU7b7;!Y8xY$bxDe76C?g76_z%+n?Prtce|k2 zStGtB6#jSeF67>RptUgk=;fWQLQX0djm=*zR8H=NJq5oVE5~~{hj~pty1v}&y{)?U zEy%Gey!&>zp1mR6)DyRi>XaKd9{V&v$V*F(*Xa9Jyk-HN@?J+gJk6N3j*P%|>Z7;` z7^Dj+C7Tn7-@|5J)pjuLMnUKANh5M`m|sV4W+euY9-*_+BL(aw5#n}jCF^}i*{cna z=wa&GF7;Z~8cy}Ec3`RE4)rAXpCcSyia ziNV&DFK{+k-7Z3d+^DFxf}G(ho#h+eWcbk;)b)wm>?E631tLh6ni={H8+ z(GxA_aPh090a+F!x5B54SdGi8ckV8c$+HPd$bLsO|v>>mU6PYDtnoy zH#kjXx|U@<<)P)NpwHHWzM47!`uiE@L+<68^V7o@#^~{K9;^>I@%Rp~L|6C@C@%-N z;6CK8JMqi16SW{s_n`wm$~IdVm*Nr;jMVOk_JCGo6b6F}`MeN$g>be8D< zz|rGsul(ecwobtuZQp8BY3IM-Xp^k?Y;I+AV_Jpqm%Q(>47_V=li%9!Pb1x;#q?iu z3@7h6O5krL;&Ue?H|U;WM`-}e6u#h8Ow1Y;q+54Ek6Pra<0f4qPJ2L~WF} zkc!9g1odmM{Hc5W^N2W1JMJbA54>?F=yg3yy}%EWKeMA>avbG%ELw zFmbI`l*!T-PD4P@^VnVYx(D?My~opRlXCCV&!Qpr#f&vkrbG6t(X z+~o;}m6kw(i}@MDjK_Kh#ceEf|7#NoZr>m4j#@2`dIX)GZmeidCABE7UuVr3I{7kr z#=ga;yaHUv`$g*{;vXmowE^p+PKE4Sj=>nC0LS5arQjgQ%Qw>1KOEri(R_ughb{vG@@} z-v#q$6j$cHkQ~e-{E5`=wL4wHh{AZ}L900HH2tpQq0NHPes3rmFh5{|{c1v@H^yK< z*KEdsj9#`5TLeOnUQJ2f6xpZ(QvVo*aN2m4D<}O&YQ}Z_zPX_PAH4r}_0M+9!fikn z?zHJwYwoG{k*L#5kwyuBXP=toHloE8UJoNn6Phb<9>ljWR9}^p4Vbauc&+?a8au|~ z9%t6abw)0B4}}!|vVFy`MrmagxuOuVj$2!OR}C!#Mg?;8#j zwFz~^pBd-iP^dbhm-$;Knyz)cY>|t|K>t?_+tv%_eK!W(CweV;8lqVP@m#En@Nfg) z7qF5<&{hylGq`2j!GT0tW2Bdc1yXzOBK!8ZLfBmk2n#mWZ$<7oTm9|=H1dY+d312y zb21z^=c=>BJue9o5QNz7b9XXrJ9Bo(#k{csPf88SVtD_|)j)sUBth>xYfXy2JZD7X zGipR$elSOt&?L#9NG6{+f>komDzgmZ`N<2lJ8K-YKTv;4o9U6hr>#p=_k&fZeZ);I z*rfh(W;K%~FtCj*xzQPHwd7N0uEw7FYU2tEaZQMJmi10(m(Y$VVDK1kmygU=TNXmi z=q$z*PpE0V6a&E=NaAPC3tnx$1}z3F-=SIw^9iBy7>s4+Vm14A7QLJRXG8|^fP(#c zzH{K4^8fS*tmHu9Hjg+gdvN^K9Ht_xOc=mBrnBIr4J~GYD#b3Ql>hCkQpPmv0{>Z*hGos045@cg7(uW? zWE?5l%g~@w_AS}9c3$%pQA$OQl0URpCn$9psj(*YqoTc2r~YSnBkOZ2Nkj2{H*0`2x?QwU`B`%|ZP+ty!tYa>>TP^y zyeBFO2eol-8c}lFIGQn!=+G%X+oXqWR4va@ypMhB&o+j01%M78`onu-W~Apf1}F;+ zgGp;^djdydbsMeSvSECif)`|8l6SXn0popx=R<5!8%SGGUa+U}h7atjz0g}UYAZRI zCfd`R;-;0w04EUk&5_wWmJ-kJtQjtfC{iVLCOk=ZAi;^NVP=$pT0bI*SoMq*Vd;4) zq)j@{ENokMxGKdNdZ?{43W1tA(-c{{53W+UK|+CLxmXphMh~dI7qSf9#}h!eMrXI? zp$0C^(5fQOBF|@8CIkv|ga4>O-XdMj1C6|Lnf@M8xZ>5{<3D^JyZ3V#Q*f$4BNgwYk&vxf$+1ym6HQOzZP3(r{}Zx~AJb6->iZ5wUzA|s zBM`Z!3N(^QRM)Ifkv~UBBaL42C@8A?klKrhbH><+w~ayAxJ$sCG^0P9srg8f5hI1A zzb{E$!%%$?4gbOZz~3h($rTWL7dORdg%_cFTr92(Y~R=Nj{3YY+yW&xVEcgZf(LU1hEi;LEayduMSHa)$LOWwiopCXcAw7JeT&E@~bUR67PN z%;^+Xwu;*-cka{wH8dr+%AZY$;tLIN8y@XAb4Q$;r8C&Ayj|2!axTYlyl%gYG? zst$_H)rkc2m{1=dS%YdO!`_{_L4c0$$@qctqCs1o__95vE=}~8h0Q{=tRR3Nhu+Y6 z>mu|-3Yb#x{mjkHco+PN5T*h`Su6_)wGzRO3HaS|0Y@v5M}nXGhX4-*LCzOHwQIH) zzptNcNdrK#LaI}CJ2u?O7QR=-+6fy+5mYA+4S7a7rQuB}fEWX@{J42=o*Y)Qf^p?3 z{ENgMv%KdSu`=ao?+N!*DaZ~^AGJ1F6GrNN+X(D0R=(_%yK^5K&m(OPKVqgq+1W0K zYC_JMH5BNE3*2&ybdCdJq!hV`MVrxId3O)|y}eJVNgz=enpAkSh4{Dy0TWtK(LE=o|erBmWul>X)17l~I2yPmW zYlYfxGsH9}z;{n%))+6vZbBE6*Sjk-p|#_5Mu+R33(N^Zdk9}3##TxW7c`H>5vFW2 zwT&R0nX6dCQV%-cB-S!f|MT3`YWc}Ie}PO-@<>(+)(g*JVaSn?5-JK6Z-ro6Mv`!? z8ej=H*ystT{>1LE1(?#Fy@NlWPU>G{k_q}D5W0P$Qv~Ez=jmbA$nx)~*c4=7`^Emb zOC#xCqpaSd{5=6e97sRAF9+u-5V(N(qfZMzYt02CJ4Zshcg@Ej?rY@SJzaTb_XeHi z9yRV9f|@fq`;s)8iycqK!thY^P`rFy%cQ$f9 zS{;`L?0{ zq5tTr-@|iEySRI`R_phL7549t-=TQVR7a<|GtNpVz-F%=5Z<>f>`zxq-&Q;(yC?)uS)pZ_q|z)=uG8MBLlgo%;M?^F~oU%9gg zVvcQDd4XEodNov`~?^15PUvAtDIZS%_~_-{qQtERytb~~4lTlveu`(; zhL&4?^>@OgQBtdQ4FlUUe+~rYM_IrjkHYi#}aBkx3~88 z6PXb#gI@E#qjDD;A&CbEDpzQ*Z#~lUfLnLd zjPqx(DjMLJ2~azg)C#mGcD&4u2{F$Qc0nv*HLQ9yi6iatS=;AO#TNQ#iHSVrl32+` zb7VenQ6#Vzjsi`JJYYYG(>{~EE5d!+qyx2d-Ie@JAwxAAh7nYAFV;M2b9HIOs9}jA zjw|;QKgGR~GgO^>>@pm@sP&r3o!s6`HYMcSc_ijkAO}P?;XmTF#6Xs%Hjfm}{~=z- zs|U@$K(~L1*JG*4G*y3#*Beq_;&pWCKjO9Gzr<@D;J?Ldnx8p)A0$q3*elcUQc6wG z$U!#x%7zm*SBc6$&W=VrvL^2mR*joUpt7}e=GzjvUTF5*gsQw@TsK=Q$A5>^z4E8& z_`xtlCClxe1+e*Ol)?5$RF_gsg!4>%Dc7i+G_qh(o5XOcz1#Ge(_at}k+Tj)dCkFu zmB|Uvp#dSbYipzpLZGKyco*jXDA&kJ2u7pimR-+`7@)NRu%GeHe`sqzop{kzC9f`* zUhi(%UbSn{-w8WYZT)IVS-H<{QF}hxk;tuomuA&!g(ZNXa<<{Lq{V##=k;Bfp?3pd z6_XR2U{?F!ilbo{THe+X0kwoaUthR@T2;QvJAh|T$H(c!mj>HCXzE?}^}FoH@9}zG zegyyruzl*&x-Y^Zn}ZZceT%3iX+dFvOrBa@&5P2;%9|FAG4xv_{tf}HnL!j}joa(u z%O@YwdrgNO3xXM!jO9ZVMV!_f@AQt@Zx?A2O`22#q4H%wb05zKbVpx5K4!}oXm#D6 zG?USLW|HSlU({<7bm>rkLbs*J(X+85VeFagI>8=ZJRB$e?$<{zSRzuLmJ_u9t^ z{Zlg;WL#@)e4#}+j0%}bJ#Y6|8y+T{pHUSs>WZ>I0DPkYkEKIXG)wn-!P;RYxFKnN z51zOLRNpTdfJed~P~x1_P1nK;H84hnkp^jbLPS1AbBgcE!(21s7-^}I-z(x)rM}ylSFf6JGN?j$3~p_b=@3~UDXE6KbIKWQrfE2=2ZAxDClV&KBi5ew-SjwYZ8yTbDW`Djq~9XjIG2dP)1J2;ZL(cq^sr z`D`X)wm;TSZ)+EgNlUI{+f|)19##v~*4f3f*KtxcouGiQgkUdP^PMCy8HyAaIq+TM z8MTs%en`^_12kJAhhLGQ`Wuh*{RZ=tX!35K=B5*X?S&ZzrW|G;rJkIm2Ln8;RiHy! z?31}WX?pyS>$BRxi%r^OIx=Ev#D!T8`_V+Ds!ljetQ7qzuUnQP;wB3-8*Q-WR=eHnlB!gW?j!}npq za%$XZtlt_BgVqx4Ldvz6FsGVU6@A-K)~S6d5d=G;?7%GDIZs%BPLe|jgt4@2OjB-NhYb_M`!B22mwP9iMD<;|X^%tK% zFhLq~R&S|AN}QF2F$}+sO>X zG`Xm6-sXU6okCa2QH64b3l27>^xQLX!MFRXor8xMENn?yD{g>9T?U+VmvySz9A_pO z3Eoj*n^%}ELL((8AszgbF3G#s8)3s6%oQaG#{9Y(FYAoJImZLA7VL51Mu+iZAT(0_M}W-Z0Ny|Z*&iTPxmfhr(%bhgBf)bH^8PfIb+CC+-T6e zJ<1yZrH+0Fz#0FbP;aF^(_yE8NpiHvajR7eL}%zWU1d8o8qIQmfMFEqX0y!Soli00 ziqH#}Upy}`(lr&$(2$3(vC)(rFz*u^tvRqBC&aJ(pxqHSTjMnUetDFWS515wJ9|f! zp5*TR-zxRwzg24a$H*_08fT5A82`?0gQk@;F_nT5AuNQL4nmY=Om#OS?MtQp+(a%e zw@k0N!N~M3q0si~2)D*Kj2k%$pR8#NrQ@ zvZjM9bwUo9q^JQhc>>c~@xVJ3YLR*boN1&|jc8n8u?j^wS1pqht*oPaiWwHXAf!CX zLt+|BfE;*Xx{5hx>W*edQHaS?%#rB_YgJCEi%Y=Ii7~632W93{nmIU6%JFTg`m|~= zARj?%rP1zq1}4Yf26>nc{v_p)@WDIJtT}UJkTKf532^Qt?Ao4r%HDtEl$(zxhAuBj zMn|{Z4m{?SDOu&{gGW8MzvbK7vBvy@ln!^+)kp-hSj859Gk))ODWx7*Q_x7`yyMh? zP8QZSGb%&d;?X5%uXy73w|mp{<{^}51Odx_z%b$g`RT{O!j&sh{7gFtV@(tT7a_n@ zhF1g+E**1QF^sd1IE{x_Egjl>W}Yu?S+8hdeqgQ7GbTF`_5T5YK!3lWBm+*|z2>}HaRT|<#E&OAj%p;<1@EXVu_ zuJa^H#&U~M0|H-TISW=qGi9?fiOWtZQLART9%N5{suE#(_MbKDpX;}z<@Nt(?@t%v zNRmWRxPS8$F{znLQj;V*s-m0jrT|rO8i58-)%4NmBtd2X(MlrnL_`YFH8l@%pXI*O z_X?kx`4YaxlB<#em`34X5K!(pSl6aF z3^R@^8W|h%MwW#S*FQ)Yeu7dWeC8W)v1v~f@*yVBHr_bl+5!(4_8#IM+h9ll24?XX zCm+mGJFEB^8e_#*bcU*%t%cDlEC$elnY=~oQ`F+o6%Ml>7D%QmJ|V}15i;MS*icd? z12b;GU9wyOHNZ+sEFcF^_K411b2Oe|KBuh>&F5^c_}x{wy^4Fp8saj|)(jQnK6~hE zfL)P_B9N~rU{R-we6@q(21MJ@7QJIHdf_oIwv>sA?9%&%J!lvEM4KzNlmP@JrZum+ zBy`7Sx?+8h7nv&Tfz6uSIsB-;R|EgsA#!WjX)K&QehtEgS|!TSM?4M)g8aVcV;&5l z|7qywAMeW&SdNx{hLzeEZ84Y*NeHdL;_*tEok-xWK>4j14qL+d3&b1IF5|szkAEc! z#z{5#`dR@EvYK$kn3Lu;_sFKXcMS~q+R^9*KfS<2So(x(bkfL1<}1d5+ukdxU1h@o zF;tX)`;GtgyFBj$QmJFKp?V-x#x`7EV<%up6ya=r77K-jV+!R|ZZ;-^nD!vmG!BP6 z%UL@Lvo~a}X&Y34o2VtZD&g=-IQPn)cNAbYK_)f<79UYQXC9*#~*8=E{J4f z68YBbHEC1k(JSI6qlPdQWTSs7He|0^xFG|)OA?h+uGY)mIMgF#?NXrDYQOoZY^=&Z zFyaET1p;v$I79*QOqEF`qXt}c;{e@*z9*yUjrFE{wd(!HFzkNty7vJ{6DT%6;+Yp1 ztnpC`A8@>V2bA<3*+vvdIOr@xAp^wc55W^`^F1}T2dU)2ABY8D%_Rsao!dTIZKI%< zSCs>3&3Cv~-sh}8%txdocNN(uEhw(Uw7(#K=fyp_VL~n`EhRST%cLts+z!-m?j7=K zAgnOzg|H$~|DXk~AR=E0xDXp!mdaI%Mb9h_sRl;SDKer6(BhLY{eXQUA?ryI?zP0_!80IDlKYNS$6En_Qv;u6C|18 zY?{&!+5=&+!Eo-WK#^T$sbe#APUu6#9icE$u%K0XYoA_L`}k{uWDR)7WC?7G;?^?1 z*Gol_67=hHhK8yb?k~VVTM8U}R=AJr-Y+2r&dXS$QQZkUh>}i!0!dgAJxJ1dJNCXfegIlC;MK8Y`Q6Kta$(K z>0+7G#}YsqM#HmK+F9HoN1ynzX-jiWlHwXIZR$*&O!=+R9Poy)C#p9X4qhu~EXV9e z{*CFXZR%NQ0~Xz3b3aQ$gaI~PMCee5_vyb*U3Z`V>(*iS#UBNTIHH)bB=?|;UaI}3 zhf)|dj0&#Ig!SwSHF6Y=VqeHJf#&W|cPc_BG(HYIh^9c$Pp7qC;ZLmF{PmeG+_=*1 z7i^B4)(h|WQ_vl9&02<3DMUolIr7T~Ji$ykoEIjKg~?+UCJ&P(eYI8(C(pFE%IR7( zOzeKSMvc-fXJWgC4!yv%A#D@VyfLO;S;Hg}JbL0hf2_xvo4s+k28*p6xozY*SUQw# z+`_3)mfJy zJG?{%^}7AQ7jfw@0%#@z;3-Kf7#BB8Fu-0yfp+5v4Qib23+-0K53)vs-k$eg-+6D2 zFJ7NqUY?wvb&ihDPL7Xq0>DT{;7LJ>eYh8O)uI50?*oae3HM@t81wa^NMMljZfNDz z!O7|IQRmIYu}lZJ2htF#1tQ-8-#vZrwV1y{V0%HL(h$Lg@A6jk{`r!i@GUXjJa$k5 zYKoJighPs6xABD4$Z^|xP)^~lENq?&o98TSp2i;b)tWqAJMA+G^)ja5%e9M^Ni!3h zMK$0BR?&t1N$KY|XMg&V3>>8zKy`?WlbgAW8egJHuk*vNQlnplpgaft-B}TFL=E0u z8*!n-v$zk2oJHWrLJ4}-N|40}zFIZN&90t_B4ka&m#YeuZwr&hi0I%K>d--agKtCyo*dZLyq$R<;2U56&w~H&ZrSypw-)?=9@m`szeu#ar~&=Vu6gnQlJ&o_y|rWV z|Lyh7Mg8Y_T#Ne8i~7&Z4>p7P&qm4BE94I6x7^I27d>U~lSQRd<158RVH-4-OBz~k zmAs-rUH(QaAJ0Sn+py)ojfMO-k84iyA2&)bq`&8OeRlb8V`FC%ls!xS+gQkd^SBoB z-$MSInf%v{`~9HH-r~~SIo3uDdPiY5TjICkRQv__Vr6Ka)S#y$Ds(KWv$VX|KCvVC zW0>I`^S216XvvtvmY3h77z_A^ymJ)$(!$e9vNtemIOcR|$rXrI7!V;kt9jxu^1^V& z>0m|7iul^7%;KlUolZZzDFu+Hho_I>NhiNm`lWC&mcGP;2T~pkV?Z3j3KauUDht8u zdd)1=@oQGUGXb`h+BQ4}E;Aq)S8af8blD52mudfS%pNK@=fIpL25SL~5#pwRW0bkA zJLDw{xFt2m47z2pUVQS}bhl*%(RN^<^o>Gzh7EnCHYF!a3C?iiFoFL z5sgLzZ?W&hmgM|iFCcYwpC|P}W(l9K_Obp3k9=alZiZo>5?k=&#+d3_Bq`!GPB<;5 zUNdOlweyM;DHZZKc2KAHzku?QNfmtL}2op)E7?wdt2t^d=Flsnb#cnNx2&99c zUsXth!hP!C)>%UpL^F^zl6a7W6pWSEYr`&;)+OYU5aE+Eg}45f;TsElka#M(!HE_ttQ%VtIPlCY8*SLZeoJj>m;zKV_trpIO0@3?*jp z7`_g3+jdb8eWAq$p2Y=CYe8b7)=!iA5vDB#b!vUZ7Xp14#*9>yJgr!PWl``cYlg5b zGz+@fW``J>D=RB?SRsWQ(p&o#3^V7If)`=|BF?|Aul295udxJD8z+sv`fG~vdRIAy zLV;_zv^aY7y2VYk>Xcqo_b`q?n#FR4gD@|n27S@$swpJLKkypgwNqfhH}R*oS^0`8 zxqWBd&f>h`@7mbGDhTwB`3!>rQ4xWSK{?4{uTpi)N{BqNl9fH840Fg`Hnev6@}i=- z{8d=(geMh}dy(;gVzpDwc| z?<@EdzyI@p5k6P`f;Twg;U52s-DbFEv8C`VNBw_cV=I5j$D>4YKHwn^ql4`SKkMG> zbSFQ+&b8;T|K z0pYg1Mj2h}0m4frH*&V!aJ1oE7#!XUDmS+$Wm8!&60H*fmXf2~jTCadr7?USlQ(s*+0JX zfm^{p-+g$*zYLB{#}PK23+|sPQ$fr$HHylY>h-3@Y8Y!$^R^9r&2Gq|=)7Uq)GJ3@6pf}# zaS%AgW!B_B7-t~dp}_0ZpuO8+zyGxQe}{gb61K@T$tt?G9ldJUg~u9gc4SSoywCq_ ziH+Ue>4A^OptP>zf2iNoZE1f&iC-JQ8~haeFL?;^7mz?=FQojb4+GF7aU8)Nt!Ql| z4@~%G0&ddyKXODUK=U7eZvXpVR{j-4HH5rkB7w`cJ!UXMvDORvAdda^d)a_3e=Loe zyCTM#E)!zeyk!~@ul>f`&1X*>SmOWInmzZBMxI7%923o_F;bjWKBigBDs=84jygAC z9}i>d^laSZoArp3Yyc^nWB%%aT%yLe`D7ap_Kn}QCckXtBar|M+8pFW1Yn{8DZpr8 zhLms{_j^IY(7^s4Z{FFrWz)^xfN5rbYle`|6KTrqmwgs1vJ=X`<=XM~#!L-kIT4 zgM^9RAU=NfW4sCGAD7K7e+8zM|CP@uzp>B%9c3Q%A&fYMqSq76o*WlW9RD%HIqSz= zm1wm|6VJw*L-F-!lei{6gL~r7l9?5+?2A7}nQUY1BhI!Q-)yE^K?FV$za}IFmk|Ul zjk;mlk9wUh=!%^*9wuFG4AH}K6tANlufxyjvo})VlGN=bM~ad4BKKPzygA984d~zC zS|oPIW8ESD_5;P6cvq*Fie7n@Yn|%*WYR@>HN>1I+}{NoUq60CgG`K$>AY{v4Z_^@ zPv_@9ogR0fL!Gym$0B&)@c82DUgtZphNWmT&oFi+=#HzJHhNW{Qjf=ls05j7J4R?Nk_)`;rM zXf*;6K@NGxu*i`+E0z)M*LH^aQE4cw?8GvQdH0wBDbmeu@`ngEZQ~!!M&;(?a>#M7 zbndqnwoU1eGZNd0%?8HsD{Ei#ml}k}nOG@t?mNO%b&6D6vO|iAbGx|X(`F$hY>(yGzrAmrDkW}<%6a`dt^Vhc<8bQJNaBi3ZvTq$%)xx}s1 z;Ww(cL*K-4zvan1mHJLx$=>wcsEm)aXcqY!ho|Rnk2*#ehI?QY+j-8SX|t~EFehzm z0pczn-+J$iZQ;G{_8nPxD8q;?VDZ{MqANuV|GnGsH?_^U4H`?3G^e~N+femfhPV!# zaGk`m*yKOQCNG<3ysvOaZrMX@x#qhvoYk@G3H4XK$=ahEw|)Q4#XCzx5w7qQa!*^K zbM?V%k~YIbR+N@lF7-e(D84mnI;;H$P{5S|(t$@mv5sn&r8$4R4~W9phHeguH&w;? zsiQcxw80lymx?jt;y(37I5A2~Y;$3?rl{ol^m7Ym#$p*!G(hTCWebX>#Z#OKjMF7( zSPRUt2n!d6rgD$C7}SobQCk{J@dBNR;71K)^+GCZh&;wZJv;wE-K0o-8F_}0qGY7z z_5o)0QG&2o%IA!qn5dY}noGBAE#PHLfQk$w(Qh>%o7DtDE< z>MADcM|0OiBzuvQUT{R}kf(Px1CLF{Xwucc?AvYFY^zL0xNQ*OaCGu>C(LS%;-~C5 zqnZpp^?tLO{Jq^+DVv0{F;A$P)k3Eg2rj&BhAg>n;MZc^_DO;grfsI^=Hz1BHV(Hr zr6c2=5;vtQm-wh`+}%(6rxk><>NfW9X|=i7*Y6@kx^W$8D!vOK|FxwHcS$ zd<|K#hK}l*tB~TWv9#`!a4WlYJY#moWh}Y<$AnnOVeO{f5Da$fnCcOlaOn)n82Ulf zG+t>V`UcIF73A9MRSMr*F%L(az<@`_qzIYQ;n04JahEX$be_Y0Dsh#XY=MO$SUg<0 zl(_0WBME~V&`n$d)d#2j=nAwmK%A2ZT{a}P;VHr7U)pEC@^`*56!%`F*AB0MmdS0@EpBrEaQfo)5>>kKhv~F$%N(Q_I<>>)$M?jp8d5 zf4GCSA;srM_KVAp(D@3D(TM6M;%v}zYO;`JoA3AuJJ}MZ+31ThE1z>1D|LVLJ-Qqy zk_QK@3}61uj$eeSi86*uOmA87Mx1EL}j2W77dj5ujuTJX0ou! zqrSs)!Xk23Z51Q1G0Wp#YU7CQ&kH7>{XQk0sxNe zLXNVgx)crbdP0+(g~WvE5E~)_4QKM0k1P8QUJhYS-No{GRoq}j6U?MA+s_8y#EA$8 zSHXjF1%ia%rIVgK_ea`BAdV`D>W3lyb^FAlXDF#3LDx@={*mQih#Y;ArAE0)QZ5`S zi;6YlKog)2rd?jZ%o&oTbc*G^)4jEAH?dpw8yG`+b;KP`ga;!9J8yEuj^BYF9_%KWG5Dz`uhvy-sSqhyb< zyCQE?9wN*P@AiaC^K_H_Q62)jBHhR0eG8!ZeG=Ra`+kyxU>SIr&AW;JtfsI^yW$jn zAysG{G2(cIGleEJz#^xA6z(6V-$%eCtgJZbdb2G=_3E$>mmSaoh%w7~bUWiG*RGIR z_u8>X5etfwm6$b5P`p24OiLN&TqHW>3e;R)p1R-){>u2G4UnV1T{~ii$4~IoI~F`x zk1edPTG1896mALDWXPS9awjuyiNJ&{dRG$N2!9s zsvZ4zP<3~hB!Hm)li_s{bYLJzkqqsa@e28|V8@pV!EG!Nnqt{dAAcsR{#_u?2rDIs zEm){)j7f{Y@|6rlex z=*I(*@=?9ujl{$H?tGLWohN?sH0^-!{De-vZe6k<6GCtOu+OI$J!^0~jiWM~K}9^a zYBf{J6T7};B7{K+wHhJChVpLEi7VGPT0oN%s59EUe)B~!=S2|wG;3CYX*s`EOp&Io z1Kv<+V#d&;OsUfH=p45#%J*cG=ctJdt3n`9J z>6RM{X17LkaJd|=jyWtrso4R;(Tp?cz3_$uG-_g{Y7o_0JivlZbw!>cbgBW_CqjX7 zR(kfhO*M?IqR%Bp!&kTs=Z#=rKLk%578+AUrw#skL(r$PfOSZQ#kR`o?uY`%Y)q!> z2-R%HJFy7)r*40k!YK8l1D7NlC){F{g`!TjL(hDHiFd;Y2pqSLM;TbBzu)q1uqeEc zut5xC%9G8xU*zenWD;U@0)EPZC=GAIeh5MUBMW5a!)Tb|HjsueBEwmg=Mk04(Z0&8 zmEM)BtJ)mdQ1yvi$iX_p8>gDBhsRqax(W&Zn<^=;Gh^eoA|R3mhyefn5AZ&EVz=f7Noy zx!|=6pf$B_t?0eZ(SfGEJziCyPCoBZE&Z~XTwT(0P5tAMs$>M1qdXZpI)_N}hrJNZ8}5#&Zx}8qBhkN+nTTolhlq}>XxL3-hJhv2hJ?nPzJS8@SIN`Wj$Y zX&zbXsh~oSP8Y~HQXeKS=s5X@Lp*umu?)r1#9qK9@yt$9m7ubc4lB0RT2t=DWDAdE zGqoiI@lHt>iWr<*)j(FZ-@yMe*{Wf)ac93@`yT>+sD_|BdJ21al;)@3+s=95pYQX3 zoo)RLi?%OXV^AH|brkHy_6V&N;}2t)S=mxn3rLVJ*E&Mb$Ugfn^`h@A#TZ~-e^ zXE{XZHmgRqvgaKIDX2=!1P|zXM1K#<;?g30DSC3qgUSYjTca^`d~5fbw5jtbV{wyF zLSD5-|5R+~UbApR2Y8p{c1gLLSoX%Daw2z^&KY$*Bhwd+RYj1ExPppA32_}5%1TkO zA)r<-RG=H?5vy9lfQ^sH6v%P+9gxs> z6ZuMs-=V9ECu@z{dpa>Lm&!oriquoTgdNh@1HM7|nu z1uko5+EtmYNJqYUikIrdCc!ce+)Kjr1NMnzttTPCgwX(vv#B;a^c6q8=}8o^?xiaf zqSWOiWE7#IL-e^Ko(K+KQe$kN`il!%bKm(Y7vj9urKp)$8!efA7o}TtbOfOze=y>2Y-C z#4O1ZStpMflkE9E@Owe>M|BXr9>cSTWSRF{egfoyoV+P+ta$%!SevBEm&8gy)ywnY;7?`MQns2HC+qI zp=0mUf1L{SKL6LP81IWe3Wk0}$sLudaiV`#1vn|0O1lNGDH(K_(lbRHhETXq3Gl?` zjBnCR!6rqBxk4;<7%wQ`LIR@LQ+N$)zFzZGh}TTX?x4ls`g&o&SQs#-Yrv>vBww#F zqXwsQ+clIWx!+KJ6k0j(!bQE`czt|v`11k9E}mT-U(C=VQaQ0-oOPuB&NQ*1q^v1N z_@&E+vM>OAlLmk(R|IsN68*VX&U9!nD2PPeFIcrDd6TT}azG3-fyqn74_1`U^E?p~g&CjVWRnU$6F3 z!qLX|#^NQa<%uGgr7w@H35}=SaFwQLl8ZH&X{#XB+sMSKhpUN&n|9%*mDgv|(!>V~ zKk33x`izv;5{_I~SuNX17v9pj>D2|h`@&)R86Bpd)r`OrI>C|(5}whC^wUO(@U2wY zQ4&UJ;65q&p-`x6Fslv-YBYfoRQ z=VzyXr@R)Zi(;CWEck>QR0J|$A}ZDC2QkjCfXsn`>VgvO)hzEZ6OPk=0YyBN+8#Y8 zotmkyho|S4$2xQk9xiOuF1tSVj#m=JIr2lPHVk)OfF^&= ztF;ecQUF2Xce^A0>U6N3P6zb=PDdV~DJ78B(#p~w7T4#y+H38#zn+4;c^XC^X4J+y zT)W%b^ezZzp=5qzV!$1bVmKrt|3S?iRb+xiQ}y7y{hM5=p{7lRiR<8 zG7Wom@Wd@iYeE}eE7Hc-xNMNFnbLyzcTF;+bnSDGcyX!MJmw!4^~;@|!u5}TZ*0F@ z-`(7WYvT{=TU%Q%cmCk*%mV@6`1*ei{C{(O)8zj+?XsH@^N~c&p#7qT>~{V{e$_#c2IqwC`S#ki1A^gLiw7g$$4ZrwbPTsB%@;2%RX)0X2l+=@_ z3dY0-egBaX*xV&N@f`HvF(IA5<)!g$_UI=8K&+fA{`& za(2`b1to(|n6r`6@q~y*bb6q9DbP9~TwOewaTmrF-3`$Rc86IL(Q4uiFs*5tl8+s8 zsJ`&};X{~lue&uUXl99fj>8DyX5y!)cfQ0@9Y3i~=7UEcKvK?Akl!nasd#?q4Ny%ugGnH+^%H_BhaUFkmP!%$PUJC(kkC;da)5kBeUw@SYx!yIb? zKV|MH9d2mtR!mW#Tr{Mx$|uE(QLzhvrkVCQB10u68FVZZ74&D32yf zHR?Jiaq#AZzt5b?G?rd)8%F%Z1tsO?o&_XZmIWew@RKKQy+jr%{V)0>O5WO!eNnu` zw(}A{3y8#IqHoF^2YkZ|MLO$~jM9{*%mvzw`yLS3Ev#=!2g~iU38olD;Dop)^UuPV zZiZn$^Em7*9^kI>^VQXxwat}3a)&t1c^G5XS!NKG^>E2chFQwnVpdp(m?xska)a*S zqGhyC_DFDgOUHflvNr=0-Z?7C9r@C!5DP~j+mxh&QV zFsZhl{dTz!z;wzsxB*gjo;neI%Ej}q|(1 z3dSkLU;)aE>Pyw77_4N5)}$OTX_f?64OLVj!M8gBtOMDeNS(8X^=kL7)!iH)ceIu< z-!3+Dt@n;632YWD3hG_VpMfx!Quze_5hhaR*@xXRJYqsj*;`MamFys#p{@aC?6+(Pn5#N0p0+GxY9!7QYGMedu**Mt?(c- z?{8+qJ@F))d>*oao#jdLJd;B6bbh{bmb%l8!LXtVOO zm8W8}a-5Z?GZSUXcv3dl_Sy$;uYT@a9-hBBzHB*G#J(#>n*c*e;1GzA^L{?RGy=H= zyLUUs%c>oXx9?78vmIxL9cNpWqKy&#uh6WShf#S{R9*=+C@oKBo$lKi^^~t<7v8<+ zisU;g=G|gd?u$B-rhTzEIt3Gh3J@Po^{f=91)RLEqbiJ~ym6;KGR1wRT|Afp%FFS`y?LT z-E$EUI{AP{F3@_B8s*d+ib`>LHH_J{>XBVvQ$(09+c^$Rhp8;?!b5-+J+fWDGMfch zuhizO!B)`6cDWc}uezfEi|pW`Gj`5Gsk$OQau#sQ4=uoOM6Do^;uLxOwGt0bak*%- z%~55OpxU$`EXE8Nx1%CV1`o5K6qJ#otob?X)#^IAN;?yA+m$<-BZwFd(pGVOKy#1Q zMzwsEI#i{)6Tx&Y+(8n4#5b@Igy=wwrtrvnbNt$4A<%8K>uC(lfj5g**x{5jEvg-_ z0+G&Z7D#ealF+fHEje~eZ#25 zQb{^^k#%9;e$#aloBNGSVNnqzH9F7*LkGNCq9Pwk6_dJ2h${d z6+Ctyrx#t}q6&T(M*FODTv)-XGW+m9=l6C$?Fp{idp)|Mxxz-G@TR5ecAPViOMJ+1 zNfRzGNscj968IN1XY%$7l71+bBaadQX26s*|!%L&EsJ%q@z6xGjWuj~xTI zb*mRv|H$6-$b07negb5aC?|d0GQUOf?idQKm{L*oB!hYGm-3++Ws|BaB=HtKdVAovFU+dxI0$8xq=_6<(G zQ!N}0FT$u&SiE~5h~xoECKMP=K-sRyipx#15{5K?3fqQL8G6Az{#s|ryFsm5iQ4Qr zEks#ST`fYLG#Y7CR=1j#L7Xy-*Zf}p`2Bk;V>643k{n*z(Spp%jU&>UQ6L|NK~Gte>T2$|el%mPEvk4DHOpvGozk@VFC zNf9Of#M8IIj5JVrmd!Wd`&IaU^%fK_wtF$xU6)tsMPG&j$eGFD1&dpuWEBA|x;)hy z$!4%b)q4~z3cJuhkg=ihNNpe{<vZ1cW_Av63rw;wsmKK)RisG2tB96ITmf>v8qBuv?CdYk8;4?_}YcA}z{KN&7 z<%sO$6J-N7QoAazn)_J}R$*+V*e>F9wKDOK!1ZdRPMtLa6hjhu>;*GaHq;TB;ye=K zSF+2|F>7OZ!8zy1Ijfe|h+MQ1+~?q^Wkfj^bFD$;&xFrb&qoo@ElUqP0;?@a{8h+e z&CsbFe}e#f`-R zOGtNg)@LmE_A5}2S#r%$cwHf$m1u6afr7<$t7Zz#+TguO0z9-l zF&J5_+4(unF?cuuJ0QwFPtvySGd1$}p&QetE0^rNr&@a0*9C@5*VpzuiRgKeUe0am zt7VEdOkdQAs%@$MaH=59eP{(#SbszX0OmE2-<8#(c9yLXuL;dcYvPV}?n|8S$67<}2-!O?M~rak2DyB*-{(8R`sK zCfmceY&i+Lm<(mrG6lw#{L;kn&e=hPr z&*_@K{EzE$A^Sg<>+{S1JL_8;4*7p`A^*?gTFCzk`F|Gje_19Fx$9||)=BYdW{~~-`9qf!6|SSIshuC;M{NyI z{nAyQ2ha_C;JD*TKDvZ;jY$hIYa6rN6`br?>BN>*tGM%;{yk#ep%xu*d%wil??J}7 z5Du`eRGig3|aFJwMX1+}wt?<%(O`st8b zbwX8U+MV#%ASdIbF8UZ@%P*|H%>1&l#Gx#vXNLv#*+jSD-{x)Of*n@r<<;HAQuw{$ zDwfQv$Q#Yr#iFsVg(nl9RYzms2&Fw`6go-=*%#D9_Gf7q*(+`o)(UxkcId3#>v^L# zKR;T>bl42@<+xvaaj&c>Y=KudFDqg$`?N3r!i@*N7m-0DE&ja`imv7}x#ty^IL3$u zc5@WSh49{MQB`k}V3n-;#;#c~)_g9{c`hf~@p4A5@10ty-6W@50pupQ#q9-NdtwJQ zalUxMJLja8#z2-YllpAYn!=)E923r8G1v(w&o#s^edcQJ6V}}6ouSDneM3huv^rZ1 za~3JSWG6~P%5=hz!o;mAw0fXT@Hxq&z;q}q`Y|Cvs$v#YzCGSnXiY_*z zTv$~|_!<`3h|{?Qay1P%d9{^`8a_<=owR!obSlXLT|TKn0U8gHaO*IW;so`JWaW!w z<>MzSFJ&!XR(5eMBWvB1;!TYcuFw$mOyX^;QL9&@cA_++Ze=1}=p*B6_H-*5bG0nD zN-|H}@(Pjz+vBP^o<;gvd3~PrwZt&K^!&BzN9umcv*a-Gjop;71Bh;!VBLeQEqOqU zS)FLmZro^*E>lmmR;Z!rZ3!To792HUedvVCvw#pWbtI(AYw_X#!tpHfnUq)tiQr zS?{kY>aAU+(5CDK+Es-Kq^e4qbi*54b&x!D7=tkn2B&#|g1GpxUE?MW1x+=*j+GTN#eD#BW`gI@u{K^)IvZUty<0wv zfkLBf6%QUzu>P_lsIOsM(y}qj4DA>k0+6#TX$p+-zOLA3r5nHDy!`$f4Da_wn?)Bi zbN+}30ZtS;5-*DL(#{D`2C~opwO?R!ysyS~wQu{VIz%0n3Yr>8kciXG_Aw8(qgyL3 z%C|k4Y{_)#WCOFHSdhl@2Y%;*gONyjEYQ9gZp682A(|E4`4;q%?0vyG^%@rV{iX|T z2FJkckRrKBoqRATv>Upbt&l5N^_u_Fu8&uj+U_y2SeoBiT}SUi#`qA|mU7tjwF^Gz z415CI(`F0rben~4QB@t5@spXz9JvTqTcNrcH*BTewN0w6|{dachtpU7)jtzZPP)ag8fx=lxKsUsz#pV&YIVE8`}{DjnQ( z>U`B6+)%fSE-B|C+i(0t={s8VGYYEWEws4%wlj=AMDZhh76$!Z$|M@sC>*?^FnXAE zO$Q=nAWc~*i!U8bZz+TH`Ba#)UM;klg*KyI->f!ME6V(vRBXnor7;C%r^bv-MeiwV z$Ew=vEmWd~N;H-LFh%XC@+8O1HKpo-K3}D&y6>M|f2!`{LX|SEg(@`-RjLMOsZ^_; zL9rXN#7#~vFSu~PrW#~$k1}Y1utfou4^M+9xDzdBUK$Tz!^|iqx#tB@JiMcD`W{y1 ze1I=#_g+rDyO_c;BdQRqhB(67IsEs3XZ!9W?UXz%mgjrDr^tT*84(s&&MCCA8_wV{ zVPArd* z{6#sz>dZ6($MJK`;b+oh2i8C_x*}DqTN8V=~>luR>4((oK_X*j|nS4QM5I+PYuVBq|(6VGh zcB}}^wMg-i@^tqUcmeWBKDvFFUU6OJvz*3bZF;Gk&34+uhEXIO9w##>Hdx0Eb4nFcq5Z_T#5Xpos zR{u_JB}ve5c+Gk)yIx--JBG=Vbmx-@9R_KRDw`vzO$*Xu>y|O5%ga-X-B?h7g00;g zdV&O^a7mHf#{gNC{Yk-IwKU)$Z57uCH20`qAWk?owV^6Wq6j7_)+R_0{6FFwAA%=O zbRb53GxFXXzxKF4UC$o{Yu$l2i&j`BDO?c-8*)ouUb8^x!ayn=&sOWg#6T*lJL%O} z45}=D*JM*!I(^Qmb4-=J`4mo_r9?WtCejDW=j?`8AOfT-i$ZD{M$c#iqT(@r*ysK8qbHa=KaHcdqjf=G zN)L{PY&!{ZPDdIH_JNi$EHiZp8GS(V*4|(OIpO)UW8x8L(QL!M$82DH%%6K@;;Xf|x21Wnv>YizXSJ_(5am3>>0Vym=0 z$39-CLAAv&6^ydk6>_b*+ZmkYg?B;>S6A7nppcMjK$0_OnUkh6Q)i~;#-lM<@SFZF z#=e=IFk1{hASo$@_n9!vs6OeH*d@{vt?o0 z%KSBb=OKc%xUsq2Aoc+>;Xf5GxZv=lsE`GMD_Mf0x%j!DLj;(!eERZfz=QJ)n?vo5 zgMivptwb9-*zb@>-)p>_Oh9D8^glYRCn|y2$vhp6Tn3q27z1%z2=Nq;>G`&9^}^~O z*_$4D@4UcIfQ%C5P?KBcwOd90s~e7Ue8!gvtKU}hVE0qTF>!kc&a7jr=F`e5?BXPnX^N~otTwJHFT!IIU&K5+4cNK8183WTKQ69Z ze_p#IV--p(nEe2o`CIVx7$?2lNz+o~lYC%K-zi`4!XA~k=sXszu_%~DCl@L)r9CTi zmi)n)sv4YU2$)qVIA)EG&gJ3xo8!ycs*09o9)YM?=Ji*_ z=4Gl4jstIs{E{EYDctXrbD@H^dI7if>cJJn`~^#J+A6gZNNPX6pu>4djuSsurKH2E zDh(bkQgv1GV_3pbY6S+uQi;1E9TKxNISGYVm)GIi3?p}J{ZC!2i0glf5h5f;OU6G2hTYoKvjHs65nSK<5BTiA*i z?`1+nmv5aIDWCvSPOYow>xi8KdG`7Nku~YlOsYZd28%$wN70v{#T=}{ z!b-9I<)3CPXLVyG#wlfg91!Pb;#7u%DUyRu0--1xcnwdOBF7}rBMI&R1|?0vAej1$ zaddQwYr!Mu$0Ms2(TM!A65QwDon@3b78|WW+RuceR?o*5kZhxzeby--VsJ~=sgy!? zth7$v@u#3Wq}pgCh;umnC|a%;_`L@__(r~nQTSqgjEL)hER4v3EZE?5*kA#*kI4Os zpnMLd=OVMQm|Y3Ij?UzaMc#gu#1AYP+$dbF5YKgTUTAY5^IqWNv2tx7xJI5g17^A` zbB1cmUc8>gDk$O>&{+9i3J(3jVDah@RBs zAbM(9nN3c^v{rtT&z`PBB-*H%gSd9K4Fu<19A93Ik#gfK&VoHPkp}#MJmVpN(c!ui z2T^*kNV{48sqMYR8O}g?e~P*?EWxK=>F{Qiz#tByGz^{&-oBnJz{!jBS zZ~nxF_-Aak`Io(Pjdt;p*CV+ibA*iu}V;dy?-Gjg9ot=Yx{LAr0?i7*Dc0yS3ctFSK zPWvv2hXX2nqy&`n<7u~z-|`9n9fr#r6~{OX=%X7vWa@I(ktL64D2L%_<9_tmxI%{$Cv8iST4hOziHiQa1PP%_F#Rrv_~vp;V|w6##7~Jt#x2P;sZlahM-7g z9ie;j8VGcNK%8ypAf>wNsr~k0&-+L`7+KMcD}s8 znqC^lkY$u-d!!q^%TXp$PS@T(4?Hco0+k#|V7FP?AX zRVuM?`fVE!s1`3!afv(#425iX(z zzmn^D#Q!boe|@fN{_%f{(7)$&eg62rjot0d9XtN-Q1DDaq*!YLdkWW>dfs99@J(Jhw_?OO60B%)wb6Y17omW8a{Sc1Qfx>8zAj zAnz5H1_zTme^HFVQDg{&Gveo@xNW@FiewoGlPx0h)&Hj8TL z3B)b7%MZucQMGEssD~K>>M_#dJoOI1j#P`T>$~qXdaeGTGGAjUgxswY^o^P2@yB`b zfFdfak4jEWO>>adgV5biFTA5TTFyuW07Z|BZ#d^xW?Yviv?fM_mEW5Ag3U13M|_f1vW6cs?^Zy5`{Vk~8IP$b0^^FhA688h}!73SNd z!EUuR?PlFL_i6m7g)a&$J6kugU4dyQj3&A=SDeh-xpP=a^YxaT zfP@s@_Kx_@jJa)4mEGRn@|t+i>~ckjq`0gcXAm&O&7MqVLwcgE6#P4Aq(uI=!z#rZ%J$2o9zd~n|g zOJS*C9Qg(njgfuZMo=71L6HR)9GkTYDIg0Uf_Rt}lp&~fioi(APo1br^)=4Gs$kB2 zkOi54#u-}ysJRX4_ljgim?9tVqn(iz#Yvq>Y#nNUyDds}?dj|M93^y~5iCz_#y2+Q zU@Yv-=O{13R-kY2)M`x9H5+8=t#VjCLdJa{z!)>iyrsSPFPi);{$}EvD@d(4@ACX| z8MCsxb}UR;sy>@Eq{-dvg^}h`kE&7=;Ej%?&z~Ii%f;Q?Qy&(f%1D-0h8#0_;xy4w zmISQ~TFsPb-)vyh^N9c1vEzSs7x6#yxaJ@Kb8&od^!m7+q+cUCzqsr3$N#KvZ0@X^ z@jqL@5*G14bGViifja_0Ib;RH<>7kRKTEHrrR(wym8y$Vc+iiBEY&*-{*oQEmsY*O z@TMPPW%#h)^W5OHl%*_XJf-uYT)p`ank;iq59R)ADuOb2x?UNfjRS;wa&9!`*J`Un zuZ3~mCNBxk8?6~y&6>QC8I$rBN$&}xh}0RD!iWKVeSG!v`O&rBB{k1tZ5%jyLSwJd z6VZtt5Yb0riln?4puk1hG6lh~guEDRW^`SEv4+5V|GC%6*Lpn*`ES?G|BCUS3;A#M z*PP@(VvQYUgjocCKcnmO%YQq&>zgmF`0tI4h5R>2UO@WqIT}ujyaz z#BNda$NMGDa1JuQ4#|34oZO&(^Q>+wZ^jpO>iG4W z(}SzyJohoev|#O*jiPP7uEBVHb$U4}AnhB5&ElSygDn0~hx_*I1eWtS~2GpLpvJ}O`*0JX;xw@?CxwF9!>LmYK@ z%=6eNDgmR8XG*PA0@KEJ8}~sP8h1#_*N%~l3A+e})^CuS{fM7>7`OKp496HIYNs5M zHXad!Ip$E*&mE%}7kVKOt?!r_c#?V0zIXI~Z1}}cgp=RQtAu`j3OqK%LW*HxDV5l9 zsvhYE-?6w_aazfUTB0KJsIGV-w38`@q1;=CDJ!p-2aRiCkg6z3ha<`kG_f-lEYTAk zlrUpgg)iVk@Wi31pJV^`yn|jZylx)p92!@0)fJi9LqLGy%6FU|n z03r_A^t%JCSU6@G*%T5$yVJoFK%I`8>Xbe)GO-E77Qja%LyCtdGQ__y9F`6`&Xp3e zx7anwzY79iPHPq@bN# z=lOvqW+YX31VH^GkDHai#lbm8M}kjbnx#1$@hX9#DA~u5KT^KVL)wkuXmg@X>UgtZ zpaV@*0^&8kP>u*2y%WrCgPpTz$fhjxJ^)$D0gFi}h8G1NgQQ`j9y%vM=g{)Gz~f5w zCsONFD+eQ+a5SG+rpPDsbxh|ZGe7L7qNcuhZbKG+XYHGWYvkeE%f9TI`AaI>hJMfOEmVbS!csh386@Gv!aBhg)t8mE;m;? zHmTG&hd{@2Z=O`XDCD@Y#F4yh;+!=bD#0{A&&3Tl(nwkqSFS7t$7zqEjd}tsV6e8m zNlaz59d$HCBOXQ}I%k4TFMjaDs33}5AG`R*W8X|=_%4{%YMvM)#%NjRWL{gOj1Dt~ zmm5AEU(~H0H=W!rS-wmp4CZJdR$AqSkgT@dZdbkip3=TFRG&n{nari8=sVj)FqL^& zI0M5WQziEIKt+%N-qUBKevd&n(ivZGx2#z_*DUDZo(?$J++;J5e+l{%|qm{N!3 z<1$oA-PNfqb_{$T#Dd~5Jk7=gS-KEo`3Y(mk#mvg zlq*nkd3oxBtL99CNw5HN^b`83QHNN$#RNPJ+$Eqh7CcywEy~AJ-WA6bZVA?8NUoD| zr-q&jt|8^`Hbqdd4bEhU4m|NLq!|t)^FIVcyItJwQLrFmf}`&aitY{*JPFZfF^@d3 zgy(#E(CwV``XYVTbkcWCUc0G|OvTyPf7YxqD&OKBUZ!f4rc2NvbDFYLzM6>>guvv^YN`KZ?z`$_ zm=qehXT|)PfrVUcGmy@bb?os7!P|c9XCf%@eO(~%%f$by9Woh(~t$^U-Cn$WvXTAX!oAyMV9O5l)TXca$03$gf$PPTQkwJ=(R)pZweF^-nKsM@1zGiE<5kW49k zLPpGrR{_rv`&7zAYsO@_=U7C7>R_dL7?1-fdqf|!IU3Kf>C=vhHhnf%{O&5;Ud63v zjV1F~Gc=d`?4hp#c7>#hV9lb)RGltz_5oTUP<+S9MI2k*3y(S7rN~ueG~X}mNxRBz z+g!0l86YPy$$^}Ap{6#|73+h%qElf%ig=wnF&~vnY~X)8M1l=FUx%~buR*RMG7^=b z?4IJmP0$(kJs%T(2vyTLB^=1UtUl#v@n=}YebFX^?GV1uNG%?(lo_i8CJXfKnlaIp zJ4=CFC0b{!z3uU@L{T=WpI={F4FGEuek5}uz2+VnUiYqn%U?U1zThWQ+Po9o{X^e! z&C)aj+NvpM+1@Lvz_o`Ov|euWH~z}+ARaqLAF2m?Wzfd;HTD7qM@6ly&tjojam=B> z%x&FdtJ5B&n(E^atodeuQuPg4kJ<)p;GS)X(8{3)C1`(T&pQe*fgqFL0CSJ1C@{xY zi_!>2jx0FpeuO)zF`Zlz@R}q8@UR?llTk;Q3Nq3^75l%}EZqMA-X+QGDYq}k-Z=C$ z+zg~-udaFABSd3WPK^`cNcjz5LOuVLRgik4ACN25RtD2T#OAZIpr!HO~@>+sm6HFdBG%D#({fD zn0~-Mk!bcLXENGbC+NYP*KK_~@ zxx;*5atyYSag(0k>!qSh35G6kW`~+0ZZyDLTM8U}oI&Q=Xdau zp8$OzD{qP$E8f3*x?m?&!~~FshY46K?JVw)zfyeJwB^Aj$$^cQHif2|sQlJw4|qq| z6Ga^i&$X3GmSgxM|Hkw|H}&MS0SjcYxuYdx!T_5tVsvQe`}AL@`n}Kpb*t6;;*SDE z98q{&l7|L}UaI}3hf<6+Y#+6nzMv#ROWEMt{N_O&<8$@a_J-2N{S)Kb0iA;jR+Y**{&FoWBkWld8(YfSa`^gOc9@0jK9WwbdGHt*+u) zhwHj@*e_8(tm3}!7m5p27B7dP}@8H6m*AN z?#_!iaJfBabAImu6LV3WnuS8NP>5!s5EZeFuUro*VQyplh6%r{o&AP5JzVzk$U4<{ zdXlCb70q|CPBb%Rrp5*{u@d8IW8pMjIE|m9;wL^>cx@M6+h?Q)m$2!&`fu58yYSu4 zPd6{v{1@)q&+oo{4yK4)Ip}nJ7*&w)Q_7^|HmYRzhO=_03-l-D{B!WB+sP=iF#H9~ z=SE>F3@L=@oQPSeMd-5Qu&=7?yU%tswH(CzMgrn?NBq_4xayx(sfc9-)Q_25N z%FtS28<^$)<<3rF{SW+G%m2T*ySe%D58lo^5b%xX|DWRg#}VxK1N+8xvD-? z6n9t>H6zG=P&1)EzG9@j#~&mc2|EM{Nc5u(3hNMLdJ>knY_-2!WET_}z0)>hh09DL zeek337HyGvz4zsxg6y0)By)-9pycd zA-}AXO@^P>%tFa!TozDQa@xfPrx-5@ge<$Dm_w8drkVzz8!uIxC70LPw!_lMFfXn& zQfh#%uf@!*{l@?Lo$p{eF4un3HniV)+=$HkFVnzE0(ymNXRZUWo0nG?Cucw9^AQan zZh~ZggWbs|pknsNn1dpSb*6!p?yH^%u^ePpS!|wJ6=5d&&;vd{8jJz&iE2i+XGICr z8K9n%q7S8s87hpj^4yZod*pu#ABGPc&qyTK*Dg{tv{F&yp3x7y*VeK*iv&2g!6UIe zKeBDhj+UEtpAZ^=wY|+VXqGoT^Sc`ijUFis3l9XyF`vt4T?wxz|E^1mOiOj`~hG&=q#Vr z1A5b=H_<544e~ORXiyG5hVd{p7I_KrqyM<=z2V6@=s2^45C65y70652PC2|uX+O&7 z3nOd8uZR@5A4WbC1+d;JrQ-C+=8H*Xa^Hm6Q2BBl;sW<62g^N6okX;uFDeOH8xbP{ zHaJF#3cKdhM!xsEvR-`9$lL;X^%KM9_(tQQgoa`7UEk zQ{cRk29dFVC_&!e5_l(PS6iDFxJ?Tjjdc9}ZPniy7~V>@29DV2?hOug5BXZt5ZOj` zsoG51bfGf0C0md^ldtCHNQ35F%;i9E6Sh_HEHf#Oj9^@i)&k%|ktnRRGuRa41uPp8 zDKh9=fj?pplrzpPb1z5EL-fT9Fj9li?Sz(z|40Kf(|1}XOZOD*nNsyTmvH!AQtd@B zK<7)(NxiR+FE0;%IxbpXcyY4ZFBU=Bsxc;P{H3#LE*-n!!o|Xc1XWz&BITb%JPc3V z)8>Q?I;ymcq-%bZf@rX|vA(&vzPr8o=j%>~O$GP!U$JagN-iLghbIYmP9~?Q;P)7> zX1*5C;ZUd|=Piun4tYzVNS6TE{rkG;(sJ1f<IQ=A{>&$TAW9ZJdoZdXg#oHCf>>Ax%Tna#_lc!Z|42xcx+BAWVG2o zZc#&7M+&C^%ISVUpYAQN<0{q6a{o_pnOY zLPymL)`W{sVtJk{c;MKP1C+*J#xKq2C`=9vTX@9v^ngr@rn>)RCIgIOelSLf<$$(3 zU5p6fd1I%KxD#mNP_*E}9QMIe`oLl>c=kGB`oPs{42D+kc$iq0s93gWD7_D9sMA|t z_~Vj8Em~ttgyt_H&9}WvH7<(weeF9IbE-mOLDT777y*O3kK3GT&Y_M4C z`D4(b9FEPKIPMoqHu=5}EJa$p=t~AqrxOWW?82!^lr3HyLqONf3;7~8Of^@UqUJ+4 zq^*!d-|G&@lpW{r@OZZX13kjy4WMS-4x?VDhuL`@_DP&FbL_f_kiHCc%(H}}lp$1X z{ye8_m-(i!O{z%7hM|2N3**^1<8};79W_S_=mht4wqdOK_ECb;`qzPBOo$-eJthLT;(qF_M0T^x|(@K*mX4G`42cElT0nK2`?p_f}|*t8ACL^ zzB>8O<0Eu%{mK)FlbWJvmliC&4=Gb$P+u`&=E8#LoCV8LYgF>*wd4V;n>*l@9?F&$YtH)m@GY?0*T)x~HwS+| zIs2(|aCr6h;I#AVxM267Z{)5|lMSm+U3^AAoDeMXR;SE~PL)^X2vIp!#b_ii!;2RB zo-59xVCgOw*|zcGgmw1zwQ&^LvaaJ5z-^a#y{Kh1Y+B+^aDzQhS@_j`v>X6RH#g1j zZRQA2;9CLQVp~v5AvLxH)kdN025cMX1K$w4fcFq~licMxz~e|-!IUd@nwdGu@XWCk z68UL@rZ9(l(i|>Ms^s+d3fc;=oDqH8LgD5iPN~$UkUyD3DqT*Qrm8;9-?6fGw$-4&e^T zro+j_rQPB6hCjy1i8J6^16o2L7Srcx+uPV_t*@`+|E!N6Kqg7yg@2QWFclEeSckUT zJ7*bCc#NerAq^O87!1a|q9PF*Bh~ z435s7cbHm#Su7cz#r6z|>-6N+@zu%e;~a|1z(8+?w`^B+0~=XZEJv#;Ln`A`Z4k~O zNNWUMB|@dL$mbzRs?E6=Gm=Pse!RO~#gA8}8eNP3HC_8th%dqalJ$NHVP5!O=~J~s zba>LC8WA}K4Q*=yYJ`M6u@{tfyePtF$Byt};B=&`UeY~Xuph78UAtWks$^Ju(HBL;vyo{M3f6FiqiN*}qDL+E^U!ld*$KH#TcDXm~KjAKg|( zW9pe=cK$u3I(AL6wiNV{-;hd1l0x4e5zOZ`Ol4wo$U?d{O9`i z=I-MB=RB^(`On4q&#&|RC-eKT*F($%0y=4DaIBI#l8MaQ!}DGLhMK4cJeK~4Zm$ixMZcYTavtp)1$RD*O5BWb zlBfRh{2NRL1neF|_J^W0e4nBSl`~GtTH&Xh;-rTUxIuue8gla_0j^zk4_BF&0&?*? zXoFISGIjlonnUA0k69$Ap|72o>%~Y;H$#Ac#2?av!UmX-gur0EiI!voUXx;v-d=*l ziJ2_vpoUhWm+7O_13>+4csEQ49V>L`Lv{gu2J9{3NCF_I2k{n0iLpQ)pLK!R^gKC1$YcVNgjHJXHiaiKmgyfnVa0BF+Fd_6g(Na7vnh`cId|} zF)SSyaL0WSiQ#ifWd>Sc68iL0oL$DmnVz(+vAljmqda-2E~#;XoJ2>p;5C>?ma&ti zs2$b(%vl!x`vySy{X>9tfuLLwi_`>kYCx}2EO+`@h7AHohmEv@hc%qhYZo#yqzCGE z#PYKVW2T(-J+r#H#tHnK7wAdfbiN?2gjf$d(yDL)l70RG`f!RlMJdDNN8_lj>=*G; zWL|y`&mas3oEV8i~0|EtN>wIewF*gTHGTbcB>BT zO!z z+{rCV>L|H8bN3-Y{*l5~Ey6(;3XhXqVLKxy3Z7(;XZ8b5w5%KLk!0H5Auw;+17)1E zvKt}=!lti%#*Y*zcKzU1*jJF{qnj>_dy=J)$4QmM+9&)+ac%*$*mE!}KuAThY>pqh z)KSvo`!l{t(kps}ab@Yfq=R(wG<%rYF|=?SR(~$7FqxJo1_0%eIef8WnbKVYOc?R) zM8qlw2$V)4HX7sHrxXbdzFO*hJSgC?oQOtH4l^+;0DTM}#f(oWXr%~|KqLN<~ zc+BbLQX3^+ZaXDjwhtzEsK8Jrhip4k6k(;FIZ}1i*igC4TtL;%^BSVXo`aUhGb?XZ zwU3uDINOb?eKh2Nv5ltNR+r4}MMF*T9y<1V8X3e&lv?0L>j zWIS4WX;X|7`qygwZm+f1{(2fmcc)?WVMc9~+ke;BH+HtPT#)M<8@ub9fACIc)F18o z#_hk;wEt@vv&k+>>8??Nw0r`K>v>%BnEwj@&+g9VmYM%^dv}rlb1v7y|FiJ_e4YNE znifo%6IA0~SoXEhn?yedXj0WisfZTy%*wq$tPM_#a9PRTvi4gjd-S_;K!nob$fq8Qfq-elRK>sP^YAy=FMePBji)*@0g(^=6BVp% zQLdpJXqO-ELYPLO`PH|VT5`JDUMW96SYu>?5#-SA_mcK73Mro!iotnq!c3<3(m!Pf zB%e!GIci@8 zOK>^<1x#z{3!f3|cGMHhSNF{2!%-%G{QM@kU#MPA&hthcuwa(Xq(mZLmbrk(=yblx z8NRWp9t)X*AzV8V;#>fG4h6$OWQHV<@$)|VxjJF6r^3)^@K;YXsJJ=P$iQzi&Be;vFICX zX2>CRR9GrFXA3Mg*X@7|RNNa9NAm=eifHxdn^~Z`D9rZsGytkp8)oQ!1Ch7o85url zgF_)7CvSKohC#6b-s{5y0V40cD!prQ4#GyzK7v1tF_ExLfgWKd0xV<(8aL`q5pV+3 zYk+xT7JgonjYGsHh#iVlmL|x`Z?6tlFb_XU_dtUhAekXf*EcAtf{A%b@kn>NTDA=5 zHtt(^zbDl&DgXcJLRDosml!Lhn5JYI8<@Eer?iMX z&0>;j@@7l=;-{DsRbYvQ;xDjRlKj3VBb^!lG}xA(xpaO-CRbHhM^|4B`+ZF6C{$+) zU-)s`pnG!#^AMV{1>DZ{=z<40xRxUfiz)210o+m{X$*c315&Or5%*k{mx{(Irl+rG zcO9?%QW@as6=JHT!rK}bk>0ac;b&FqX>8;9sFc8sextWH%@R@0%20QBQovU03%XOM zOw{!2!+dQKKl(LA|3ANr@n3qlN7eby^_OP-&y9_Z?S=n;9@oPEzwrNmo&JBpoCRo- zTRRVa`oZbDpCojEAAFy;|Nnr!dF6jHy!iP8htK})05z-9SFkMDNH1vRMm48?{#J<# zpB?l}+2KGE8I?1g!sg-~fQ}-nI`B2gq;he<&P!r>LTp-9iIk4H-A#?()O`;>-M594 z-y532iv%H82}`xI5ccHcNc2N-$&&PB+O1OM6&080#)Pitnjoju$tz6olYdqr322=f zXnUZ9qYFynk+lo+gojBD3?Jj4T0Rrim+|jRu!`ahc0TZ{7QX;OY$n=O{KIi@no(nsIb+~1g*%5 zfHT$E3Ycdd3=Qd1lc|&-O5rQxxFmTGOR=nUgjtb{&>gy1$8*Ch`%OEk?3dW}+WIcb zko_8dIn4T078uwYKZee1S88K&5*1ABY1`g-Hb_@(LTfMO=Y#UG?s-LH8?P6eb}xz= zFsabFKi8o_LOGtNPlq?F&i#VC0jk}AS6@X6ky|oPDS%rsIatK8QH){XLM#(nhW#vD z?Skl;@8fz9*s?5IMR8I|5+_rzHL&+YS8PHo>>V?xnp?0l&7xZF*KFuqT+VBX_TNq?jKT~^WW@Y`Te~}( zX8yme?UxJt?>w%B{dZyiotgcYj#i{8qatoBWxLV=J-EOJXf2d)ONG~bn{R<^uW}hF z*b}E_~ZzBn$&*-%jv})ezlHi@G76ik=varOt*JltW5@cM$asc`7>5 zd9AIZpdVz;CpiX-I#<~1R7V{?xg6dUex*Gt#CZ|I<=GJzD(D=~ozF5_%MXWHe2dxj zgnFfa$)EB>bZL$aWS#&impfZ#?Q2LSP-U9*GXcR9>N@Wjoh92VJmhFjz~=dL?x5 z8uv@;LbO}TyE?d!qX1Kg-STh|eil;g>>GUN7v-Hxme@|hNaDN1e=w%}C`@r1eZwAV z-9CxvPkAz@6Xdk))@#r#9)=I+cuJ89>0BX&a8yCZe@f!v zfd7mi*&mVx(GR0Rc2|LNmH1H_X38CEhyD30NOJe_Fg1Vvh$#qd^vLHbCdGsa2aG;Z z(i@$h5 zTm#WxEE*P_%hKn_af(KK3zMC=SjStq?_eC(Z9t86519krv{?qfYfDoW47@?^_}sL^ zy0@%I;M}fcTbjyZ2}*+m$^!%{LJ*c!@z?=S6RJy|>uvIf;%AirE#7m9&^C68J5$n6 ztBY}Xkp z%+t3MXB4WF6lvL(@e*4~xn8C0809bOq4>tDg^^8% zT4>tIDd=@b z80diH74`h2*E#-#`P*?B(;;uIc^0Y3lXU=N?tVZj%Mk$+1A_8h2pGG*Rx;t~2;xy- zH0eR$%fW$Oe7C8}M9p8ci6Xp=?fbJl}>1hR>oImj_Pr$sVSxZWeH> zz}M^Xgy<=WGCasZ?Ipn~fhDdMVwE=BSu_6whCJhXf-M$g{zUHyg?ozDFwT$~QmBvP z#7TDAX_6zX$@W0yKOXM`+8>mvY5MR5P;C7sK#~liB&J}+Fv4C$5_PjXa$zj2vFizF zaid~rV?(ooMvHm%c<1#^U^70WKV7ys6JjuqUQ7+yZg_R@Ee76^PPdVdXBe%PAB71X zMd}1|+O)64F*SK}8V5D`3T%<}&$ zQJ@v^pPTC&*7^V4twsFjT&{)wztI1`PW^xK{QsXdoxfoaC^O8{JN51O^m?`Dpd>ec zp|o`Xa+Urn>dN%^Ii$awUq))cgPyNy?Kl3)@6%4`e0_L&bdf9VR$gaHw<&WwbKamQ zUE&F^lmwes@uf`eEI0$Hx@7tBGiQEi;3U`Au%Uwt{U~&7N(yHag)9{fE0@$tU6GHT zL<4Q_=lBsL5OJU2r2z;ye#sKjV_)&U4uW_7t{>k}#~-nd1DbWNEPq4mOvhG}amZio8gg7xFpqn^eQM8YAqy<-8p=u=8Tt1lCN{!>T}+{z_;2?T?oSwSjmlZXpNr5=bP-3%c- z>GeDWoVO>q5D(s*d`UU8pLvSx$&)^or^e>iDNX@nTc>s$)+y%}KaE_H&nbIk^>#b! zB#tFw*BHnygIWjgm4byp|K|`fqLCyFb2|n3f&mFLYm=Y#PO6h_@t*1u4Xr&@QsneY z@y?c;Zcf5Y_2l}~S}!hWUlxDDOJ)WeE0-$E`fPa(VV$)Xd;#B>X=1RcNI_HK1Y6J6 z*1Wi$-!(=1KPqj`I?q-0f7f?5bo>A2%bnfLh5dgX*TVk4u>XIZ_W$|i|5dVF%-d(c zqr>HIXEZuJDT-{Thegrttc`-ubb442=x#nMP7sVQl=&0rWaUU9X&alcrEI_4WOb%y z;|!p^u72$be0}XV%7K6azivBCQGJ|10CT+M*sh3iU9IU<%`0C&7Q& zT2M<}AA>lrCZ*$vvIjBnVcdRr-7w0P&9E%rrSnIrj*-i&gRA4t+q26z$A>4cPL7Yf z=DLA2ypDoff7s8k?9)&b{Gq>bqZ&q-gHl&;-yFjpboP_i+;Bj<661xB2SJ1~1_qkm zhCH5FmR7dDq|vo5TEgTLP4 z=eV6-Un`Do_Wc+lNNHEaB4W6hWjbSyy(yXf5ZWG>%(yrO=HXJztjyX0zTMf$@eUjMu#NtIrm7KRFw5 z1=nkA#2DYR2&m7Kx2txDF-Tg1nC8x2P>R4PKfvRiR4_I7@zUZ0x*BYkA)sbWVUMLH z;sGoK3r9jU-s`=+cuts`)!o;FBgkj38E((E*I)`uB9zNmS)8C~CV=f|^KE12si`SQ(^H-hA)HRmocw zojF2Elg7=q3HkV_gIv`ayY`mH>2V_GbjSPwEK4IA_F+2Uw)HU$($(C_nLEDBXbp=$ z#}hR6_6+uhS0@**5m8&SXb&ldxe=6jKK=;d-UOJVArSTI)C<ra0I|s}CbRSSCw;CJdgexP$TvsYs2@%Lzh_&XeKLXc~c!=W)UWGeQmaaVHiA+%IQlrd}CD+But^v;OicRnS^CbV+P!i zswaU4+)+2{Nq45=Ot{1;)ZW2zz6tcu2E0C7IE96bJ%`jby*P^kf$(|8Tr6xdU&}Sk z`VT_+8Lj^J*2d1R>Hk^Z-rQZ-f97#5>^}?p&%*vQ@%c}+R`n#HD866)o|G{D5M=<& zLjN4>S9&=`x>ZyTksj8pw@B}n)Lf+JC8ZAOd2#tg$7Ahes(fBphSB{-@$pvvPVouX zynw^3Dqo2D5OuX6J0lGp6mf)?nnyoRj?6|aNY#4YfppMHU)=^C~Z(NJij*~XAxv}#D{J+%*^4zS~h-tjal$PuZuIge#-TA65w0`$LpwH2us%W zHP1zs z1QRVi3^FAbn%K~5qdR<~bD0NO_cOfG{A$S7@xL3T?b73S$(yXg+L zUs9!@^bhK;xU z5D}#`?)7AKIHwE+w4rDJBUhB6~i3 z(LHGCF%WguREpJw2u8h91mh=>q;P|{3ZpO!{eJjQd@rTk>84kb{E!0gupqsD;G>;C z3Yg>}IwkXm7~K#DpxWNyFu{{eFsZ>OpVDmSl4x2CK(g45e|MJzchr;XYjGmxAplK) z3|@FPhMbpdAXI6LE=!>#0ztWjtT*$Eo7vv^a}JT;HDTaSv1w+_D}mgqmg!^<%RbCBz4U-e-N%o=MnssW^2Z} zUo$$a!?JW!yj=8EkwR9-dc8EVG}6ga$>KG&bh6YZwU|X|x@ox_@T!!h@N&yj^tt6D zT*;SC%>=QvTG&!sP#3ew_)Ax^!f&wVWissYAh8&w0drpf8W<+9J4q0NZQI(ud}ZDO z9bQGu#=+*t74i;p5CsXR6XbpW{r2}Sohx3*+tSYV#((O^J_~RY z9FlC(d=wT0Wmtv?#D-Nv4C3u{upL$O!As(#fcNNfoqU^97l-WDlL)77U1_{=bVT#& zAT(CtAg4Xko#3FC>Sb>!*?0-gvc9F?rylPwt7u==-w+CUb=O>6OQ2z@Op!WnSJGfD ztLB-#+*vWjl9QVIBTwVwI3-MhpSC_V*{NYi)P}nqGgq5KyV!GzZxbgXDwrJ6U00i0 z;yTee6Q8zTG8rnj9ep#KaHmn4*ruU@nYoo{)O<>cLI7Rv78IG5{PqMzXle*#W0-PO zf7BkJr<;1v^8&0}9_l(=DDzOHxv&7hM9N0iJ5*jUY;?eDBMh@eHj~u42We9q9AbC7$<=@XW&Y@?0i{b9>BeNdii}gh>-5Dw4~8 z>bZ&vlND|5tmn=8$wYaOj~ubBHbt?)2+-ZS&>Ro z6Xz?!>o)9XZgnBY(*x!j z_R|&+FN?|&fYYZa^FJ9hCroCwT3uxzSQ2#nUP<0GX}%>pebcnk(&RHX<>XCftj@Uk zn?_-Il9Hy7=^XF65;@5>h)~(t9kZ{TiK|-ZBCAtAJ&wdqVl$sXZYP(VFpKm~IqBQ6 zY-4Ws3ZPm$eu=5Zl_b%MRGVq;!-YuUK-EH|sGkC{j#2CDOM>VKdmVQx9g&^PbvIQi zE5hx&@FS67V(v(aZ3FW@OMCocqy2U^+AsSo+!W7$iD>DNqSCXcn)!b=UaoJxH1q## zZY=Wu&E;C0|5}{?TAcry|M{sOIkP~3$e(*mP;3FNqd;|bIuchtVTq0CJzoFngfj)|K-(0C_)#3-$a zhavuuQ&~8SORg-Z7;7a5WXu>n4>OW0RWQDA`cUUrsq;KkO!%O=984tw$jEDk^?vlj zK5=zAk|oHKZ90D55fLoL9G!-)iDy~bYMmL}*^~`~K>NvuAR9nOF^i2Ja;7{(;kmDs zgm{b}g6K<~80!32Ix!#71mSSQ3eg`m?yz*?2p^}4&(Vd@AowQt(Fhs;$u&|{s`OKB~@6E;e>vPg= zI-urU9-m!}SiBbG)*fZ7B$t?rGX|cp1_SOn zR%4&IWN2Hc@w)eU&b=T^Y&=PM&HBzIzZLZQ==iL#v~5YZdtr|VO9-|z?!20@uVVhS znz}`^q^9vJMvAPu%T|TON6Mq$`~4yX3G{edBCm0tMSRrh1<<2pycqLp_9*Wh<;_%{ zpi#Sos-YO4Ylc};f_&hvS=Ldm^u*1IRIHb=qs;EA5kK$XLU_425nd-iD_191e+Qa5 zJUzHLKtihKM|e%Zlkjr$CA=<=PhWLdzn}+~or6m^SEBA0FL7nJ!wty!IlXUBq#WWo zG=Fw})ls|jcj}Of-&Ax6Gas-7!K`QYQ6a*Mum%?NOC>UDuxbKThEjlDm7SE2Te1|q zT zE}Z8X`u}A|DJ-s8T~mzz=nm5iB$h-RvXyCoE9yUO!~dD_AM1WWIPneF0H8#8)83&j!PFS2c*tfI^ z8rh!3Xwb?BD!cqgh5Wy{y}fJ3f3I)uZZG8jd0Y$mee2j)z_OPfVhJ0$*)L@TX zdX71s@f;Wo#B5S1v3+g4JlkSZT>FjvF`vZSlOj}wQZKg)o!_ooT7W8dvi!Hcz%DdC zR%R-m5fclPRJATc9TGWI_O*k4zY3)e`Oj|hxu1)-FkKg$ZVLcO z>%m`513Xnv1+7Vyrv|j3B|VmvJLP~lS&!P@@h2Z-jlf*P4PNBr3|3ET5QEI!Ka6|9 z0g!Z?4Gw=cEYrYrD9Gi#GbqTw>a+0KsksIxrD+w)thdQg6AjLLle8t7F%zP2AT!z` z`{?-=yU)1$<3u@9MB`IWky4Z)WoKQsiShHM#kV3y%Eo%0Bt`p_5~k2&7M6dbWlF*O zb4-Bl%mk{6ceRPQ$qPt(xe!w(6}j5Mqn^v-AtMtg*E9)jv`qRsqMMR0Ej{A zu{m-Uc~1nw9BEIu@G*m|Cl0Y@cG<;PVF04r7d8XYy@eZ@=;h@2{=jCN@L<@Uz<58Jyh{t07$+W)uBL#80E`m0g!xXM7vB>(PGlh4OL zJkim9t{zP+aMB9r)fkI9q{~eFZC7u`@sFyFYhGU>N2>eL0T$+uscW|1Xqs1vY}4ma zm)bg@1{lj($l%XET%ct=N#ELB@I z47Y!b<31fADyyfOpL_{5waJi^Ws|sWkvH<{LxKf*k_T#^b$Kl>qmpdO+2eB>iD22H zo>&gWdPU%=) z)!Me&xn<-h_;P^z*a(%dMk>w33NC?Ckc1W)u^ABcUAf0ht;U3fbW};c)g7y8Uh-UD*fv=nrx@)xROriS|gk})1 z6M0Agr3(~@Zo^Oi^_>$M?C7zuCIUC$5`x!{(QI&oL0xhurBTxWUDii&u?5R5k100* z;PH_kKtlQ+>rk*izvF*?XBHL0D~Oyf1aWDKe;pKHi9JNZcSc>k3M>qf3r~QBlZ@%^ z_dZjUn7^VQM0c27AoT`1>HUaP?;de@>wKAsFDeS475Cv)xWh3XLE_>X2i zkOClTA2`-CvV2%=IiV@-^RH!G0U?Ub8OK*!&iY@%#xyo7>!f%f;r*on_9%Bp`@bc&VAYoh2Iuo|xN&C_ zDdMg^0UEXK74qA#C}@fYyH)LW#?iQjzPx9s3sZAM>tNL`=&J9Yz6Pguc3XpLyWX8@ z?4IXV_NI1}+YMejN^L5n)9sVvWOsR=zTL3sDaQZuyJ4CR11$)+D*yB5#)c99yRo&g zzKH*w$F+$6UBv%>o$U66J(EO{NelUt?z%>*xcFN-QM{AhxPAQ zkKexFIGSa0=e!UHZa(!LLG(V{2z#mzC=0W`voF{_%J%*6pSb4fHQoc(a&B@5g(Dd! zNryTe?Mn{D(G6UjsCmeS-2DKG_q)JZI-uKT6dN*)AOWqDC%lQHyaiYI0P6{3^VCTy z@lfz5vVeHQ^b72M)zTpFq7B$i-IG=hNMjw#3 zzvlSx4l#{m;{6=-2jXuQ5~CKi$Lp5&NX-st^o5+)_wl0{jDr@aFmt8s6!cItQzvVM zQ%HzLY5A@z)7|CqFUJ>{B&{;D9gF-}-Zdug zEMpK%`cTUYOPsy^>8ImM+=RX6R%y@3W|#jF|6KCj%@w8 zynvPz_Vyur*}CCKP$_4fBQ|f+<4qc_8TLV)@BpjxrXz#3IeY%j@43u%IP_+OWw2mc zRs^Xav2#A3AE>Zxc1TXF*p@~~>dKHmRPwF#pp{asGhn04VOGP@Dp0}PtlVIl`&4la zp!-zws-l3z&fz=3DLW^3j@nkqnTj3ixSV2#7e_qzs+>G00NnS?BMo?2?u=1v|9DOA z)DYv^(*<^klF|g6c^B*?oJt2a?I$c5r@O@x&xpYe_Pi0;*7P!o7UU(6;~Jq;F82&) zYQ@##s@T-5eKU2tF-zMz=^|4)ww12|L4#vtTUCtZL<9nq+K^K@vFF*PU`!S{>&k*^ zH=_A2NSzoT!8;l-Q}q}h?yf8P++|J}^N5QEYMKXK*n1-Q8uq2{qcksoc@;b*~^xZ>ZMy)=> zEUATpqE3aJ=D4z&h?5~Sc^J;4eR@B9@S{~!npnLLb`X<)%S33=JcG`x5N34d^^b>d zR<~c~LTMJqeNe!H?3P4Q)VkJgx&v04tp!uj#V{fRg+a861xZkmzP?VA)l)xGG0N1@>A6-wQg$su4LFv+yD4{FBmNRiW_uVHSK@hI^h8{3=PcKpZYBK~6@*CPI75&!XZ#(zwZ|E;EcBp@4! z?O$z&OYS1*@Y-Yr z(DPEA&nV6Ilq#g-4qiWq=0?G(Vt^Bwvh`%u7UA(j35?|52X36_9lG@9zI@rQqfk;)r=EiVzZdZDCzi(M zR2*?4?zO zGeRaqy#`1{{lCqfUF-bc#`>cE$6T(3{dZyi{d(-bb3f4s_`Se2Qg9AWJhsp4h@f=F zG(E;O+3sx~%{e$cgw3#Xaq`p8SLH`@j)Gf%*v~|;87amx_+}XCVKtXm2WLkI7f1H- z98f``o}cuz&MCnz2S=|@&g_FY2fYVegzj(N9ACUTzj%Fcc6i*mIDT_}aRm~lePre> z4}zn$9&#`&nGpwU#BTvPe>mmH0sIaj786jvmPUPjP`3oGRCi zOIY=|iOT@P%z?$gjnfsE7pVZ};u@>=F_8o?p5{#)_sg7ozupJLRS-#{1K17+V4R8$ zjA->ya!S11efh)I>^w0O9k;2Ie2imc&qI`!xANop`Dtz^fo&Z7R0 zB#QA0emN6IdxmS-DbS3wm~}w2N9Ztmb}0R_%@~Vo%xn7jA7$YkX$GpW|7^V6 z-Zkt$o9i1J3;WMJu7&+)VgLDh>_49+qvOFHkiZ=csw5qw@>ZdQB9k#HFM}{L@Spmz zugcWZ+pVX_{|h4A22WM~|K0U1ga2=B?Yvy@|9M;s{=eY=3;sVI|98jky7mC~o5fK9 zMW-nWA_U(2e13M^!Ay~_P7V){B085>2Uo{aj20+tg55fHgc0NeLBKSYS`go!Pc~e=TeX$A9&>L_|QH{$jkqm!(QiasL-Z9a34%jw^tr`#)^_o7Va7&CQLS z#r{8!Yq9??_W!SE|9{T;|IK2bs%xGfol$Qc0aYO3tM`5din@=7sr%;PFpF<*ufhlI zF+bL&fe!j1Ozo5TsvCfa@;~yQ4yh`uv+*DO6muuK0bhXVLIq9Ln^!oo+Kt4I(lE2` zzYZfzcz2!vnUUmUz43G4!!vD+r@R8!Ne}R?^(B5(e-c0q34W4 z5n^!y)Spzms0oJVtA(Zk%KRsi&?_}$#imOy@|}0IW0||_yFYAxzdg(945E{wgChi0 zq&k9>*a~51o;b@DUwmeQEB%ZtFH4_eo)@6g12nXn^LRaq^)Y!jNHgdeFCp_ptec2~?l7U;t7ZqRZxO?QMi>OoZOO1_^luAh3FN}t zCnT0fAWWFqO3+HO3Tc!Ir+CDCbU33oJ8{>EEBv`OS9prRLf-&tcoWVn4&azbaF z-?E;jZHk`fbZ&i`uq1LE53Acb@-TD+J2AVEE5TSCDer{jGhwznM@WVtRI#4qe9_UD zT)djFH;zJ)mh8s*gLt1pMoTG9upt*p5tljru(R9GCu)=Ts8bzS@d^~KRjRSA$ryY@ zFs-Sc#St^8Mj=cxkv!&=(Dw4NqA1ngs@tXC#j+R9XiBw?Ek4FX8=#`asVD-@zSRW^ z(3OU%LyS^qZ?vAXR@6TCxYXVubb#>dkX2wlOtC|cbfGdAu$h4Z90LbqwbAVm*1QSa zQ%EvVCeN;G!M3#SQ(+2a*|yT6{7P-aNPKLzNMs{ZKKrsv$RI(+rAsi8hv`bZJJe{# zP3fWx%Q+Xc1&kUgsOn$EvxSgB+mFb?B8sy3sQ+gym#g++oRD@O^THmifgC%aEO*CS zLfTMO93XN#47n2v%~JC$7Mdkb%qNu%}%OC zTv!B+M%s%yvgU2yzX|#vWa}xQ8J#`=S4h1Ei2)fEfrnRv23up4)ZCES%Nk&5%+bDv zmYlvnP|DN6yI6ss!wOW7r!loJIg~57YpzR#3o|Y%Ve{<%V%cH)DWffYaly7V7C%Za@5Ph?KXle#0( z;9~4yDFE0LQeGj?f1tg|JLv1uBjZP6C-d_%1US_U;5{!wE|?6;-Dq|*H$~_zw0_6J z`bipeAge>mZ>%|SK&zM;*4W78=r$0U1WBNwivyIA@g#-lfjY0Lw1*DD?uVf+@ZS#m zw=i!=XJkSYh;<@U`_eJiX`z(iOhqgW4od>vhIivHZ3M#XeO8)oVPv3&QZ(czVkbx` zqc&&lhAM_z3pW>FB5vfWFoLirQBGO+c>xhKYKz;@Ll3R zOwF9sK4pO4Fu2A04}Z^-9U$?8@fMddELMD&GAlf7JkDZ~3U@9p7*KSl&eh-FR5+aFWQig4VDhOR0{I@E%vn~yJ32l+`Q`ZH??uHV3-%UD)ESBF zYu0z&`#1&F{^p5`jf_3(EuWqr9-Maa_TBX-r`kT-?TIT1Dkw5*_>) zoad*f$A{#wesg|uc2!iU^79QrsrfUA!@^pag_Nci#FP`I7Q{5>P_2wqlJFZ zG(b9Y5TbYo=a6}Ni2+NG3$I+m=EJt9^7$FNu&0eOv$ChyzIrvabG%%R0mdg79JQj6 zL1}hnNf2*IsiDdl5o#X&KI^yCG(Zf>lA*!4yW~`yqBzoKZc3+Yf){&`s;QcdRRq#D z$$8eNq~iMHPop+gYX1@oQcYOb(DWVb7t)Xk=JJ4e^WmUm}9l zN0E*N6-O$oS6HvI;@v_FUdVuJFMfNm>l&!)X)RhE+7~Xd2(Qbl^NZuoNfCYgMUK`17Uws#R=02%yg zOZ|AU-Z5vTpE6gXOm@#Y!hOtK=;)KL!yX4-uQ`c$l0;bluCJY_m;kj!SaV@GigPnH zCeG&FaQb)TNJM}Q#azULY&9M-(d(YY97O-Vf%IXb9(c05S~ei|i5r$J<=kVk#*l|} zL^y%17^lVbr42>d)t!!YReBJE;em2 zgzIaRA%SB9=?(jtOau=@>JAx0GyCZTNY;E-f(>82zCJsb3Lt2Dmsg#`w^!${UQwOO zNLo$Zn}k4=It;bTw|+mh`|Msdj&aZuV)+v=v>lm;E~~kORlG{Y5^>dA76qhkt_rI} zJ1>2x^Ul&eie?8x+9u$npKFW4t8AOX3%N-d3&!hbe8(6zH@65?YS8z)wsfjqKzcA} zmK9ML{fjpqyy}qx4#33?@p=fOVdgBUtX{9#TXhCl2;=5yW&>n{a1GHSZ@ds6rKM5T zOO{F9-EKKwuoIc6S3&N5ajjT)*jT3Cz0EPZr`@u)?mZdmTw4q)%oC%J$O^?V#^XSD z#aPTZqWV47Vd+y=Bz@GHz|zSpp16{M>YXdt1Ija5>7COvS{Z%Y8nJKkr)?iApd`~| zP)a?nq8>_b4U#G8DHZsr*Pr~u6=QUysoGI#XxpobM#~3d28t=e*>p9nS*&WT&Kmf1 zu0%Hhl%TZs>T_dMvoh@|rzs}u|Muwpcbwx`QT+?Lo3PZyaLwP9H@VAjw0QrG%^x;5 zx3~2=OaoEZ9?v*Qo6d9fFz|7+Ko?h37+ykvW~NQe$Lg^U(Ps~mIy!0`_6Ge6ai|eL z5E`C$2)eQ9E|g8D!<$uK41mQ5rQ#GF2sRJ?pkB-Ht~62s)q?~zw((WNn<@Snj&Rto zQCOReH{AGng-w-vFiuUZgrcaPL!q=?*y4#M-?%h-}|Yz!A3QS zf}Uf&QYX(}EsZT#dRrhm;5C*2t;lW~)2ZxFr5ICBD$7LyCtE8%h){!3Ri6&X2T~?X zY*t7-HF{#n6lz@h#D_Nu@XHGtQXKi%Np9;T(zOHA#}kiB$GWAqsKsSZd@iHj;J99_ zot>R^2|w2nVAd@q_}Z~Z@`Jn+o{-sf^vOIW%+C&~k-d9bP}>;A8edkTh;%u%6}2;t z_{%*{2^=18-oCFrZ%R`Y-C|*(dxfW`$Lr}2^(n0M)Ha`5B_wlC4YV3FHSl`v-YIRV z9WrAIPYpi%-D_(sVh1u9qJMFjdwOQ*30iutPNzL93rcl5PAZ)vPYI*S75LK~K@404`Dy1SH?S+Ry-E!zCWF;uC=4h-DNFX&w;tIBT zdv;P$8B5}O81Y0WhUek+$!SsO41EWx1a(Y%`nQwQ^Vi2$#}@?=E8@$1Aetgt*nKs4 zgmp}f8Bto5p(1=MDzPCuZO0?Xdq@|1Y(%4PyVd2XY1>8UCd-rOW=o2Zs0TCT3Evh! zQpH1qkf30p_WD#?927Y`r^v|sEcgU$4iDnKd`5h3^bF&2==?O}jqZWg55Z1y`qe!3 zDo>vAAn}peBu`RPI8u2=Pc&eSc-%u{YPYqzC=)~)IWqE;&LKtvV8BGkrV@iH$Sv;c z@gOXko+t9aYIp+-B0##n3GQGuUlL7yH%XSjCE0? z;<3e?I%XLMiR`&@pv~MuQf0am z>Yo^6sOAV8Z(}in#EJvMay0Rv2=RS56TVX4Eu9|T#h$JpxECB3oA1h|2p z$V@T(8!fcjEbO$gvGM3_Z2%W$V60H~x*_apFEzC#%$~}X#>0@#@Wqd~vM|B!!!V+J zd{4HMRhVRY0cNN`?V5~)VTK8O@I=+{CcmM5*;J4K`#^Yie-kJ7aoiK%4U?O6WjuWW z2B4)}!m{I-Lf1!!R0oL4uTY!g0iQnoQ=Q2UZ+hX!P_3uO4OvF)yw5VTYajQ+4*@2- z3qkvcLg-H8@Sw3m*@9W54JI_Em;PfI+yr`p#Af3^4jbd4#(@eIQ*3)JOr?}#=uN&4 zW2gW3$s27#wXYgKY_D%`joD$PM_L9T5IEwfMn|uC>L;2Q?H&5|PfEh)VHA>Fff=8Z z02*HF_It@%=HI1jOfp)-#Slkp4}KT{V`+bS=xZ@jG&w3=H{M>3Ic{Zu*0!K8?%Ap$ zxRz#H4AnuB<2P8YQLqLTlA5gpSDC}{8!A@_6vvO^uPqkxD>Hi)X7eH#dPc8jvnK-q zbuyM4y3iOTQZ(gepc~EhK#C3qqvH`k#!uUTl6To}>IJlKaRr6J#DiTN9-ninIH11yZ9MiX3lr(TQ#DW&9l2c3HOX zFmW#BpeKF7gZ%-vFFKj!8tOP0vnFmjrs6^iv2Hq3Ri!*PozsA(9tbp)EUu_)UvYC9 zQ>eZ_cWGsN9TFn7?26=1x~ZG;O7oKdGD$d30n}wxUfSNTn9Pb8N)$U1 z>}Dzp6$w@Nq($C4XR;)G_x(Ey#V~0Zrq#F^QV>epDE*=(Z+>rVwqnnMjvCeilf%x| zplmSinVFV}5Hz>sJiU42%nO#>Fm`KIHU|8!y&3Kq1)0Xf`fh!!JIX&9 z&fnSkW~)QPYxrhWT+X(;^@GMMx?8?=l$FV_Yko}_5dDLr^OY6GawAy{KX^U0`q`Mi zo~h^gYj+q=!OM#mF;j9Ompd`8xTjg~k}Ry2AMfs=*D4-hK(ung+wVQXkkd7P5UwF1 z!XN0a3qP$Vf$6_~?uSaV7n(*^i&!UN9KjW5alLaY7Jw#)fctaP{_rVC;?$<1L$$mt#Rt z&uqAeMLV{^W?wzGA*NH!KAz7HrX9BszVB_zn;e7t-j2K_QL^vt<~QH+mR~Y**H*VJ z&WXiYPjYjf?ogOA9pm623*!|nNv@Ek)wdxO+6@R+4ckGfy?`;9Vw*v^oq)c+zBURT znQHy>kvjQ6E8>XQOD!)QqS%$f02^=LTsFvE@`{a9N!jo3!;{udUNHTBRMBG>3c~^m>;p15ePq6y<3#C-EdW5Ce9a`^vE( zR~!w5=hWb2N2SiR@7_tM@86lmsl0At8$rDvXFL*yB@*(H&N$XZN9SzAUgTJ3FCfZe z^VI>EwJV(IRn52+W`xRSYBe)9)g=|p>Q*r$K(dnA^I@08ogcA|VqT>|FY7HX4s^8Y z-dmg7JL}t)zQ^XDSDqY*DkWOIM3r24nM7G>NL%@|=6hlKk6}bbT=v)ra~?a*=!$yI zb#j~ah%@L)i&%9A8hv7+sRU5S{`rx0-zfE|d{4QVto%=Sd;#XEpblJxW=F8WKfM!2FisjjmW3~RAx(D2}$6Sj*g3DxLws5 zqYy%qT>N*`us5 zE6VDdv_m_N4yoYPZcTQYw%mJ|i@=1AlKc>3Zb4G$w6~sTBz_k0F_n9LMXTBh&#y7?7L!L7>BD4dO5`=$4iBy^i?xN zQ1IK7M^Vss))uO0oc{M<-?l^}Dn5%uEI*|UNlM`|PH#Lrgf?DdGN(|YJAN!LEiWVj zYK;j3ptWXUhOR+{x-pbg1EZHi?g!Cb#%(~3nVn+-0Ht-;3^%-+mQ88zZ*-7&QEc|jcQ2(hySMv0$w z?Jml3DwYFfYFxj zLMMd!1UF=RPi3bDZjCV(tQ+SNm1a{72DM0Lo`+#S3(4R2vPu!RCYsYreky z<-5Kd0D;RMV};YS7(nDi-5BUJ9mG*jUz%u&D;rWv;bAaC)TMNVJ~Oc59Jc8U&=@hB zn$ofeb!MkxMwTkN*cxRvBrq{6BhQ2)YRVZIa~5(o!9FjT0r^@{ws;0^mdj85Ny@&f zAb=tnY93e2&+av0t6YUmaYguC)vF-3#8D8y>_=rafQqh|P3zm#Gpq_w=fJJF#L>OX z#(_O@7Xa%3S@9`Q=l4@7ephxNR$`^b!B~lvdZ*e-52lVdf|3KOcv&?9MmjhkE@#}F zxW+6LP=@2Fb!ybASn?<1doJ7F2%KzM6$1>^Iz#6x`;x=p!z|cQW^G1x>_jtYa^5vpPT&>12;;a@Zy8#niIIAa z-WVk+UIw+v7io*x*t)`Vhk@Nbu>Q!XdFywRIHiaU5yb{-+X4IDkf)1vP zR*c0Zb_23V2`i?aY^cmK%-C6_L}0GKIvYDB9wdJ&TaeV2HyohQbA!>lscmN^#!oLU zr@F~Ej40NT@_>p8?)0L*i9Vpb0;(YLaiE;l4K353X~X=jp?%QU^ETGm)$$rz9VvL! zczb!&_`T)XAMLD<^VRA`;p^{>n5QH_-*tfX36Yrz;%fY99|O_Q>WY6sHyX@<)c7;| zrE}L3VWL`q5SP%3P`O zrEkWeQ`TA?LS=7$eoDo%9!NVM?#k)2#;Zh>>PsV#;>J3Bz-V!Y{mE&Oe%Z7rrnL?+ zVwW7=;jsvj6Q4dEwFr@IDxLV2G3K#dG&#xTE=LAYqdE;vp(jkx8+mI=NT|U$#SZ;f zegyMdKBpQO>ZF`w`BTm_zteWG2@Q@TjVsFSGK{*0c(TQS%o=ZsRgjj)fQ`2!D;H^Y(Y6e z&RmN+!?(xDdb3&78wOpAA=EkNtZRVI&m6j~HY>^AVQbb1c^2WDdIP3PqdhHAY$}&g z!O~%xUL96msEmjvJ7I5hhHfilQXA5~IXOzl&&6;T#F?Mm1t`<%(y4Z5NXK}jDe#*k_AKZ__syAsu7yeggl=oMtaxQHAE1$whVMgYv&p}eU>p|4Cs zEe^uLM`}8wM&3t^;Cw*}#olvKl7@v`=Le{K?F1Jyzd0W+$+2UQEDTq(kTB~=6w8wl z%qoIMuqZ%Yv5Mf{*MU{s1rZkd$6i!}>CY&Dxuu-G;xWy%TnWtcJHf3C-D_fnZnIP> zhI$QyRvtCXj{u^?y3C9}W!YNsV-_|~@r2z;X2QB53A82-gHc*kvEgz@r_rb2OI#M93if)eZ-^9m^x3uOR!*C^Ts>B%Ex2J@8`^6 z&qLl<9?JgX`T6NsQT%e*PN4#P{V4tdmCal(v#qhAQsZokY=~K&eT5C>1X~Rir|#)g z`$Q@iJj_$6&q#KttUIipEK?CtT6TCKSSvq7JI=OmoFyA2PmMDZ%-58!X3806Se~R# z?UGTKMuH{gJP%WW2JJHU_5y?+2HQm9ku5%1S5m>ZK!p-DZ}GNnAk zJ(hq`5ur3Vxi}?7D7L+#sUx@}n3`QZ7pV+5U0BpK0Buv}C`e zf!X@E@kA{b+AO(R#psCAwG#Q!>xCtVwvng7DRxl&=Gi_j%R}mM7peC!%uX_}T>Fjx_4}FtlZw91U?Jz2K8au{ zO%d5ncy;hS06oyXG3yxTctS%H9+pDpD9lt?T0{Gif+w&)__08`jq+S^7CBSI432t? z-^61%?F5hB#~@LwiE^l>8<0>lg-LgfanD;edp-H7b7=#%K3|N>=|EfA5H{~- zN*NNHoes5fGra9|+7Esd-U6YmtStRuan0=#RK6;xe3el-D4T0+MXZSxu~xJq)@Vhb zrh1q74{3Ywq_=_bL%ZACf8e1+#=jdcw{~{^u(ADeeRp#gu8lveZ>?`{@BYDCp9cb9 zJMVG9h;K5VqQJV)XTf0kd!C-!Y6>)#~-v-Us_9+MDxAE@u~ zZH75O0ZI?6-_jPSB1`lR#;m@8iKip4ad7FKTsFKP4=ztGTL9zNldGT4-(GpY9$Z`; zoL!w9UwY>k-r@P#(aF`x`5F9r;-TT|g*-?vEwi8*4u#+L85uG_NyvrcaIw1CQ ztP%@KSQo|>-3@W4zr$RclrRaT)rT;pL&|921t|USA??Y)|{Y$(?Wc4P$u9iMnMFK>1xRH>nR#VWRodwDK{Y`cBo; zddtTVqM{i5QJ5CK@Ox`17XlJ%!dfOF>FP=_^=_ zLP(^K(O^p%z3XL7&0>JR_QU4(`sVJ&Uy|UqLwELHZtlGNVQ0Gq|NgMOzSH`D(tm`# z{g*%N?rwj-`~AlE8(W*Z@XhAx@mrZ{m19X9ISL|{vQZ{mCGz*>SeH|N4u<6s1j2lb z`1t8y5of@Nwp$qG82ZeKEGfdIQs55p5cE(@wc)*%LbPEBacD7O-(UNU|Mk0K-s;8O zA*!1!24$FpPJ7%i8w@k@8?m0fy*OoFtJfSk-XS_Ob?e)G&>sMe-UU2w|BaH)mWGfE z`TO?ASWQKb^|itpWEj=H6Dmy@xqIq&sZ6?3TfAO4lhq#vA*D@;XY|b# zDl{%pLw((Vs0;#GvffAUfIg9s(U~XQq`r|bpsCm3UEZUSI950;aV<^ADj#?-Eu89@(Ek1q1X-|hF3_AmW zl%Va49B2)aQaT{&F*vCklh2`8_Y`Da3dEGs-awz=RLPkyB0jd;SPMk2_Cm|DxYo-X z;F%%HX#&5F6`CKD*7q&EToqz2uMVz`tLwuYv6|ZA;3^Rpi((2*H zp8Rz30>R~D3tYKRoU8_~yir$)8KcqS1}#FM`E)jTb^y&C zxvSA!DXRh7qYblX&yjdvt;b?djarRGL$F$tMY)+5Wf7gkk}L|rDQl(lz_Spae09Yr zG7^r*MeM5Wg<($KDLRLng_%3{121g>Yq^Z`Zt1gAYqPdMYa6!Ql&x=!O}elXj5`Fq z(KkV7&%|~mxes&MV5FdE2^Bk(A}wI*{ITLw*n4|3!mI9vgx3@{CA_AvF{xn2+nls> z%tVi+)=Rv`JE&|C=j82dy4rEl-waP>Z>gP_rrm#Zq}9))Lfhva+k?xYIV(mfW2TBx z1V@GMkb`G^0K=BD>=spVY3ipi6yOdgnXcB4?5@cn%)%cg*o5i^n}Py4D^Hli5Hm7D zRT$HAd8tShq8GNvb+{b8R`jj3zL&Zj70nzs=}sE{(^-Nw580sX82%^9j**`@6|ITt zK;nY#4HIrF;=%n1H)T=o!(o)mK}{o^X&u8yaoZ%}nR4yR zum4dbLGo{6z!X71har`Ti_!D0SAPYx;yY~}HCg-tHo?;9p#wZ40*cI#AJ4%rS}@>l z0L-f=3_OD*_!!2+)K~~A0a1QlJjC#Z8_LM2rA~K7Uc^uO?v4GNr2|ot$fU(o6>x;4 ziGw+c)-oftlEutkm~=IZH>aeAn}V#O2&G0E8cPX6qUe+p>;a=pEld>;2eA0U{9B+x zgXDC11=BDR$+0Y^YOGTH5N5Cis(DhQ7^8Pn0dEnI?!t^sw&szgzYehEaFQ`$8JK{V z_>VNMW*YQwRTYb|7`!Wv&N56n4m=49{S1yg>BfJ4QdOUeDacxa%3Zeqk+&=j$SlPG zZO3A2yg>k}_Uk6_XDmKA9W5izh7M(J)6rwiejW3%2rQZOno9h~oj(Y>9UkChg@07U zf2?n8Zfu+JADg>di};UuT#NXRMf}Gs;y*fq9T0bJtheF+8W^zg+o#nez(k(G>VW;j zU;KT+o6>- zBpZJ42PqG<;%6|@wTm~0sW>N-7pFiT(GPDDA5%vGqd|F)$+Kw#g|&v@DcArz#mMio zkKVALEPPs5fo9)R?`nK)26eHoQ`i9>eEe<$m=n9j2MRY?pjYF7eR-0m!+_Uxmk$wh zY`DrTxOtZhy4sz5sE71Ew&?)OAF6JG27pQpSRU@AX{G|OUxAmz6zqBLj7QX;R3fz# zG8o2NdO@Y%mt24U-qMG?>Zec9Sc5;n55I5>zU&9(_Gt%lU$tWVMXFQYMpFs$>;MyO+b8$(l}wH)A%ht59F3K5RbQ{lx z+2w%8n??A3!Wl#elg!>YJ+Nl3x)U>DY&rHPU}}pg5HLq$Vhhrr2=7jYb^PFm{Wp{h z9FHPQS0ya~KGN)&Fvgm}0D*J{3Y0NsapIovnH;q<(_~}?Gcr0eTTIJznA>8BXb-14 z7fy!vbNmqC(Wj|0Is@nk2J*fiK8UYJH;UueoqO^5ND~HhGj_X3FXOfPHtJ3^;$bw& zm>H3d-#8=Anr%;$Z5#A8s-ts3WZx{2)!Kv>?5k$0-#leGx772f530!pop*i{_rvaV z?YxEHM-q~3C}Yu0Okg_faCc|G0F5+@=oz&-6OJ1o?dVT9SB;`@c1G7J7E_e>XgZ92 zv2^A$FHW{7@^nm<85%(A&!c{fe`JjDcNI)rib{L0sP+an;&@7VK(4QKH=uwoaC$bhWt6c_~M45h;+*&UggKbLWnuO^-QLu1nV%?KHP(oruRe z@UWod>P8oo>}+>BGQolo*K2n{zBQVioP3=Eh*>0Xs**?n@R4jXCXBIY#4Nlx;>5WN zb&lKz)pNC3VL^Z0kcEZ1V$r(3!bI;Rh%5KoP3y!ZmOLYiI6+DankYg zMkXD}G#PA-Ss$I*E~fsoO?@pUzF6vC_I%gaC}y}dj7%X1T};QS0~r~^J^``tIkM(9 zVK-dVIUY5hV*R*DyCdnYPtZo~+U$0c@%D}drKk|TC`uV)<5@70ube!b`_x;2IMv-r z0XVA75O(4{<8btCOy*0E`Vsm3!DTnmwNG&oOOo9{jJr1*xcIP-1vjHGuxrF>l?5CFxmWfI$;!MosM1eNxjPJe{8SsY?$-E z^Kxr*QU7Be*P{N@qW;q?>OWEK+sa}t*s(atJgtBnmL(mqnl9qjl2K2}c-&T=E-lq; zTU27@7Lrudh+#D`gyE#k3>%`Og|$1T+bHRxoyw*a4Rpfx)AI4A(;RDBXPAyqkx5aU z`Jc*1X;vSYW`iX|br!i8yKOV+V9}7vQZ`P%ap&+W(|C^C4=WK_0TN2nxJ|!t7ZR#d z`%T`D=r*oGfSCenx{a0&+?o1o-1e;mCj|p9O%F5u#$5=gP8l?AKg3D&g0VZZ5=^Zv z*HDYoY>eBi>&$Dxa4XL0&ZGw}B-A<3J#J^jNudH1I8TdBtu5DJi;q2y+bj=(E*POJ z_I+9{xyDy`US!-xtq{b5ftChvPQP*2*sFtj$L&W|v`qm{YR5y(yk9PKjTWLewJz2{ z)ohSc9~sjdKANfvhHN=OrqYIMaBkn=sQPI3G+;Ue2uIBRlB)}F>jH0$3sR^hwgxgS zh*~wai{SqbgLG=W)yu8T7&sQTO@nDcH;c7Rq4Q)ha2W@t2GpuGI_+LN8kijIsezNJ zz$z@bGX<2$Mzjh#(*&F^%4tGXOW@27?i2~asGT$IK5L+-*lmq>Orz6$Lo?RN!5xSu zcVyEY4>~vJ2pO`-%rjNsj=~`mVW^-PcVUo8S`vm5VI(TD2Tc{Yqw2sc#^A0hFqM{~ z+t_75ni^0et@*V3Y^N=sq=oJ<&0=_mFKD?}@!MP!9Sby>vJ^{Jk<{qQt!>b zy$K|ivIcEbj@88AK8}KqL4q!7=66Q>i8MFj(_fUQWL+7rA#S;pLb;YOYm#X(A#3Td zrU^LDb~R0?YCfyk!JU8#O~4%JSg^PaSXcj;(RY%u8(`H8C{qM06P!#Drjo*BR!}FH zdIKy2ISoi^4wXs9EiCMoa@6Z#jLuYH3i0yDe`3~(sX{;WlOzn1i*fmDAzW0hZm+_J z>4JqN7Q(jiG=0E8x)_)?RiKXS8nd9fp98-KYQt1vx-)XjqW7mU+v87A5uYmL*I^Vs z3?I%Dz|Jpze;8ch4n5T-aNYcr#KXaKp~jC>g*S=nSP0V~ji~~k{zP3Rew2pU^Z^rL zO%>v=eiGcr!!h^HN~k~jY0#S)AC=8axB+0WT{7$kIYoTB7>+r0-B2Sjt5lz<%O2CNmR$2za5qxF5VFtAqK6Zg93lgt*$pNl3 z+`8hWGH_<_a>)x0Fr}fu6)!o!IiqU}9y&g+h*qt9%>mLG{aNtP@wqFs(*4ZwacQ_> z#Y+xwwIlsT_@J_x8i0#ISX2kylyV!iAIEAF^rt;92DtW?oM##?32+_6e7=H&pW zMGBQX*W2U|#m}m68}XhiV#dZ!ac4^UX?4*ZJyQ6z1gCCjIs7zYD>xuQL(n zBh!N(&(MiLNGD&2+R)$$%xRu1r zEXLwzsj*k0LbcP1n{E@UM3JzL${X>cloIqcZ#FJBW)+@l#1r?ZRq;bwpR5~})ysOr z#x=J&shfC#!AQY;>GK+<8n;BE_aW#NHt1C8^X8e+!R*e+HiA0xnEM^n#q~w3C~x`_ zc0AA(Ty>GEdaC2TYx{OU!dvk7$`_m6Mku=D<^LEwkwV-nZ=*c_$NKul)~=cVV{3DL zk^f^J*9-5ppL_@smU#n{LA*JBjl2GaHFfc?W?Tx1CR99J3tZ{PO)55e~nw^7CacXnRt{C{J2bA7@8=W-SD ze{%;||7v!Cbg>1@VGDpaehQ)>@iT_D^eM{jvpDXzy`yvQ?EK0*hMxb+(mTdv-Yh@7OOAQspmk`cd8>RfYfR3~n|-j9sE8E;AUYpY&j)5l$&!Gk6%#fO$LZDE`F0 z>~scCT_mSY2Q35byD-ClzXM=h{G%I3w+Q%iFL&!IjnU`-<<`sX#r)6Xsy+YguxY!SrX#meW&c~>G4=nA?TwcU`EMRq zuiw56gMM!n)69E+_Ier575@-MtB+wXyWjIR*4GE078%^X%BynybIE0rHpsBUK4QzSun^2m*E`$piic zO{|N5H&=Q&VRVN{g4x)5Fj?I!PC(}jGMbny1pojSsRYLZZ%`k-vp7R+_!&{5-|u^a z7{-ayt9Rog1`WXAK|w{NQqs4GNEV=A)|gxm#eOm92LR6r=HCAZbm{eiTYuQk{wQu! zN3aPXd&COT!w{&~L!C9ikpLt;7lQ;{mJxE(TB(2e%M2QctS(8hMD zw{k{8TuyyJ1{)7N#1*1Z0W#VaafFz`YWp`S!GsSU{14D8z|u_`_hH4ffD+*j;w55j zE{QI*S#j^?ddmdVY_!{rl@&9od}F=6(Oz#LzE)Sc@xq+I)e$d_eBgD7G0X_l3;_{5 zU_cDCb2+#VqfZ|15O5H75+dWHqSreqdkOlw-G<&$Uk_j|{OCylkn_x^*o*uJBsqZ6 z!p!=}Yofcfjn3UCuM6Df2IoK_51>9=Bt#7yXcK|-yk*vY8(waIx4eR!g+|771Ar1o z==D`#?ep?N4dqKtVZ0WV`6L}aJow3z<7o&hB4NKBPrJyifNeP*MgAb}2XW+hggtTG z{ul<2XitJi@0a)rhc2%v9rSMd{$09+ce;H)O*_b6a23Ji+`y7)Eb)&ze64oq1H?$< zA$YjKdQR_`6o4JULg1CFWEd=|lZ#}_83gBJUKRjT$FLwixB9xGeTA>O_L6+JLkkJ} z(2@5VG(=!lz+0drA9}c!!iel^z%0_(;|`m&{m>(d;SasTpAXJ{Iz2xB2_CEf3}t_1 z$Xtc-(;gc{YY%=3^S35iXy0cK{iPJhryD@8Fo_W&=eGvH!rEofci@6?gzvZ6^Y$U# z!GMJ~bffY65|2_yhqt%kr)H3@;P%g;5+^3=7qSBOo$Yf^-UCcYIOvN{acTG-DM1K; z7RjFI9)AVV)=tu_(ekL5??vlD!~`g#ZEBZ;kgx1}%Oqv3rs3VP0DwFX=B=B7EFt+s bdkJrM;3v{l2)pd3Ms8N^dze@%d0^bci|{u5 literal 0 HcmV?d00001 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..91ea23ca0671 --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..62d7440027f7 --- /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,2424 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + 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 + 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 + 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..4b63cb73aaae --- /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,3791 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc"), + (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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..c7f575e3064c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py @@ -0,0 +1,5618 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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..0b2b65162f0c --- /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,2887 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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..fd5f7208330c --- /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,2873 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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..8caa1fea3b3f --- /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,2891 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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..8855b0d1ad64 --- /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,2875 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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..cb355d0eaf36 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py @@ -0,0 +1,3946 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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..ac7ceb319b95 --- /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,3115 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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..b88075f1c618 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py @@ -0,0 +1,4414 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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..9a0f4979db05 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py @@ -0,0 +1,5190 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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 + 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 + 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 + 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..d3c971085582 --- /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,2731 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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..364169d96d19 --- /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,2851 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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..8c4f6c788231 --- /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,3324 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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..dcdec3d7043f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py @@ -0,0 +1,5200 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), + (UserServiceClient, transports.UserServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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..e3cac5caebac --- /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,894 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..c83087341250 --- /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,1246 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ConversionSourcesServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ConversionSourcesServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..586714c04254 --- /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,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..1a70db2a347d --- /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,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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..657b13c2b0b0 --- /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,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 inspect +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..ba02c61eedbc --- /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,803 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[conversionsources.CreateConversionSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[conversionsources.DeleteConversionSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[conversionsources.GetConversionSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[conversionsources.ListConversionSourcesRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[conversionsources.UndeleteConversionSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[conversionsources.UpdateConversionSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..03a202362a18 --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..2ffccf9a5fc6 --- /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,5696 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc"), + (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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..99c6fb1959b1 --- /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,879 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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..b37d1dd8e063 --- /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,1231 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = DataSourcesServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + DataSourcesServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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..38b65bd1a3ed --- /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,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..13a4d717e4e3 --- /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,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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..b5265cde6875 --- /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,462 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..578acbd1ce7d --- /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,772 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[datasources.CreateDataSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[datasources.DeleteDataSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[datasources.FetchDataSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[datasources.GetDataSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[datasources.ListDataSourcesRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[datasources.UpdateDataSourceRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..3eb1b5b07a2e --- /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,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. +# +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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..8afe6378fdba --- /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,704 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = FileUploadsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + FileUploadsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..071773dc0ca5 --- /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,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. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_datasources_v1beta.types import fileuploads +from .base import FileUploadsServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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..ef6996006854 --- /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,292 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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..cd6597b70bf8 --- /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,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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[fileuploads.GetFileUploadRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..8af0e5a52d60 --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..0c476161e247 --- /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,5682 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc"), + (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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 + 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 + 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 + + 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..f55255e283c0 --- /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,2177 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc"), + (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + 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 + 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 + 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..a57143cfa523 --- /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,557 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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..cdb582406777 --- /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,912 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + LocalInventoryServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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..5871c583a09f --- /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,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..0be6d5b83b71 --- /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,342 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..003e3774e885 --- /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,373 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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..27455f0a84ad --- /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,468 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[localinventory.DeleteLocalInventoryRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[localinventory.InsertLocalInventoryRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[localinventory.ListLocalInventoriesRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..4febadd1c18e --- /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,563 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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..fd6006001569 --- /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,918 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + RegionalInventoryServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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..ee92c7526c93 --- /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,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..8653391dd348 --- /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,343 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..831fffcc6cb1 --- /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,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 inspect +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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..624af3d0a99e --- /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,472 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[regionalinventory.DeleteRegionalInventoryRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[regionalinventory.InsertRegionalInventoryRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[regionalinventory.ListRegionalInventoriesRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..69c4a31abe8f --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..dc04243af8ed --- /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,3659 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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..2a170ce08be0 --- /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,3631 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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..2884af750669 --- /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,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. +# +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 + + +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, + + ) + + 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]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..e3a4a2405b8d --- /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,690 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = LfpInventoryServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + LfpInventoryServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..917f427714c7 --- /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,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_lfp_v1beta.types import lfpinventory +from .base import LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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..cf456e7875b7 --- /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,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. +# +import inspect +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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..ddb8c5ec385d --- /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,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 google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[lfpinventory.InsertLfpInventoryRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..ca50465ec57f --- /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,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. +# +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 + + +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, + + ) + + 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]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..a9430efaa34a --- /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,690 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = LfpSaleServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + LfpSaleServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..0d05b5dd995d --- /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,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. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_lfp_v1beta.types import lfpsale +from .base import LfpSaleServiceTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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..b7e6fa1eb3ad --- /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,293 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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..83b7ce536cc5 --- /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,278 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[lfpsale.InsertLfpSaleRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..cfeddc832339 --- /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,684 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..a9752c675163 --- /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,1037 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = LfpStoreServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + LfpStoreServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..03dd7df91e4f --- /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,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..6fd63b713cf4 --- /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,354 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..fdcfb49a78b7 --- /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,390 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..64366bfd71e8 --- /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,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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[lfpstore.DeleteLfpStoreRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[lfpstore.GetLfpStoreRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[lfpstore.InsertLfpStoreRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[lfpstore.ListLfpStoresRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..e3327910013f --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..e53a578cb2b0 --- /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,2152 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc"), + (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + 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 + 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 + 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..87e6c59d93b8 --- /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,2134 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc"), + (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + 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 + 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 + 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..7dafcb7fadae --- /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,4555 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc"), + (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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 + 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 + 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 + 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..c52ff70d9d59 --- /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,804 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + + +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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..00e3eb53aa9b --- /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,1156 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = NotificationsApiServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + NotificationsApiServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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 + + 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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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..4579e713049f --- /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,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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, str]] = ()): + """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, str]]): Strings which should be + sent along with the request as metadata. + """ + 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..d1082b9c738f --- /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,398 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..daaec0eb0334 --- /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,439 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # 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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..3704394b619b --- /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,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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 + + +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, str]]) -> Tuple[notificationsapi.CreateNotificationSubscriptionRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[notificationsapi.DeleteNotificationSubscriptionRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[notificationsapi.GetNotificationSubscriptionRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[notificationsapi.ListNotificationSubscriptionsRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[notificationsapi.UpdateNotificationSubscriptionRequest, Sequence[Tuple[str, str]]]: + """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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + 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) + + # 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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) + + # 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) + 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..834227f32181 --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..4aa3628ee715 --- /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,5172 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_class,transport_name", [ + (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc"), + (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + + 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 + 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 + 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 + 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-products/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-products/v1beta/.coveragerc new file mode 100644 index 000000000000..0d94c2da5109 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_products/__init__.py + google/shopping/merchant_products/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-products/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-products/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-products/v1beta/MANIFEST.in new file mode 100644 index 000000000000..eeb53abab351 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/shopping/merchant_products *.py +recursive-include google/shopping/merchant_products_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/README.rst new file mode 100644 index 000000000000..77b249a95743 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Shopping Merchant Products 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 Products 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-products/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/conf.py new file mode 100644 index 000000000000..7ba9f03c5b3f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products 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-products" +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-products-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-products.tex", + u"google-shopping-merchant-products 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-products", + u"Google Shopping Merchant Products 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-products", + u"google-shopping-merchant-products Documentation", + author, + "google-shopping-merchant-products", + "GAPIC library for Google Shopping Merchant Products 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-products/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/index.rst new file mode 100644 index 000000000000..b94cbc45f50d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_products_v1beta/services_ + merchant_products_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/product_inputs_service.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/product_inputs_service.rst new file mode 100644 index 000000000000..99e2c59bfb43 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/product_inputs_service.rst @@ -0,0 +1,6 @@ +ProductInputsService +-------------------------------------- + +.. automodule:: google.shopping.merchant_products_v1beta.services.product_inputs_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/products_service.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/products_service.rst new file mode 100644 index 000000000000..f20ce0b9e362 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/products_service.rst @@ -0,0 +1,10 @@ +ProductsService +--------------------------------- + +.. automodule:: google.shopping.merchant_products_v1beta.services.products_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_products_v1beta.services.products_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/services_.rst new file mode 100644 index 000000000000..ce641539544e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/services_.rst @@ -0,0 +1,7 @@ +Services for Google Shopping Merchant Products v1beta API +========================================================= +.. toctree:: + :maxdepth: 2 + + product_inputs_service + products_service diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/types_.rst new file mode 100644 index 000000000000..af3a6c59c20f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Products v1beta API +====================================================== + +.. automodule:: google.shopping.merchant_products_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/__init__.py new file mode 100644 index 000000000000..794f9625d9da --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/__init__.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_products import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_products_v1beta.services.product_inputs_service.client import ProductInputsServiceClient +from google.shopping.merchant_products_v1beta.services.product_inputs_service.async_client import ProductInputsServiceAsyncClient +from google.shopping.merchant_products_v1beta.services.products_service.client import ProductsServiceClient +from google.shopping.merchant_products_v1beta.services.products_service.async_client import ProductsServiceAsyncClient + +from google.shopping.merchant_products_v1beta.types.productinputs import DeleteProductInputRequest +from google.shopping.merchant_products_v1beta.types.productinputs import InsertProductInputRequest +from google.shopping.merchant_products_v1beta.types.productinputs import ProductInput +from google.shopping.merchant_products_v1beta.types.products import GetProductRequest +from google.shopping.merchant_products_v1beta.types.products import ListProductsRequest +from google.shopping.merchant_products_v1beta.types.products import ListProductsResponse +from google.shopping.merchant_products_v1beta.types.products import Product +from google.shopping.merchant_products_v1beta.types.products_common import Attributes +from google.shopping.merchant_products_v1beta.types.products_common import Certification +from google.shopping.merchant_products_v1beta.types.products_common import CloudExportAdditionalProperties +from google.shopping.merchant_products_v1beta.types.products_common import FreeShippingThreshold +from google.shopping.merchant_products_v1beta.types.products_common import Installment +from google.shopping.merchant_products_v1beta.types.products_common import LoyaltyPoints +from google.shopping.merchant_products_v1beta.types.products_common import LoyaltyProgram +from google.shopping.merchant_products_v1beta.types.products_common import ProductDetail +from google.shopping.merchant_products_v1beta.types.products_common import ProductDimension +from google.shopping.merchant_products_v1beta.types.products_common import ProductStatus +from google.shopping.merchant_products_v1beta.types.products_common import ProductStructuredDescription +from google.shopping.merchant_products_v1beta.types.products_common import ProductStructuredTitle +from google.shopping.merchant_products_v1beta.types.products_common import ProductWeight +from google.shopping.merchant_products_v1beta.types.products_common import Shipping +from google.shopping.merchant_products_v1beta.types.products_common import ShippingDimension +from google.shopping.merchant_products_v1beta.types.products_common import ShippingWeight +from google.shopping.merchant_products_v1beta.types.products_common import SubscriptionCost +from google.shopping.merchant_products_v1beta.types.products_common import Tax +from google.shopping.merchant_products_v1beta.types.products_common import UnitPricingBaseMeasure +from google.shopping.merchant_products_v1beta.types.products_common import UnitPricingMeasure +from google.shopping.merchant_products_v1beta.types.products_common import SubscriptionPeriod + +__all__ = ('ProductInputsServiceClient', + 'ProductInputsServiceAsyncClient', + 'ProductsServiceClient', + 'ProductsServiceAsyncClient', + 'DeleteProductInputRequest', + 'InsertProductInputRequest', + 'ProductInput', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'Product', + 'Attributes', + 'Certification', + 'CloudExportAdditionalProperties', + 'FreeShippingThreshold', + 'Installment', + 'LoyaltyPoints', + 'LoyaltyProgram', + 'ProductDetail', + 'ProductDimension', + 'ProductStatus', + 'ProductStructuredDescription', + 'ProductStructuredTitle', + 'ProductWeight', + 'Shipping', + 'ShippingDimension', + 'ShippingWeight', + 'SubscriptionCost', + 'Tax', + 'UnitPricingBaseMeasure', + 'UnitPricingMeasure', + 'SubscriptionPeriod', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/gapic_version.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/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-products/v1beta/google/shopping/merchant_products/py.typed b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/py.typed new file mode 100644 index 000000000000..962817aecdcd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-products package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/__init__.py new file mode 100644 index 000000000000..949f22e1af16 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_products_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.product_inputs_service import ProductInputsServiceClient +from .services.product_inputs_service import ProductInputsServiceAsyncClient +from .services.products_service import ProductsServiceClient +from .services.products_service import ProductsServiceAsyncClient + +from .types.productinputs import DeleteProductInputRequest +from .types.productinputs import InsertProductInputRequest +from .types.productinputs import ProductInput +from .types.products import GetProductRequest +from .types.products import ListProductsRequest +from .types.products import ListProductsResponse +from .types.products import Product +from .types.products_common import Attributes +from .types.products_common import Certification +from .types.products_common import CloudExportAdditionalProperties +from .types.products_common import FreeShippingThreshold +from .types.products_common import Installment +from .types.products_common import LoyaltyPoints +from .types.products_common import LoyaltyProgram +from .types.products_common import ProductDetail +from .types.products_common import ProductDimension +from .types.products_common import ProductStatus +from .types.products_common import ProductStructuredDescription +from .types.products_common import ProductStructuredTitle +from .types.products_common import ProductWeight +from .types.products_common import Shipping +from .types.products_common import ShippingDimension +from .types.products_common import ShippingWeight +from .types.products_common import SubscriptionCost +from .types.products_common import Tax +from .types.products_common import UnitPricingBaseMeasure +from .types.products_common import UnitPricingMeasure +from .types.products_common import SubscriptionPeriod + +__all__ = ( + 'ProductInputsServiceAsyncClient', + 'ProductsServiceAsyncClient', +'Attributes', +'Certification', +'CloudExportAdditionalProperties', +'DeleteProductInputRequest', +'FreeShippingThreshold', +'GetProductRequest', +'InsertProductInputRequest', +'Installment', +'ListProductsRequest', +'ListProductsResponse', +'LoyaltyPoints', +'LoyaltyProgram', +'Product', +'ProductDetail', +'ProductDimension', +'ProductInput', +'ProductInputsServiceClient', +'ProductStatus', +'ProductStructuredDescription', +'ProductStructuredTitle', +'ProductWeight', +'ProductsServiceClient', +'Shipping', +'ShippingDimension', +'ShippingWeight', +'SubscriptionCost', +'SubscriptionPeriod', +'Tax', +'UnitPricingBaseMeasure', +'UnitPricingMeasure', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..ac0f69541032 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_metadata.json @@ -0,0 +1,107 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_products_v1beta", + "protoPackage": "google.shopping.merchant.products.v1beta", + "schema": "1.0", + "services": { + "ProductInputsService": { + "clients": { + "grpc": { + "libraryClient": "ProductInputsServiceClient", + "rpcs": { + "DeleteProductInput": { + "methods": [ + "delete_product_input" + ] + }, + "InsertProductInput": { + "methods": [ + "insert_product_input" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductInputsServiceAsyncClient", + "rpcs": { + "DeleteProductInput": { + "methods": [ + "delete_product_input" + ] + }, + "InsertProductInput": { + "methods": [ + "insert_product_input" + ] + } + } + }, + "rest": { + "libraryClient": "ProductInputsServiceClient", + "rpcs": { + "DeleteProductInput": { + "methods": [ + "delete_product_input" + ] + }, + "InsertProductInput": { + "methods": [ + "insert_product_input" + ] + } + } + } + } + }, + "ProductsService": { + "clients": { + "grpc": { + "libraryClient": "ProductsServiceClient", + "rpcs": { + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductsServiceAsyncClient", + "rpcs": { + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + } + } + }, + "rest": { + "libraryClient": "ProductsServiceClient", + "rpcs": { + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_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-products/v1beta/google/shopping/merchant_products_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/py.typed new file mode 100644 index 000000000000..962817aecdcd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-products package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_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-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/__init__.py new file mode 100644 index 000000000000..6bcc06bac82d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_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 ProductInputsServiceClient +from .async_client import ProductInputsServiceAsyncClient + +__all__ = ( + 'ProductInputsServiceClient', + 'ProductInputsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/async_client.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/async_client.py new file mode 100644 index 000000000000..68e62b1ccb77 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/async_client.py @@ -0,0 +1,462 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.shopping.merchant_products_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_products_v1beta.types import productinputs +from google.shopping.merchant_products_v1beta.types import products_common +from google.shopping.type.types import types +from .transports.base import ProductInputsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductInputsServiceGrpcAsyncIOTransport +from .client import ProductInputsServiceClient + + +class ProductInputsServiceAsyncClient: + """Service to use ProductInput resource. + This service works for products with online channel only. + """ + + _client: ProductInputsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ProductInputsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ProductInputsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ProductInputsServiceClient._DEFAULT_UNIVERSE + + product_path = staticmethod(ProductInputsServiceClient.product_path) + parse_product_path = staticmethod(ProductInputsServiceClient.parse_product_path) + product_input_path = staticmethod(ProductInputsServiceClient.product_input_path) + parse_product_input_path = staticmethod(ProductInputsServiceClient.parse_product_input_path) + common_billing_account_path = staticmethod(ProductInputsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductInputsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductInputsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductInputsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductInputsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductInputsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductInputsServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductInputsServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductInputsServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductInputsServiceClient.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: + ProductInputsServiceAsyncClient: The constructed client. + """ + return ProductInputsServiceClient.from_service_account_info.__func__(ProductInputsServiceAsyncClient, 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: + ProductInputsServiceAsyncClient: The constructed client. + """ + return ProductInputsServiceClient.from_service_account_file.__func__(ProductInputsServiceAsyncClient, 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 ProductInputsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductInputsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductInputsServiceTransport: 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 = ProductInputsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProductInputsServiceTransport, Callable[..., ProductInputsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product inputs 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,ProductInputsServiceTransport,Callable[..., ProductInputsServiceTransport]]]): + 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 ProductInputsServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ProductInputsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def insert_product_input(self, + request: Optional[Union[productinputs.InsertProductInputRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> productinputs.ProductInput: + r"""Uploads a product input to your Merchant Center + account. If an input with the same contentLanguage, + offerId, and dataSource already exists, this method + replaces that entry. + + After inserting, updating, or deleting a product input, + it may take several minutes before the processed product + 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_products_v1beta + + async def sample_insert_product_input(): + # Create a client + client = merchant_products_v1beta.ProductInputsServiceAsyncClient() + + # Initialize request argument(s) + product_input = merchant_products_v1beta.ProductInput() + product_input.channel = "LOCAL" + product_input.offer_id = "offer_id_value" + product_input.content_language = "content_language_value" + product_input.feed_label = "feed_label_value" + + request = merchant_products_v1beta.InsertProductInputRequest( + parent="parent_value", + product_input=product_input, + data_source="data_source_value", + ) + + # Make the request + response = await client.insert_product_input(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_products_v1beta.types.InsertProductInputRequest, dict]]): + The request object. Request message for the + InsertProductInput 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.shopping.merchant_products_v1beta.types.ProductInput: + This resource represents input data you submit for a product, not the + processed product that you see in Merchant Center, in + Shopping ads, or across Google surfaces. Product + inputs, rules and supplemental data source data are + combined to create the processed + [product][google.shopping.content.bundles.Products.Product]. + + Required product input attributes to pass data + validation checks are primarily defined in the + [Products Data + Specification](\ https://support.google.com/merchants/answer/188494). + + The following attributes are required: + [feedLabel][google.shopping.content.bundles.Products.feed_label], + [contentLanguage][google.shopping.content.bundles.Products.content_language] + and + [offerId][google.shopping.content.bundles.Products.offer_id]. + + After inserting, updating, or deleting a product + input, it may take several minutes before the + processed product can be retrieved. + + All fields in the product input and its sub-messages + match the English name of their corresponding + attribute in the vertical spec with [some + exceptions](\ https://support.google.com/merchants/answer/7052112). + + """ + # 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, productinputs.InsertProductInputRequest): + request = productinputs.InsertProductInputRequest(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_product_input] + + # Certain fields should be provided within 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_product_input(self, + request: Optional[Union[productinputs.DeleteProductInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a product input from your Merchant Center + account. + After inserting, updating, or deleting a product input, + it may take several minutes before the processed product + 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_products_v1beta + + async def sample_delete_product_input(): + # Create a client + client = merchant_products_v1beta.ProductInputsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.DeleteProductInputRequest( + name="name_value", + data_source="data_source_value", + ) + + # Make the request + await client.delete_product_input(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_products_v1beta.types.DeleteProductInputRequest, dict]]): + The request object. Request message for the + DeleteProductInput method. + name (:class:`str`): + Required. The name of the product + input resource to delete. Format: + accounts/{account}/productInputs/{product} + + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, productinputs.DeleteProductInputRequest): + request = productinputs.DeleteProductInputRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_product_input] + + # Certain fields should be provided within 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) -> "ProductInputsServiceAsyncClient": + 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__ = ( + "ProductInputsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/client.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/client.py new file mode 100644 index 000000000000..f0ca70750bc6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/client.py @@ -0,0 +1,827 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.shopping.merchant_products_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 + +from google.shopping.merchant_products_v1beta.types import productinputs +from google.shopping.merchant_products_v1beta.types import products_common +from google.shopping.type.types import types +from .transports.base import ProductInputsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductInputsServiceGrpcTransport +from .transports.grpc_asyncio import ProductInputsServiceGrpcAsyncIOTransport +from .transports.rest import ProductInputsServiceRestTransport + + +class ProductInputsServiceClientMeta(type): + """Metaclass for the ProductInputsService 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[ProductInputsServiceTransport]] + _transport_registry["grpc"] = ProductInputsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductInputsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ProductInputsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ProductInputsServiceTransport]: + """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 ProductInputsServiceClient(metaclass=ProductInputsServiceClientMeta): + """Service to use ProductInput resource. + This service works for products with online channel only. + """ + + @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: + ProductInputsServiceClient: 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: + ProductInputsServiceClient: 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) -> ProductInputsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductInputsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(account: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "accounts/{account}/products/{product}".format(account=account, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def product_input_path(account: str,productinput: str,) -> str: + """Returns a fully-qualified product_input string.""" + return "accounts/{account}/productInputs/{productinput}".format(account=account, productinput=productinput, ) + + @staticmethod + def parse_product_input_path(path: str) -> Dict[str,str]: + """Parses a product_input path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/productInputs/(?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 = ProductInputsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ProductInputsServiceClient._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 = ProductInputsServiceClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ProductInputsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ProductInputsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, ProductInputsServiceTransport, Callable[..., ProductInputsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the product inputs 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,ProductInputsServiceTransport,Callable[..., ProductInputsServiceTransport]]]): + 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 ProductInputsServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ProductInputsServiceClient._read_environment_variables() + self._client_cert_source = ProductInputsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ProductInputsServiceClient._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 + + 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, ProductInputsServiceTransport) + if transport_provided: + # transport is a ProductInputsServiceTransport 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(ProductInputsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ProductInputsServiceClient._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[ProductInputsServiceTransport], Callable[..., ProductInputsServiceTransport]] = ( + ProductInputsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ProductInputsServiceTransport], 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, + ) + + def insert_product_input(self, + request: Optional[Union[productinputs.InsertProductInputRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> productinputs.ProductInput: + r"""Uploads a product input to your Merchant Center + account. If an input with the same contentLanguage, + offerId, and dataSource already exists, this method + replaces that entry. + + After inserting, updating, or deleting a product input, + it may take several minutes before the processed product + 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_products_v1beta + + def sample_insert_product_input(): + # Create a client + client = merchant_products_v1beta.ProductInputsServiceClient() + + # Initialize request argument(s) + product_input = merchant_products_v1beta.ProductInput() + product_input.channel = "LOCAL" + product_input.offer_id = "offer_id_value" + product_input.content_language = "content_language_value" + product_input.feed_label = "feed_label_value" + + request = merchant_products_v1beta.InsertProductInputRequest( + parent="parent_value", + product_input=product_input, + data_source="data_source_value", + ) + + # Make the request + response = client.insert_product_input(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_products_v1beta.types.InsertProductInputRequest, dict]): + The request object. Request message for the + InsertProductInput method. + retry (google.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. + + Returns: + google.shopping.merchant_products_v1beta.types.ProductInput: + This resource represents input data you submit for a product, not the + processed product that you see in Merchant Center, in + Shopping ads, or across Google surfaces. Product + inputs, rules and supplemental data source data are + combined to create the processed + [product][google.shopping.content.bundles.Products.Product]. + + Required product input attributes to pass data + validation checks are primarily defined in the + [Products Data + Specification](\ https://support.google.com/merchants/answer/188494). + + The following attributes are required: + [feedLabel][google.shopping.content.bundles.Products.feed_label], + [contentLanguage][google.shopping.content.bundles.Products.content_language] + and + [offerId][google.shopping.content.bundles.Products.offer_id]. + + After inserting, updating, or deleting a product + input, it may take several minutes before the + processed product can be retrieved. + + All fields in the product input and its sub-messages + match the English name of their corresponding + attribute in the vertical spec with [some + exceptions](\ https://support.google.com/merchants/answer/7052112). + + """ + # 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, productinputs.InsertProductInputRequest): + request = productinputs.InsertProductInputRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_product_input] + + # Certain fields should be provided within 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_product_input(self, + request: Optional[Union[productinputs.DeleteProductInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a product input from your Merchant Center + account. + After inserting, updating, or deleting a product input, + it may take several minutes before the processed product + 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_products_v1beta + + def sample_delete_product_input(): + # Create a client + client = merchant_products_v1beta.ProductInputsServiceClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.DeleteProductInputRequest( + name="name_value", + data_source="data_source_value", + ) + + # Make the request + client.delete_product_input(request=request) + + Args: + request (Union[google.shopping.merchant_products_v1beta.types.DeleteProductInputRequest, dict]): + The request object. Request message for the + DeleteProductInput method. + name (str): + Required. The name of the product + input resource to delete. Format: + accounts/{account}/productInputs/{product} + + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick 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, productinputs.DeleteProductInputRequest): + request = productinputs.DeleteProductInputRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_product_input] + + # Certain fields should be provided within 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) -> "ProductInputsServiceClient": + 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__ = ( + "ProductInputsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/README.rst new file mode 100644 index 000000000000..fa031e4be3c9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProductInputsServiceTransport` is the ABC for all transports. +- public child `ProductInputsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProductInputsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProductInputsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProductInputsServiceRestTransport` 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-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/__init__.py new file mode 100644 index 000000000000..e1e036be5719 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_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 ProductInputsServiceTransport +from .grpc import ProductInputsServiceGrpcTransport +from .grpc_asyncio import ProductInputsServiceGrpcAsyncIOTransport +from .rest import ProductInputsServiceRestTransport +from .rest import ProductInputsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductInputsServiceTransport]] +_transport_registry['grpc'] = ProductInputsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductInputsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ProductInputsServiceRestTransport + +__all__ = ( + 'ProductInputsServiceTransport', + 'ProductInputsServiceGrpcTransport', + 'ProductInputsServiceGrpcAsyncIOTransport', + 'ProductInputsServiceRestTransport', + 'ProductInputsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/base.py new file mode 100644 index 000000000000..3d16fcf605f3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/base.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_products_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_products_v1beta.types import productinputs + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ProductInputsServiceTransport(abc.ABC): + """Abstract transport class for ProductInputsService.""" + + 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_product_input: gapic_v1.method.wrap_method( + self.insert_product_input, + default_timeout=None, + client_info=client_info, + ), + self.delete_product_input: gapic_v1.method.wrap_method( + self.delete_product_input, + 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_product_input(self) -> Callable[ + [productinputs.InsertProductInputRequest], + Union[ + productinputs.ProductInput, + Awaitable[productinputs.ProductInput] + ]]: + raise NotImplementedError() + + @property + def delete_product_input(self) -> Callable[ + [productinputs.DeleteProductInputRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductInputsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc.py new file mode 100644 index 000000000000..935022958cfc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc.py @@ -0,0 +1,309 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 + +import grpc # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_products_v1beta.types import productinputs +from .base import ProductInputsServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductInputsServiceGrpcTransport(ProductInputsServiceTransport): + """gRPC backend transport for ProductInputsService. + + Service to use ProductInput resource. + This service works for products with online channel only. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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_product_input(self) -> Callable[ + [productinputs.InsertProductInputRequest], + productinputs.ProductInput]: + r"""Return a callable for the insert product input method over gRPC. + + Uploads a product input to your Merchant Center + account. If an input with the same contentLanguage, + offerId, and dataSource already exists, this method + replaces that entry. + + After inserting, updating, or deleting a product input, + it may take several minutes before the processed product + can be retrieved. + + Returns: + Callable[[~.InsertProductInputRequest], + ~.ProductInput]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product_input' not in self._stubs: + self._stubs['insert_product_input'] = self.grpc_channel.unary_unary( + '/google.shopping.merchant.products.v1beta.ProductInputsService/InsertProductInput', + request_serializer=productinputs.InsertProductInputRequest.serialize, + response_deserializer=productinputs.ProductInput.deserialize, + ) + return self._stubs['insert_product_input'] + + @property + def delete_product_input(self) -> Callable[ + [productinputs.DeleteProductInputRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete product input method over gRPC. + + Deletes a product input from your Merchant Center + account. + After inserting, updating, or deleting a product input, + it may take several minutes before the processed product + can be retrieved. + + Returns: + Callable[[~.DeleteProductInputRequest], + ~.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_product_input' not in self._stubs: + self._stubs['delete_product_input'] = self.grpc_channel.unary_unary( + '/google.shopping.merchant.products.v1beta.ProductInputsService/DeleteProductInput', + request_serializer=productinputs.DeleteProductInputRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product_input'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductInputsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..fce4093a6a7a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc_asyncio.py @@ -0,0 +1,335 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_products_v1beta.types import productinputs +from .base import ProductInputsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductInputsServiceGrpcTransport + + +class ProductInputsServiceGrpcAsyncIOTransport(ProductInputsServiceTransport): + """gRPC AsyncIO backend transport for ProductInputsService. + + Service to use ProductInput resource. + This service works for products with online channel only. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_product_input(self) -> Callable[ + [productinputs.InsertProductInputRequest], + Awaitable[productinputs.ProductInput]]: + r"""Return a callable for the insert product input method over gRPC. + + Uploads a product input to your Merchant Center + account. If an input with the same contentLanguage, + offerId, and dataSource already exists, this method + replaces that entry. + + After inserting, updating, or deleting a product input, + it may take several minutes before the processed product + can be retrieved. + + Returns: + Callable[[~.InsertProductInputRequest], + Awaitable[~.ProductInput]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product_input' not in self._stubs: + self._stubs['insert_product_input'] = self.grpc_channel.unary_unary( + '/google.shopping.merchant.products.v1beta.ProductInputsService/InsertProductInput', + request_serializer=productinputs.InsertProductInputRequest.serialize, + response_deserializer=productinputs.ProductInput.deserialize, + ) + return self._stubs['insert_product_input'] + + @property + def delete_product_input(self) -> Callable[ + [productinputs.DeleteProductInputRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete product input method over gRPC. + + Deletes a product input from your Merchant Center + account. + After inserting, updating, or deleting a product input, + it may take several minutes before the processed product + can be retrieved. + + Returns: + Callable[[~.DeleteProductInputRequest], + 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_product_input' not in self._stubs: + self._stubs['delete_product_input'] = self.grpc_channel.unary_unary( + '/google.shopping.merchant.products.v1beta.ProductInputsService/DeleteProductInput', + request_serializer=productinputs.DeleteProductInputRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_product_input'] + + 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_product_input: self._wrap_method( + self.insert_product_input, + default_timeout=None, + client_info=client_info, + ), + self.delete_product_input: self._wrap_method( + self.delete_product_input, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'ProductInputsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py new file mode 100644 index 000000000000..5bff979ef5bb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.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 google.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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_products_v1beta.types import productinputs + + +from .rest_base import _BaseProductInputsServiceRestTransport +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 + + +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 ProductInputsServiceRestInterceptor: + """Interceptor for ProductInputsService. + + 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 ProductInputsServiceRestTransport. + + .. code-block:: python + class MyCustomProductInputsServiceInterceptor(ProductInputsServiceRestInterceptor): + def pre_delete_product_input(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_insert_product_input(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_product_input(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ProductInputsServiceRestTransport(interceptor=MyCustomProductInputsServiceInterceptor()) + client = ProductInputsServiceClient(transport=transport) + + + """ + def pre_delete_product_input(self, request: productinputs.DeleteProductInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[productinputs.DeleteProductInputRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_product_input + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProductInputsService server. + """ + return request, metadata + + def pre_insert_product_input(self, request: productinputs.InsertProductInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[productinputs.InsertProductInputRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for insert_product_input + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProductInputsService server. + """ + return request, metadata + + def post_insert_product_input(self, response: productinputs.ProductInput) -> productinputs.ProductInput: + """Post-rpc interceptor for insert_product_input + + Override in a subclass to manipulate the response + after it is returned by the ProductInputsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ProductInputsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ProductInputsServiceRestInterceptor + + +class ProductInputsServiceRestTransport(_BaseProductInputsServiceRestTransport): + """REST backend synchronous transport for ProductInputsService. + + Service to use ProductInput resource. + This service works for products with online channel only. + + This class defines the same methods as the primary client, so the + primary client can 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[ProductInputsServiceRestInterceptor] = 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 ProductInputsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DeleteProductInput(_BaseProductInputsServiceRestTransport._BaseDeleteProductInput, ProductInputsServiceRestStub): + def __hash__(self): + return hash("ProductInputsServiceRestTransport.DeleteProductInput") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: productinputs.DeleteProductInputRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete product input method over HTTP. + + Args: + request (~.productinputs.DeleteProductInputRequest): + The request object. Request message for the + DeleteProductInput method. + retry (google.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. + """ + + http_options = _BaseProductInputsServiceRestTransport._BaseDeleteProductInput._get_http_options() + request, metadata = self._interceptor.pre_delete_product_input(request, metadata) + transcoded_request = _BaseProductInputsServiceRestTransport._BaseDeleteProductInput._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseProductInputsServiceRestTransport._BaseDeleteProductInput._get_query_params_json(transcoded_request) + + # Send the request + response = ProductInputsServiceRestTransport._DeleteProductInput._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 _InsertProductInput(_BaseProductInputsServiceRestTransport._BaseInsertProductInput, ProductInputsServiceRestStub): + def __hash__(self): + return hash("ProductInputsServiceRestTransport.InsertProductInput") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: productinputs.InsertProductInputRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> productinputs.ProductInput: + r"""Call the insert product input method over HTTP. + + Args: + request (~.productinputs.InsertProductInputRequest): + The request object. Request message for the + InsertProductInput method. + retry (google.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. + + Returns: + ~.productinputs.ProductInput: + This resource represents input data you submit for a + product, not the processed product that you see in + Merchant Center, in Shopping ads, or across Google + surfaces. Product inputs, rules and supplemental data + source data are combined to create the processed + [product][google.shopping.content.bundles.Products.Product]. + + Required product input attributes to pass data + validation checks are primarily defined in the `Products + Data + Specification `__. + + The following attributes are required: + [feedLabel][google.shopping.content.bundles.Products.feed_label], + [contentLanguage][google.shopping.content.bundles.Products.content_language] + and + [offerId][google.shopping.content.bundles.Products.offer_id]. + + After inserting, updating, or deleting a product input, + it may take several minutes before the processed product + can be retrieved. + + All fields in the product input and its sub-messages + match the English name of their corresponding attribute + in the vertical spec with `some + exceptions `__. + + """ + + http_options = _BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_http_options() + request, metadata = self._interceptor.pre_insert_product_input(request, metadata) + transcoded_request = _BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_transcoded_request(http_options, request) + + body = _BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_query_params_json(transcoded_request) + + # Send the request + response = ProductInputsServiceRestTransport._InsertProductInput._get_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 = productinputs.ProductInput() + pb_resp = productinputs.ProductInput.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert_product_input(resp) + return resp + + @property + def delete_product_input(self) -> Callable[ + [productinputs.DeleteProductInputRequest], + 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._DeleteProductInput(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_product_input(self) -> Callable[ + [productinputs.InsertProductInputRequest], + productinputs.ProductInput]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InsertProductInput(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ProductInputsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest_base.py new file mode 100644 index 000000000000..ee9987784bae --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest_base.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. +# +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 ProductInputsServiceTransport, 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_products_v1beta.types import productinputs + + +class _BaseProductInputsServiceRestTransport(ProductInputsServiceTransport): + """Base REST backend transport for ProductInputsService. + + 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 _BaseDeleteProductInput: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "dataSource" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/products/v1beta/{name=accounts/*/productInputs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = productinputs.DeleteProductInputRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductInputsServiceRestTransport._BaseDeleteProductInput._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertProductInput: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "dataSource" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in 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': '/products/v1beta/{parent=accounts/*}/productInputs:insert', + 'body': 'product_input', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = productinputs.InsertProductInputRequest.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(_BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseProductInputsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/__init__.py new file mode 100644 index 000000000000..83e3a381efc6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_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 ProductsServiceClient +from .async_client import ProductsServiceAsyncClient + +__all__ = ( + 'ProductsServiceClient', + 'ProductsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/async_client.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/async_client.py new file mode 100644 index 000000000000..1fdd043a4e65 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/async_client.py @@ -0,0 +1,490 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.shopping.merchant_products_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_products_v1beta.services.products_service import pagers +from google.shopping.merchant_products_v1beta.types import products +from google.shopping.merchant_products_v1beta.types import products_common +from google.shopping.type.types import types +from .transports.base import ProductsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductsServiceGrpcAsyncIOTransport +from .client import ProductsServiceClient + + +class ProductsServiceAsyncClient: + """Service to use Product resource. + This service works for products with online channel only. + """ + + _client: ProductsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ProductsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ProductsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ProductsServiceClient._DEFAULT_UNIVERSE + + product_path = staticmethod(ProductsServiceClient.product_path) + parse_product_path = staticmethod(ProductsServiceClient.parse_product_path) + common_billing_account_path = staticmethod(ProductsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProductsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProductsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProductsServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProductsServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProductsServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProductsServiceClient.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: + ProductsServiceAsyncClient: The constructed client. + """ + return ProductsServiceClient.from_service_account_info.__func__(ProductsServiceAsyncClient, 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: + ProductsServiceAsyncClient: The constructed client. + """ + return ProductsServiceClient.from_service_account_file.__func__(ProductsServiceAsyncClient, 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 ProductsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProductsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductsServiceTransport: 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 = ProductsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProductsServiceTransport, Callable[..., ProductsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the products 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,ProductsServiceTransport,Callable[..., ProductsServiceTransport]]]): + 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 ProductsServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ProductsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_product(self, + request: Optional[Union[products.GetProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> products.Product: + r"""Retrieves the processed product from your Merchant + Center account. + After inserting, updating, or deleting a product input, + it may take several minutes before the updated final + product 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_products_v1beta + + async def sample_get_product(): + # Create a client + client = merchant_products_v1beta.ProductsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_products_v1beta.types.GetProductRequest, dict]]): + The request object. Request message for the GetProduct + method. + name (:class:`str`): + Required. The name of the product to retrieve. Format: + ``accounts/{account}/products/{product}`` + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.shopping.merchant_products_v1beta.types.Product: + The processed product, built from multiple [product + inputs][[google.shopping.content.bundles.Products.ProductInput] + after applying rules and supplemental data sources. + This processed product matches what is shown in your + Merchant Center account and in Shopping ads and other + surfaces across Google. Each product is built from + exactly one primary data source product input, and + multiple supplemental data source inputs. After + inserting, updating, or deleting a product input, it + may take several minutes before the updated processed + product can be retrieved. + + All fields in the processed product and its + sub-messages match the name of their corresponding + attribute in the [Product data + specification](\ https://support.google.com/merchants/answer/7052112) + with some exceptions. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, products.GetProductRequest): + request = products.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_products(self, + request: Optional[Union[products.ListProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Lists the processed products 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, updating, or deleting a product input, + it may take several minutes before the updated processed + product 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_products_v1beta + + async def sample_list_products(): + # Create a client + client = merchant_products_v1beta.ProductsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_products_v1beta.types.ListProductsRequest, dict]]): + The request object. Request message for the ListProducts + method. + parent (:class:`str`): + Required. The account to list + processed products 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.shopping.merchant_products_v1beta.services.products_service.pagers.ListProductsAsyncPager: + Response message for the ListProducts + 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, products.ListProductsRequest): + request = products.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # 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.ListProductsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ProductsServiceAsyncClient": + 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__ = ( + "ProductsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/client.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/client.py new file mode 100644 index 000000000000..e11759667b94 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/client.py @@ -0,0 +1,845 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.shopping.merchant_products_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 + +from google.shopping.merchant_products_v1beta.services.products_service import pagers +from google.shopping.merchant_products_v1beta.types import products +from google.shopping.merchant_products_v1beta.types import products_common +from google.shopping.type.types import types +from .transports.base import ProductsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductsServiceGrpcTransport +from .transports.grpc_asyncio import ProductsServiceGrpcAsyncIOTransport +from .transports.rest import ProductsServiceRestTransport + + +class ProductsServiceClientMeta(type): + """Metaclass for the ProductsService 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[ProductsServiceTransport]] + _transport_registry["grpc"] = ProductsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProductsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ProductsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ProductsServiceTransport]: + """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 ProductsServiceClient(metaclass=ProductsServiceClientMeta): + """Service to use Product resource. + This service works for products with online channel only. + """ + + @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: + ProductsServiceClient: 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: + ProductsServiceClient: 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) -> ProductsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProductsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def product_path(account: str,product: str,) -> str: + """Returns a fully-qualified product string.""" + return "accounts/{account}/products/{product}".format(account=account, product=product, ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str,str]: + """Parses a product path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/products/(?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 = ProductsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ProductsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ProductsServiceClient._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 = ProductsServiceClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ProductsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ProductsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def 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, ProductsServiceTransport, Callable[..., ProductsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the products 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,ProductsServiceTransport,Callable[..., ProductsServiceTransport]]]): + 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 ProductsServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ProductsServiceClient._read_environment_variables() + self._client_cert_source = ProductsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ProductsServiceClient._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 + + 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, ProductsServiceTransport) + if transport_provided: + # transport is a ProductsServiceTransport 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(ProductsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ProductsServiceClient._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[ProductsServiceTransport], Callable[..., ProductsServiceTransport]] = ( + ProductsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ProductsServiceTransport], 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, + ) + + def get_product(self, + request: Optional[Union[products.GetProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> products.Product: + r"""Retrieves the processed product from your Merchant + Center account. + After inserting, updating, or deleting a product input, + it may take several minutes before the updated final + product 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_products_v1beta + + def sample_get_product(): + # Create a client + client = merchant_products_v1beta.ProductsServiceClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_products_v1beta.types.GetProductRequest, dict]): + The request object. Request message for the GetProduct + method. + name (str): + Required. The name of the product to retrieve. Format: + ``accounts/{account}/products/{product}`` + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.shopping.merchant_products_v1beta.types.Product: + The processed product, built from multiple [product + inputs][[google.shopping.content.bundles.Products.ProductInput] + after applying rules and supplemental data sources. + This processed product matches what is shown in your + Merchant Center account and in Shopping ads and other + surfaces across Google. Each product is built from + exactly one primary data source product input, and + multiple supplemental data source inputs. After + inserting, updating, or deleting a product input, it + may take several minutes before the updated processed + product can be retrieved. + + All fields in the processed product and its + sub-messages match the name of their corresponding + attribute in the [Product data + specification](\ https://support.google.com/merchants/answer/7052112) + with some exceptions. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, products.GetProductRequest): + request = products.GetProductRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_products(self, + request: Optional[Union[products.ListProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Lists the processed products 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, updating, or deleting a product input, + it may take several minutes before the updated processed + product 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_products_v1beta + + def sample_list_products(): + # Create a client + client = merchant_products_v1beta.ProductsServiceClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_products_v1beta.types.ListProductsRequest, dict]): + The request object. Request message for the ListProducts + method. + parent (str): + Required. The account to list + processed products 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.shopping.merchant_products_v1beta.services.products_service.pagers.ListProductsPager: + Response message for the ListProducts + 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, products.ListProductsRequest): + request = products.ListProductsRequest(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_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # 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.ListProductsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ProductsServiceClient": + 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__ = ( + "ProductsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/pagers.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/pagers.py new file mode 100644 index 000000000000..030d3c3e9284 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_products_v1beta.types import products + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_products_v1beta.types.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_products_v1beta.types.ListProductsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., products.ListProductsResponse], + request: products.ListProductsRequest, + response: products.ListProductsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_products_v1beta.types.ListProductsRequest): + The initial request object. + response (google.shopping.merchant_products_v1beta.types.ListProductsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = products.ListProductsRequest(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[products.ListProductsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[products.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_products_v1beta.types.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_products_v1beta.types.ListProductsResponse` + attributes are available on the 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[products.ListProductsResponse]], + request: products.ListProductsRequest, + response: products.ListProductsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_products_v1beta.types.ListProductsRequest): + The initial request object. + response (google.shopping.merchant_products_v1beta.types.ListProductsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = products.ListProductsRequest(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[products.ListProductsResponse]: + 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[products.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + 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-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/README.rst new file mode 100644 index 000000000000..c1cbe3d98697 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProductsServiceTransport` is the ABC for all transports. +- public child `ProductsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProductsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProductsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProductsServiceRestTransport` 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-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/__init__.py new file mode 100644 index 000000000000..328b51677c37 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_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 ProductsServiceTransport +from .grpc import ProductsServiceGrpcTransport +from .grpc_asyncio import ProductsServiceGrpcAsyncIOTransport +from .rest import ProductsServiceRestTransport +from .rest import ProductsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductsServiceTransport]] +_transport_registry['grpc'] = ProductsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProductsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ProductsServiceRestTransport + +__all__ = ( + 'ProductsServiceTransport', + 'ProductsServiceGrpcTransport', + 'ProductsServiceGrpcAsyncIOTransport', + 'ProductsServiceRestTransport', + 'ProductsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/base.py new file mode 100644 index 000000000000..d9294b8fb782 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_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_products_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_products_v1beta.types import products + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ProductsServiceTransport(abc.ABC): + """Abstract transport class for ProductsService.""" + + 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_product: gapic_v1.method.wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + 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_product(self) -> Callable[ + [products.GetProductRequest], + Union[ + products.Product, + Awaitable[products.Product] + ]]: + raise NotImplementedError() + + @property + def list_products(self) -> Callable[ + [products.ListProductsRequest], + Union[ + products.ListProductsResponse, + Awaitable[products.ListProductsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProductsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc.py new file mode 100644 index 000000000000..1d1389b6dee7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc.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. +# +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 + +import grpc # type: ignore + +from google.shopping.merchant_products_v1beta.types import products +from .base import ProductsServiceTransport, DEFAULT_CLIENT_INFO + + +class ProductsServiceGrpcTransport(ProductsServiceTransport): + """gRPC backend transport for ProductsService. + + Service to use Product resource. + This service works for products with online channel only. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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_product(self) -> Callable[ + [products.GetProductRequest], + products.Product]: + r"""Return a callable for the get product method over gRPC. + + Retrieves the processed product from your Merchant + Center account. + After inserting, updating, or deleting a product input, + it may take several minutes before the updated final + product can be retrieved. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.shopping.merchant.products.v1beta.ProductsService/GetProduct', + request_serializer=products.GetProductRequest.serialize, + response_deserializer=products.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [products.ListProductsRequest], + products.ListProductsResponse]: + r"""Return a callable for the list products method over gRPC. + + Lists the processed products 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, updating, or deleting a product input, + it may take several minutes before the updated processed + product can be retrieved. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.shopping.merchant.products.v1beta.ProductsService/ListProducts', + request_serializer=products.ListProductsRequest.serialize, + response_deserializer=products.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProductsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..064e2defaa37 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc_asyncio.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 inspect +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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.shopping.merchant_products_v1beta.types import products +from .base import ProductsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductsServiceGrpcTransport + + +class ProductsServiceGrpcAsyncIOTransport(ProductsServiceTransport): + """gRPC AsyncIO backend transport for ProductsService. + + Service to use Product resource. + This service works for products with online channel only. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_product(self) -> Callable[ + [products.GetProductRequest], + Awaitable[products.Product]]: + r"""Return a callable for the get product method over gRPC. + + Retrieves the processed product from your Merchant + Center account. + After inserting, updating, or deleting a product input, + it may take several minutes before the updated final + product can be retrieved. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_product' not in self._stubs: + self._stubs['get_product'] = self.grpc_channel.unary_unary( + '/google.shopping.merchant.products.v1beta.ProductsService/GetProduct', + request_serializer=products.GetProductRequest.serialize, + response_deserializer=products.Product.deserialize, + ) + return self._stubs['get_product'] + + @property + def list_products(self) -> Callable[ + [products.ListProductsRequest], + Awaitable[products.ListProductsResponse]]: + r"""Return a callable for the list products method over gRPC. + + Lists the processed products 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, updating, or deleting a product input, + it may take several minutes before the updated processed + product can be retrieved. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_products' not in self._stubs: + self._stubs['list_products'] = self.grpc_channel.unary_unary( + '/google.shopping.merchant.products.v1beta.ProductsService/ListProducts', + request_serializer=products.ListProductsRequest.serialize, + response_deserializer=products.ListProductsResponse.deserialize, + ) + return self._stubs['list_products'] + + 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_product: self._wrap_method( + self.get_product, + default_timeout=None, + client_info=client_info, + ), + self.list_products: self._wrap_method( + self.list_products, + 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.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'ProductsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py new file mode 100644 index 000000000000..9e0d6af98d9f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py @@ -0,0 +1,398 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # 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_products_v1beta.types import products + + +from .rest_base import _BaseProductsServiceRestTransport +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 + + +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 ProductsServiceRestInterceptor: + """Interceptor for ProductsService. + + 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 ProductsServiceRestTransport. + + .. code-block:: python + class MyCustomProductsServiceInterceptor(ProductsServiceRestInterceptor): + def pre_get_product(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_product(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_products(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_products(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ProductsServiceRestTransport(interceptor=MyCustomProductsServiceInterceptor()) + client = ProductsServiceClient(transport=transport) + + + """ + def pre_get_product(self, request: products.GetProductRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[products.GetProductRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_product + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProductsService server. + """ + return request, metadata + + def post_get_product(self, response: products.Product) -> products.Product: + """Post-rpc interceptor for get_product + + Override in a subclass to manipulate the response + after it is returned by the ProductsService server but before + it is returned to user code. + """ + return response + + def pre_list_products(self, request: products.ListProductsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[products.ListProductsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_products + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProductsService server. + """ + return request, metadata + + def post_list_products(self, response: products.ListProductsResponse) -> products.ListProductsResponse: + """Post-rpc interceptor for list_products + + Override in a subclass to manipulate the response + after it is returned by the ProductsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ProductsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ProductsServiceRestInterceptor + + +class ProductsServiceRestTransport(_BaseProductsServiceRestTransport): + """REST backend synchronous transport for ProductsService. + + Service to use Product resource. + This service works for products with online channel only. + + This class defines the same methods as the primary client, so the + primary client can 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[ProductsServiceRestInterceptor] = 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 ProductsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetProduct(_BaseProductsServiceRestTransport._BaseGetProduct, ProductsServiceRestStub): + def __hash__(self): + return hash("ProductsServiceRestTransport.GetProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: products.GetProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> products.Product: + r"""Call the get product method over HTTP. + + Args: + request (~.products.GetProductRequest): + The request object. Request message for the GetProduct + method. + retry (google.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. + + Returns: + ~.products.Product: + The processed product, built from multiple [product + inputs][[google.shopping.content.bundles.Products.ProductInput] + after applying rules and supplemental data sources. This + processed product matches what is shown in your Merchant + Center account and in Shopping ads and other surfaces + across Google. Each product is built from exactly one + primary data source product input, and multiple + supplemental data source inputs. After inserting, + updating, or deleting a product input, it may take + several minutes before the updated processed product can + be retrieved. + + All fields in the processed product and its sub-messages + match the name of their corresponding attribute in the + `Product data + specification `__ + with some exceptions. + + """ + + http_options = _BaseProductsServiceRestTransport._BaseGetProduct._get_http_options() + request, metadata = self._interceptor.pre_get_product(request, metadata) + transcoded_request = _BaseProductsServiceRestTransport._BaseGetProduct._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseProductsServiceRestTransport._BaseGetProduct._get_query_params_json(transcoded_request) + + # Send the request + response = ProductsServiceRestTransport._GetProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = products.Product() + pb_resp = products.Product.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_product(resp) + return resp + + class _ListProducts(_BaseProductsServiceRestTransport._BaseListProducts, ProductsServiceRestStub): + def __hash__(self): + return hash("ProductsServiceRestTransport.ListProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: products.ListProductsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> products.ListProductsResponse: + r"""Call the list products method over HTTP. + + Args: + request (~.products.ListProductsRequest): + The request object. Request message for the ListProducts + method. + retry (google.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. + + Returns: + ~.products.ListProductsResponse: + Response message for the ListProducts + method. + + """ + + http_options = _BaseProductsServiceRestTransport._BaseListProducts._get_http_options() + request, metadata = self._interceptor.pre_list_products(request, metadata) + transcoded_request = _BaseProductsServiceRestTransport._BaseListProducts._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseProductsServiceRestTransport._BaseListProducts._get_query_params_json(transcoded_request) + + # Send the request + response = ProductsServiceRestTransport._ListProducts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = products.ListProductsResponse() + pb_resp = products.ListProductsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_products(resp) + return resp + + @property + def get_product(self) -> Callable[ + [products.GetProductRequest], + products.Product]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProduct(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_products(self) -> Callable[ + [products.ListProductsRequest], + products.ListProductsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProducts(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ProductsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest_base.py new file mode 100644 index 000000000000..ea9a202f4e6d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_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 ProductsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_products_v1beta.types import products + + +class _BaseProductsServiceRestTransport(ProductsServiceTransport): + """Base REST backend transport for ProductsService. + + 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 _BaseGetProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/products/v1beta/{name=accounts/*/products/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = products.GetProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductsServiceRestTransport._BaseGetProduct._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/products/v1beta/{parent=accounts/*}/products', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = products.ListProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductsServiceRestTransport._BaseListProducts._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseProductsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/__init__.py new file mode 100644 index 000000000000..34321319c6a0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .productinputs import ( + DeleteProductInputRequest, + InsertProductInputRequest, + ProductInput, +) +from .products import ( + GetProductRequest, + ListProductsRequest, + ListProductsResponse, + Product, +) +from .products_common import ( + Attributes, + Certification, + CloudExportAdditionalProperties, + FreeShippingThreshold, + Installment, + LoyaltyPoints, + LoyaltyProgram, + ProductDetail, + ProductDimension, + ProductStatus, + ProductStructuredDescription, + ProductStructuredTitle, + ProductWeight, + Shipping, + ShippingDimension, + ShippingWeight, + SubscriptionCost, + Tax, + UnitPricingBaseMeasure, + UnitPricingMeasure, + SubscriptionPeriod, +) + +__all__ = ( + 'DeleteProductInputRequest', + 'InsertProductInputRequest', + 'ProductInput', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'Product', + 'Attributes', + 'Certification', + 'CloudExportAdditionalProperties', + 'FreeShippingThreshold', + 'Installment', + 'LoyaltyPoints', + 'LoyaltyProgram', + 'ProductDetail', + 'ProductDimension', + 'ProductStatus', + 'ProductStructuredDescription', + 'ProductStructuredTitle', + 'ProductWeight', + 'Shipping', + 'ShippingDimension', + 'ShippingWeight', + 'SubscriptionCost', + 'Tax', + 'UnitPricingBaseMeasure', + 'UnitPricingMeasure', + 'SubscriptionPeriod', +) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/productinputs.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/productinputs.py new file mode 100644 index 000000000000..c436ce740300 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/productinputs.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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_products_v1beta.types import products_common +from google.shopping.type.types import types + + +__protobuf__ = proto.module( + package='google.shopping.merchant.products.v1beta', + manifest={ + 'ProductInput', + 'InsertProductInputRequest', + 'DeleteProductInputRequest', + }, +) + + +class ProductInput(proto.Message): + r"""This resource represents input data you submit for a product, not + the processed product that you see in Merchant Center, in Shopping + ads, or across Google surfaces. Product inputs, rules and + supplemental data source data are combined to create the processed + [product][google.shopping.content.bundles.Products.Product]. + + Required product input attributes to pass data validation checks are + primarily defined in the `Products Data + Specification `__. + + The following attributes are required: + [feedLabel][google.shopping.content.bundles.Products.feed_label], + [contentLanguage][google.shopping.content.bundles.Products.content_language] + and [offerId][google.shopping.content.bundles.Products.offer_id]. + + After inserting, updating, or deleting a product input, it may take + several minutes before the processed product can be retrieved. + + All fields in the product input and its sub-messages match the + English name of their corresponding attribute in the vertical spec + with `some + exceptions `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The name of the product input. Format: + ``"{productinput.name=accounts/{account}/productInputs/{productinput}}"`` + product (str): + Output only. The name of the processed product. Format: + ``"{product.name=accounts/{account}/products/{product}}"`` + channel (google.shopping.type.types.Channel.ChannelEnum): + Required. Immutable. The + `channel `__ + of the product. + offer_id (str): + Required. Immutable. Your unique identifier for the product. + This is the same for the product input and processed + product. Leading and trailing whitespaces are stripped and + multiple whitespaces are replaced by a single whitespace + upon submission. See the `products data + specification `__ + for details. + content_language (str): + Required. Immutable. The two-letter `ISO + 639-1 `__ language + code for the product. + feed_label (str): + Required. Immutable. The `feed + label `__ + for the product. + version_number (int): + Optional. Represents the existing version (freshness) of the + product, 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 + product. Re-insertion (for example, product refresh after 30 + days) can be performed with the current ``version_number``. + + Only supported for insertions into primary data sources. + + If the operation is prevented, the aborted exception will be + thrown. + + This field is a member of `oneof`_ ``_version_number``. + attributes (google.shopping.merchant_products_v1beta.types.Attributes): + Optional. A list of product 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, such as additional attributes used for Buy on + Google. Maximum allowed number of characters for each custom + attribute is 10240 (represents sum of characters for name + and value). Maximum 2500 custom attributes can be set per + product, with total size of 102.4kB. Underscores in custom + attribute names are replaced by spaces upon insertion. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + product: str = proto.Field( + proto.STRING, + number=2, + ) + channel: types.Channel.ChannelEnum = proto.Field( + proto.ENUM, + number=3, + enum=types.Channel.ChannelEnum, + ) + offer_id: str = proto.Field( + proto.STRING, + number=4, + ) + content_language: str = proto.Field( + proto.STRING, + number=5, + ) + feed_label: str = proto.Field( + proto.STRING, + number=6, + ) + version_number: int = proto.Field( + proto.INT64, + number=7, + optional=True, + ) + attributes: products_common.Attributes = proto.Field( + proto.MESSAGE, + number=8, + message=products_common.Attributes, + ) + custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=types.CustomAttribute, + ) + + +class InsertProductInputRequest(proto.Message): + r"""Request message for the InsertProductInput method. + + Attributes: + parent (str): + Required. The account where this product will + be inserted. Format: accounts/{account} + product_input (google.shopping.merchant_products_v1beta.types.ProductInput): + Required. The product input to insert. + data_source (str): + Required. The primary or supplemental product data source + name. If the product already exists and data source provided + is different, then the product will be moved to a new data + source. Format: + ``accounts/{account}/dataSources/{datasource}``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + product_input: 'ProductInput' = proto.Field( + proto.MESSAGE, + number=2, + message='ProductInput', + ) + data_source: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteProductInputRequest(proto.Message): + r"""Request message for the DeleteProductInput method. + + Attributes: + name (str): + Required. The name of the product input + resource to delete. Format: + accounts/{account}/productInputs/{product} + data_source (str): + Required. The primary or supplemental data source from which + the product input should be deleted. Format: + ``accounts/{account}/dataSources/{datasource}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data_source: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products.py new file mode 100644 index 000000000000..ae8d34200ede --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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_products_v1beta.types import products_common +from google.shopping.type.types import types + + +__protobuf__ = proto.module( + package='google.shopping.merchant.products.v1beta', + manifest={ + 'Product', + 'GetProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + }, +) + + +class Product(proto.Message): + r"""The processed product, built from multiple [product + inputs][[google.shopping.content.bundles.Products.ProductInput] + after applying rules and supplemental data sources. This processed + product matches what is shown in your Merchant Center account and in + Shopping ads and other surfaces across Google. Each product is built + from exactly one primary data source product input, and multiple + supplemental data source inputs. After inserting, updating, or + deleting a product input, it may take several minutes before the + updated processed product can be retrieved. + + All fields in the processed product and its sub-messages match the + name of their corresponding attribute in the `Product data + specification `__ + with some exceptions. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The name of the product. Format: + ``"{product.name=accounts/{account}/products/{product}}"`` + channel (google.shopping.type.types.Channel.ChannelEnum): + Output only. The + `channel `__ + of the product. + offer_id (str): + Output only. Your unique identifier for the product. This is + the same for the product input and processed product. + Leading and trailing whitespaces are stripped and multiple + whitespaces are replaced by a single whitespace upon + submission. See the `product data + specification `__ + for details. + content_language (str): + Output only. The two-letter `ISO + 639-1 `__ language + code for the product. + feed_label (str): + Output only. The feed label for the product. + data_source (str): + Output only. The primary data source of the + product. + version_number (int): + Output only. Represents the existing version (freshness) of + the product, 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 + product. Re-insertion (for example, product refresh after 30 + days) can be performed with the current ``version_number``. + + Only supported for insertions into primary data sources. + + If the operation is prevented, the aborted exception will be + thrown. + + This field is a member of `oneof`_ ``_version_number``. + attributes (google.shopping.merchant_products_v1beta.types.Attributes): + Output only. A list of product attributes. + custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): + Output only. A list of custom (merchant-provided) + attributes. It can also be used to submit 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, such as additional attributes used for Buy on + Google. + product_status (google.shopping.merchant_products_v1beta.types.ProductStatus): + Output only. The status of a product, data + validation issues, that is, information about a + product computed asynchronously. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + channel: types.Channel.ChannelEnum = proto.Field( + proto.ENUM, + number=2, + enum=types.Channel.ChannelEnum, + ) + offer_id: str = proto.Field( + proto.STRING, + number=3, + ) + content_language: str = proto.Field( + proto.STRING, + number=4, + ) + feed_label: str = proto.Field( + proto.STRING, + number=5, + ) + data_source: str = proto.Field( + proto.STRING, + number=6, + ) + version_number: int = proto.Field( + proto.INT64, + number=7, + optional=True, + ) + attributes: products_common.Attributes = proto.Field( + proto.MESSAGE, + number=8, + message=products_common.Attributes, + ) + custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=types.CustomAttribute, + ) + product_status: products_common.ProductStatus = proto.Field( + proto.MESSAGE, + number=10, + message=products_common.ProductStatus, + ) + + +class GetProductRequest(proto.Message): + r"""Request message for the GetProduct method. + + Attributes: + name (str): + Required. The name of the product to retrieve. Format: + ``accounts/{account}/products/{product}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProductsRequest(proto.Message): + r"""Request message for the ListProducts method. + + Attributes: + parent (str): + Required. The account to list processed + products for. Format: accounts/{account} + page_size (int): + The maximum number of products 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 products will be returned. + page_token (str): + A page token, received from a previous ``ListProducts`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListProducts`` 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 ListProductsResponse(proto.Message): + r"""Response message for the ListProducts method. + + Attributes: + products (MutableSequence[google.shopping.merchant_products_v1beta.types.Product]): + The processed products from the specified + account. These are your processed products after + applying rules and supplemental data sources. + 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 + + products: MutableSequence['Product'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Product', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products_common.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products_common.py new file mode 100644 index 000000000000..17ed5bd1355b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products_common.py @@ -0,0 +1,1906 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.products.v1beta', + manifest={ + 'SubscriptionPeriod', + 'Attributes', + 'Tax', + 'ShippingWeight', + 'ShippingDimension', + 'UnitPricingBaseMeasure', + 'UnitPricingMeasure', + 'SubscriptionCost', + 'Installment', + 'LoyaltyPoints', + 'LoyaltyProgram', + 'Shipping', + 'FreeShippingThreshold', + 'ProductDetail', + 'Certification', + 'ProductStructuredTitle', + 'ProductStructuredDescription', + 'ProductDimension', + 'ProductWeight', + 'ProductStatus', + 'CloudExportAdditionalProperties', + }, +) + + +class SubscriptionPeriod(proto.Enum): + r"""The subscription period of the product. + + Values: + SUBSCRIPTION_PERIOD_UNSPECIFIED (0): + Indicates that the subscription period is + unspecified. + MONTH (1): + Indicates that the subscription period is + month. + YEAR (2): + Indicates that the subscription period is + year. + """ + SUBSCRIPTION_PERIOD_UNSPECIFIED = 0 + MONTH = 1 + YEAR = 2 + + +class Attributes(proto.Message): + r"""Attributes. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + identifier_exists (bool): + Set this value to false when the item does + not have unique product identifiers appropriate + to its category, such as GTIN, MPN, and brand. + Defaults to true, if not provided. + + This field is a member of `oneof`_ ``_identifier_exists``. + is_bundle (bool): + Whether the item is a merchant-defined + bundle. A bundle is a custom grouping of + different products sold by a merchant for a + single price. + + This field is a member of `oneof`_ ``_is_bundle``. + title (str): + Title of the item. + + This field is a member of `oneof`_ ``_title``. + description (str): + Description of the item. + + This field is a member of `oneof`_ ``_description``. + link (str): + URL directly linking to your item's page on + your online store. + + This field is a member of `oneof`_ ``_link``. + mobile_link (str): + URL for the mobile-optimized version of your + item's landing page. + + This field is a member of `oneof`_ ``_mobile_link``. + canonical_link (str): + URL for the canonical version of your item's + landing page. + + This field is a member of `oneof`_ ``_canonical_link``. + image_link (str): + URL of an image of the item. + + This field is a member of `oneof`_ ``_image_link``. + additional_image_links (MutableSequence[str]): + Additional URLs of images of the item. + expiration_date (google.protobuf.timestamp_pb2.Timestamp): + Date on which the item should expire, as specified upon + insertion, in `ISO + 8601 `__ format. The + actual expiration date is exposed in ``productstatuses`` as + `googleExpirationDate `__ + and might be earlier if ``expirationDate`` is too far in the + future. + disclosure_date (google.protobuf.timestamp_pb2.Timestamp): + The date time when an offer becomes visible in search + results across Google’s YouTube surfaces, in `ISO + 8601 `__ format. See + `Disclosure + date `__ + for more information. + adult (bool): + Set to true if the item is targeted towards + adults. + + This field is a member of `oneof`_ ``_adult``. + age_group (str): + Target `age + group `__ + of the item. + + This field is a member of `oneof`_ ``_age_group``. + availability (str): + Availability status of the item. + + This field is a member of `oneof`_ ``_availability``. + availability_date (google.protobuf.timestamp_pb2.Timestamp): + The day a pre-ordered product becomes available for + delivery, in `ISO + 8601 `__ format. + brand (str): + Brand of the item. + + This field is a member of `oneof`_ ``_brand``. + color (str): + Color of the item. + + This field is a member of `oneof`_ ``_color``. + condition (str): + Condition or state of the item. + + This field is a member of `oneof`_ ``_condition``. + gender (str): + Target gender of the item. + + This field is a member of `oneof`_ ``_gender``. + google_product_category (str): + Google's category of the item (see `Google product + taxonomy `__). + When querying products, this field will contain the user + provided value. There is currently no way to get back the + auto assigned google product categories through the API. + + This field is a member of `oneof`_ ``_google_product_category``. + gtin (str): + Global Trade Item Number + (`GTIN `__) + of the item. + + This field is a member of `oneof`_ ``_gtin``. + item_group_id (str): + Shared identifier for all variants of the + same product. + + This field is a member of `oneof`_ ``_item_group_id``. + material (str): + The material of which the item is made. + + This field is a member of `oneof`_ ``_material``. + mpn (str): + Manufacturer Part Number + (`MPN `__) + of the item. + + This field is a member of `oneof`_ ``_mpn``. + pattern (str): + The item's pattern (for example, polka dots). + + This field is a member of `oneof`_ ``_pattern``. + price (google.shopping.type.types.Price): + Price of the item. + installment (google.shopping.merchant_products_v1beta.types.Installment): + Number and amount of installments to pay for + an item. + subscription_cost (google.shopping.merchant_products_v1beta.types.SubscriptionCost): + Number of periods (months or years) and + amount of payment per period for an item with an + associated subscription contract. + loyalty_points (google.shopping.merchant_products_v1beta.types.LoyaltyPoints): + Loyalty points that users receive after + purchasing the item. Japan only. + loyalty_programs (MutableSequence[google.shopping.merchant_products_v1beta.types.LoyaltyProgram]): + A list of loyalty program information that is + used to surface loyalty benefits (for example, + better pricing, points, etc) to the user of this + item. + product_types (MutableSequence[str]): + Categories of the item (formatted as in `product data + specification `__). + sale_price (google.shopping.type.types.Price): + Advertised sale price of the item. + sale_price_effective_date (google.type.interval_pb2.Interval): + Date range during which the item is on sale (see `product + data + specification `__). + sell_on_google_quantity (int): + The quantity of the product that is available + for selling on Google. Supported only for online + products. + + This field is a member of `oneof`_ ``_sell_on_google_quantity``. + product_height (google.shopping.merchant_products_v1beta.types.ProductDimension): + The height of the product in the units + provided. The value must be between + 0 (exclusive) and 3000 (inclusive). + product_length (google.shopping.merchant_products_v1beta.types.ProductDimension): + The length of the product in the units + provided. The value must be between 0 + (exclusive) and 3000 (inclusive). + product_width (google.shopping.merchant_products_v1beta.types.ProductDimension): + The width of the product in the units + provided. The value must be between 0 + (exclusive) and 3000 (inclusive). + product_weight (google.shopping.merchant_products_v1beta.types.ProductWeight): + The weight of the product in the units + provided. The value must be between 0 + (exclusive) and 2000 (inclusive). + shipping (MutableSequence[google.shopping.merchant_products_v1beta.types.Shipping]): + Shipping rules. + free_shipping_threshold (MutableSequence[google.shopping.merchant_products_v1beta.types.FreeShippingThreshold]): + Conditions to be met for a product to have + free shipping. + shipping_weight (google.shopping.merchant_products_v1beta.types.ShippingWeight): + Weight of the item for shipping. + shipping_length (google.shopping.merchant_products_v1beta.types.ShippingDimension): + Length of the item for shipping. + shipping_width (google.shopping.merchant_products_v1beta.types.ShippingDimension): + Width of the item for shipping. + shipping_height (google.shopping.merchant_products_v1beta.types.ShippingDimension): + Height of the item for shipping. + max_handling_time (int): + Maximal product handling time (in business + days). + + This field is a member of `oneof`_ ``_max_handling_time``. + min_handling_time (int): + Minimal product handling time (in business + days). + + This field is a member of `oneof`_ ``_min_handling_time``. + shipping_label (str): + The shipping label of the product, used to + group product in account-level shipping rules. + + This field is a member of `oneof`_ ``_shipping_label``. + transit_time_label (str): + The transit time label of the product, used + to group product in account-level transit time + tables. + + This field is a member of `oneof`_ ``_transit_time_label``. + size (str): + Size of the item. Only one value is allowed. For variants + with different sizes, insert a separate product for each + size with the same ``itemGroupId`` value (see + [https://support.google.com/merchants/answer/6324492](size + definition)). + + This field is a member of `oneof`_ ``_size``. + size_system (str): + System in which the size is specified. + Recommended for apparel items. + + This field is a member of `oneof`_ ``_size_system``. + size_types (MutableSequence[str]): + The cut of the item. It can be used to represent combined + size types for apparel items. Maximum two of size types can + be provided (see + [https://support.google.com/merchants/answer/6324497](size + type)). + taxes (MutableSequence[google.shopping.merchant_products_v1beta.types.Tax]): + Tax information. + tax_category (str): + The tax category of the product, used to + configure detailed tax nexus in account-level + tax settings. + + This field is a member of `oneof`_ ``_tax_category``. + energy_efficiency_class (str): + The energy efficiency class as defined in EU + directive 2010/30/EU. + + This field is a member of `oneof`_ ``_energy_efficiency_class``. + min_energy_efficiency_class (str): + The energy efficiency class as defined in EU + directive 2010/30/EU. + + This field is a member of `oneof`_ ``_min_energy_efficiency_class``. + max_energy_efficiency_class (str): + The energy efficiency class as defined in EU + directive 2010/30/EU. + + This field is a member of `oneof`_ ``_max_energy_efficiency_class``. + unit_pricing_measure (google.shopping.merchant_products_v1beta.types.UnitPricingMeasure): + The measure and dimension of an item. + unit_pricing_base_measure (google.shopping.merchant_products_v1beta.types.UnitPricingBaseMeasure): + The preference of the denominator of the unit + price. + multipack (int): + The number of identical products in a + merchant-defined multipack. + + This field is a member of `oneof`_ ``_multipack``. + ads_grouping (str): + Used to group items in an arbitrary way. Only + for CPA%, discouraged otherwise. + + This field is a member of `oneof`_ ``_ads_grouping``. + ads_labels (MutableSequence[str]): + Similar to ads_grouping, but only works on CPC. + ads_redirect (str): + Allows advertisers to override the item URL + when the product is shown within the context of + Product ads. + + This field is a member of `oneof`_ ``_ads_redirect``. + cost_of_goods_sold (google.shopping.type.types.Price): + Cost of goods sold. Used for gross profit + reporting. + product_details (MutableSequence[google.shopping.merchant_products_v1beta.types.ProductDetail]): + Technical specification or additional product + details. + product_highlights (MutableSequence[str]): + Bullet points describing the most relevant + highlights of a product. + display_ads_id (str): + An identifier for an item for dynamic + remarketing campaigns. + + This field is a member of `oneof`_ ``_display_ads_id``. + display_ads_similar_ids (MutableSequence[str]): + Advertiser-specified recommendations. + display_ads_title (str): + Title of an item for dynamic remarketing + campaigns. + + This field is a member of `oneof`_ ``_display_ads_title``. + display_ads_link (str): + URL directly to your item's landing page for + dynamic remarketing campaigns. + + This field is a member of `oneof`_ ``_display_ads_link``. + display_ads_value (float): + Offer margin for dynamic remarketing + campaigns. + + This field is a member of `oneof`_ ``_display_ads_value``. + promotion_ids (MutableSequence[str]): + The unique ID of a promotion. + pickup_method (str): + The pick up option for the item. + + This field is a member of `oneof`_ ``_pickup_method``. + pickup_sla (str): + Item store pickup timeline. + + This field is a member of `oneof`_ ``_pickup_sla``. + link_template (str): + Link template for merchant hosted local + storefront. + + This field is a member of `oneof`_ ``_link_template``. + mobile_link_template (str): + Link template for merchant hosted local + storefront optimized for mobile devices. + + This field is a member of `oneof`_ ``_mobile_link_template``. + custom_label_0 (str): + Custom label 0 for custom grouping of items + in a Shopping campaign. + + This field is a member of `oneof`_ ``_custom_label_0``. + custom_label_1 (str): + Custom label 1 for custom grouping of items + in a Shopping campaign. + + This field is a member of `oneof`_ ``_custom_label_1``. + custom_label_2 (str): + Custom label 2 for custom grouping of items + in a Shopping campaign. + + This field is a member of `oneof`_ ``_custom_label_2``. + custom_label_3 (str): + Custom label 3 for custom grouping of items + in a Shopping campaign. + + This field is a member of `oneof`_ ``_custom_label_3``. + custom_label_4 (str): + Custom label 4 for custom grouping of items + in a Shopping campaign. + + This field is a member of `oneof`_ ``_custom_label_4``. + included_destinations (MutableSequence[str]): + The list of destinations to include for this target + (corresponds to checked check boxes in Merchant Center). + Default destinations are always included unless provided in + ``excludedDestinations``. + excluded_destinations (MutableSequence[str]): + The list of destinations to exclude for this + target (corresponds to unchecked check boxes in + Merchant Center). + shopping_ads_excluded_countries (MutableSequence[str]): + List of country codes (ISO 3166-1 alpha-2) to + exclude the offer from Shopping Ads destination. + Countries from this list are removed from + countries configured in data source settings. + external_seller_id (str): + Required for multi-seller accounts. Use this + attribute if you're a marketplace uploading + products for various sellers to your + multi-seller account. + + This field is a member of `oneof`_ ``_external_seller_id``. + pause (str): + Publication of this item will be temporarily + `paused `__. + + This field is a member of `oneof`_ ``_pause``. + lifestyle_image_links (MutableSequence[str]): + Additional URLs of lifestyle images of the item, used to + explicitly identify images that showcase your item in a + real-world context. See the `Help Center + article `__ + for more information. + cloud_export_additional_properties (MutableSequence[google.shopping.merchant_products_v1beta.types.CloudExportAdditionalProperties]): + Extra fields to export to the Cloud Retail + program. + virtual_model_link (str): + URL of the 3D image of the item. See the `Help Center + article `__ + for more information. + + This field is a member of `oneof`_ ``_virtual_model_link``. + certifications (MutableSequence[google.shopping.merchant_products_v1beta.types.Certification]): + Product Certifications, for example for energy efficiency + labeling of products recorded in the `EU + EPREL `__ database. + See the `Help + Center `__ + article for more information. + structured_title (google.shopping.merchant_products_v1beta.types.ProductStructuredTitle): + Structured title, for algorithmically + (AI)-generated titles. + + This field is a member of `oneof`_ ``_structured_title``. + structured_description (google.shopping.merchant_products_v1beta.types.ProductStructuredDescription): + Structured description, for algorithmically + (AI)-generated descriptions. + + This field is a member of `oneof`_ ``_structured_description``. + auto_pricing_min_price (google.shopping.type.types.Price): + A safeguard in the "Automated Discounts" + (https://support.google.com/merchants/answer/10295759) + and "Dynamic Promotions" + (https://support.google.com/merchants/answer/13949249) + projects, ensuring that discounts on merchants' + offers do not fall below this value, thereby + preserving the offer's value and profitability. + """ + + identifier_exists: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + is_bundle: bool = proto.Field( + proto.BOOL, + number=5, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + link: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + mobile_link: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + canonical_link: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + image_link: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + additional_image_links: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + expiration_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=16, + message=timestamp_pb2.Timestamp, + ) + disclosure_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=79, + message=timestamp_pb2.Timestamp, + ) + adult: bool = proto.Field( + proto.BOOL, + number=17, + optional=True, + ) + age_group: str = proto.Field( + proto.STRING, + number=18, + optional=True, + ) + availability: str = proto.Field( + proto.STRING, + number=19, + optional=True, + ) + availability_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=20, + message=timestamp_pb2.Timestamp, + ) + brand: str = proto.Field( + proto.STRING, + number=21, + optional=True, + ) + color: str = proto.Field( + proto.STRING, + number=22, + optional=True, + ) + condition: str = proto.Field( + proto.STRING, + number=23, + optional=True, + ) + gender: str = proto.Field( + proto.STRING, + number=24, + optional=True, + ) + google_product_category: str = proto.Field( + proto.STRING, + number=25, + optional=True, + ) + gtin: str = proto.Field( + proto.STRING, + number=26, + optional=True, + ) + item_group_id: str = proto.Field( + proto.STRING, + number=27, + optional=True, + ) + material: str = proto.Field( + proto.STRING, + number=28, + optional=True, + ) + mpn: str = proto.Field( + proto.STRING, + number=29, + optional=True, + ) + pattern: str = proto.Field( + proto.STRING, + number=30, + optional=True, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=31, + message=types.Price, + ) + installment: 'Installment' = proto.Field( + proto.MESSAGE, + number=32, + message='Installment', + ) + subscription_cost: 'SubscriptionCost' = proto.Field( + proto.MESSAGE, + number=33, + message='SubscriptionCost', + ) + loyalty_points: 'LoyaltyPoints' = proto.Field( + proto.MESSAGE, + number=34, + message='LoyaltyPoints', + ) + loyalty_programs: MutableSequence['LoyaltyProgram'] = proto.RepeatedField( + proto.MESSAGE, + number=136, + message='LoyaltyProgram', + ) + product_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=35, + ) + sale_price: types.Price = proto.Field( + proto.MESSAGE, + number=36, + message=types.Price, + ) + sale_price_effective_date: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=37, + message=interval_pb2.Interval, + ) + sell_on_google_quantity: int = proto.Field( + proto.INT64, + number=38, + optional=True, + ) + product_height: 'ProductDimension' = proto.Field( + proto.MESSAGE, + number=119, + message='ProductDimension', + ) + product_length: 'ProductDimension' = proto.Field( + proto.MESSAGE, + number=120, + message='ProductDimension', + ) + product_width: 'ProductDimension' = proto.Field( + proto.MESSAGE, + number=121, + message='ProductDimension', + ) + product_weight: 'ProductWeight' = proto.Field( + proto.MESSAGE, + number=122, + message='ProductWeight', + ) + shipping: MutableSequence['Shipping'] = proto.RepeatedField( + proto.MESSAGE, + number=39, + message='Shipping', + ) + free_shipping_threshold: MutableSequence['FreeShippingThreshold'] = proto.RepeatedField( + proto.MESSAGE, + number=135, + message='FreeShippingThreshold', + ) + shipping_weight: 'ShippingWeight' = proto.Field( + proto.MESSAGE, + number=40, + message='ShippingWeight', + ) + shipping_length: 'ShippingDimension' = proto.Field( + proto.MESSAGE, + number=41, + message='ShippingDimension', + ) + shipping_width: 'ShippingDimension' = proto.Field( + proto.MESSAGE, + number=42, + message='ShippingDimension', + ) + shipping_height: 'ShippingDimension' = proto.Field( + proto.MESSAGE, + number=43, + message='ShippingDimension', + ) + max_handling_time: int = proto.Field( + proto.INT64, + number=44, + optional=True, + ) + min_handling_time: int = proto.Field( + proto.INT64, + number=45, + optional=True, + ) + shipping_label: str = proto.Field( + proto.STRING, + number=46, + optional=True, + ) + transit_time_label: str = proto.Field( + proto.STRING, + number=47, + optional=True, + ) + size: str = proto.Field( + proto.STRING, + number=48, + optional=True, + ) + size_system: str = proto.Field( + proto.STRING, + number=49, + optional=True, + ) + size_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=50, + ) + taxes: MutableSequence['Tax'] = proto.RepeatedField( + proto.MESSAGE, + number=51, + message='Tax', + ) + tax_category: str = proto.Field( + proto.STRING, + number=52, + optional=True, + ) + energy_efficiency_class: str = proto.Field( + proto.STRING, + number=53, + optional=True, + ) + min_energy_efficiency_class: str = proto.Field( + proto.STRING, + number=54, + optional=True, + ) + max_energy_efficiency_class: str = proto.Field( + proto.STRING, + number=55, + optional=True, + ) + unit_pricing_measure: 'UnitPricingMeasure' = proto.Field( + proto.MESSAGE, + number=56, + message='UnitPricingMeasure', + ) + unit_pricing_base_measure: 'UnitPricingBaseMeasure' = proto.Field( + proto.MESSAGE, + number=57, + message='UnitPricingBaseMeasure', + ) + multipack: int = proto.Field( + proto.INT64, + number=58, + optional=True, + ) + ads_grouping: str = proto.Field( + proto.STRING, + number=59, + optional=True, + ) + ads_labels: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=60, + ) + ads_redirect: str = proto.Field( + proto.STRING, + number=61, + optional=True, + ) + cost_of_goods_sold: types.Price = proto.Field( + proto.MESSAGE, + number=62, + message=types.Price, + ) + product_details: MutableSequence['ProductDetail'] = proto.RepeatedField( + proto.MESSAGE, + number=63, + message='ProductDetail', + ) + product_highlights: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=64, + ) + display_ads_id: str = proto.Field( + proto.STRING, + number=65, + optional=True, + ) + display_ads_similar_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=66, + ) + display_ads_title: str = proto.Field( + proto.STRING, + number=67, + optional=True, + ) + display_ads_link: str = proto.Field( + proto.STRING, + number=68, + optional=True, + ) + display_ads_value: float = proto.Field( + proto.DOUBLE, + number=69, + optional=True, + ) + promotion_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=70, + ) + pickup_method: str = proto.Field( + proto.STRING, + number=80, + optional=True, + ) + pickup_sla: str = proto.Field( + proto.STRING, + number=81, + optional=True, + ) + link_template: str = proto.Field( + proto.STRING, + number=82, + optional=True, + ) + mobile_link_template: str = proto.Field( + proto.STRING, + number=83, + optional=True, + ) + custom_label_0: str = proto.Field( + proto.STRING, + number=71, + optional=True, + ) + custom_label_1: str = proto.Field( + proto.STRING, + number=72, + optional=True, + ) + custom_label_2: str = proto.Field( + proto.STRING, + number=73, + optional=True, + ) + custom_label_3: str = proto.Field( + proto.STRING, + number=74, + optional=True, + ) + custom_label_4: str = proto.Field( + proto.STRING, + number=75, + optional=True, + ) + included_destinations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=76, + ) + excluded_destinations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=77, + ) + shopping_ads_excluded_countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=78, + ) + external_seller_id: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + pause: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + lifestyle_image_links: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=14, + ) + cloud_export_additional_properties: MutableSequence['CloudExportAdditionalProperties'] = proto.RepeatedField( + proto.MESSAGE, + number=84, + message='CloudExportAdditionalProperties', + ) + virtual_model_link: str = proto.Field( + proto.STRING, + number=130, + optional=True, + ) + certifications: MutableSequence['Certification'] = proto.RepeatedField( + proto.MESSAGE, + number=123, + message='Certification', + ) + structured_title: 'ProductStructuredTitle' = proto.Field( + proto.MESSAGE, + number=132, + optional=True, + message='ProductStructuredTitle', + ) + structured_description: 'ProductStructuredDescription' = proto.Field( + proto.MESSAGE, + number=133, + optional=True, + message='ProductStructuredDescription', + ) + auto_pricing_min_price: types.Price = proto.Field( + proto.MESSAGE, + number=124, + message=types.Price, + ) + + +class Tax(proto.Message): + r"""The Tax of the product. + + Attributes: + rate (float): + The percentage of tax rate that applies to + the item price. + country (str): + The country within which the item is taxed, specified as a + `CLDR territory + code `__. + region (str): + The geographic region to which the tax rate + applies. + tax_ship (bool): + Set to true if tax is charged on shipping. + location_id (int): + The numeric ID of a location that the tax rate applies to as + defined in the `AdWords + API `__. + postal_code (str): + The postal code range that the tax rate applies to, + represented by a ZIP code, a ZIP code prefix using \* + wildcard, a range between two ZIP codes or two ZIP code + prefixes of equal length. Examples: 94114, 94*, 94002-95460, + 94*-95*. + """ + + rate: float = proto.Field( + proto.DOUBLE, + number=1, + ) + country: str = proto.Field( + proto.STRING, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=3, + ) + tax_ship: bool = proto.Field( + proto.BOOL, + number=4, + ) + location_id: int = proto.Field( + proto.INT64, + number=5, + ) + postal_code: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ShippingWeight(proto.Message): + r"""The ShippingWeight of the product. + + Attributes: + value (float): + The weight of the product used to calculate + the shipping cost of the item. + unit (str): + The unit of value. + """ + + value: float = proto.Field( + proto.DOUBLE, + number=1, + ) + unit: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ShippingDimension(proto.Message): + r"""The ShippingDimension of the product. + + Attributes: + value (float): + The dimension of the product used to + calculate the shipping cost of the item. + unit (str): + The unit of value. + """ + + value: float = proto.Field( + proto.DOUBLE, + number=1, + ) + unit: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UnitPricingBaseMeasure(proto.Message): + r"""The UnitPricingBaseMeasure of the product. + + Attributes: + value (int): + The denominator of the unit price. + unit (str): + The unit of the denominator. + """ + + value: int = proto.Field( + proto.INT64, + number=1, + ) + unit: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UnitPricingMeasure(proto.Message): + r"""The UnitPricingMeasure of the product. + + Attributes: + value (float): + The measure of an item. + unit (str): + The unit of the measure. + """ + + value: float = proto.Field( + proto.DOUBLE, + number=1, + ) + unit: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SubscriptionCost(proto.Message): + r"""The SubscriptionCost of the product. + + Attributes: + period (google.shopping.merchant_products_v1beta.types.SubscriptionPeriod): + The type of subscription period. Supported values are: + + - "``month``" + - "``year``". + period_length (int): + The number of subscription periods the buyer + has to pay. + amount (google.shopping.type.types.Price): + The amount the buyer has to pay per + subscription period. + """ + + period: 'SubscriptionPeriod' = proto.Field( + proto.ENUM, + number=1, + enum='SubscriptionPeriod', + ) + period_length: int = proto.Field( + proto.INT64, + number=2, + ) + amount: types.Price = proto.Field( + proto.MESSAGE, + number=3, + message=types.Price, + ) + + +class Installment(proto.Message): + r"""A message that represents installment. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + months (int): + The number of installments the buyer has to + pay. + amount (google.shopping.type.types.Price): + The amount the buyer has to pay per month. + downpayment (google.shopping.type.types.Price): + The up-front down payment amount the buyer + has to pay. + + This field is a member of `oneof`_ ``_downpayment``. + credit_type (str): + Type of installment payments. Supported values are: + + - "``finance``" + - "``lease``". + + This field is a member of `oneof`_ ``_credit_type``. + """ + + months: int = proto.Field( + proto.INT64, + number=1, + ) + amount: types.Price = proto.Field( + proto.MESSAGE, + number=2, + message=types.Price, + ) + downpayment: types.Price = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=types.Price, + ) + credit_type: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + + +class LoyaltyPoints(proto.Message): + r"""A message that represents loyalty points. + + Attributes: + name (str): + Name of loyalty points program. It is + recommended to limit the name to 12 full-width + characters or 24 Roman characters. + points_value (int): + The retailer's loyalty points in absolute + value. + ratio (float): + The ratio of a point when converted to + currency. Google assumes currency based on + Merchant Center settings. If ratio is left out, + it defaults to 1.0. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + points_value: int = proto.Field( + proto.INT64, + number=2, + ) + ratio: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + +class LoyaltyProgram(proto.Message): + r"""A message that represents loyalty program. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + program_label (str): + The label of the loyalty program. This is an + internal label that uniquely identifies the + relationship between a merchant entity and a + loyalty program entity. The label must be + provided so that the system can associate the + assets below (for example, price and points) + with a merchant. The corresponding program must + be linked to the merchant account. + + This field is a member of `oneof`_ ``_program_label``. + tier_label (str): + The label of the tier within the loyalty + program. Must match one of the labels within the + program. + + This field is a member of `oneof`_ ``_tier_label``. + price (google.shopping.type.types.Price): + The price for members of the given tier, that + is, the instant discount price. Must be smaller + or equal to the regular price. + + This field is a member of `oneof`_ ``_price``. + cashback_for_future_use (google.shopping.type.types.Price): + The cashback that can be used for future + purchases. + + This field is a member of `oneof`_ ``_cashback_for_future_use``. + loyalty_points (int): + The amount of loyalty points earned on a + purchase. + + This field is a member of `oneof`_ ``_loyalty_points``. + """ + + program_label: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + tier_label: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=types.Price, + ) + cashback_for_future_use: types.Price = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message=types.Price, + ) + loyalty_points: int = proto.Field( + proto.INT64, + number=5, + optional=True, + ) + + +class Shipping(proto.Message): + r"""The Shipping of the product. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + price (google.shopping.type.types.Price): + Fixed shipping price, represented as a + number. + country (str): + The `CLDR territory + code `__ + of the country to which an item will ship. + region (str): + The geographic region to which a shipping rate applies. See + `region `__ + for more information. + service (str): + A free-form description of the service class + or delivery speed. + location_id (int): + The numeric ID of a location that the shipping rate applies + to as defined in the `AdWords + API `__. + location_group_name (str): + The location where the shipping is + applicable, represented by a location group + name. + postal_code (str): + The postal code range that the shipping rate applies to, + represented by a postal code, a postal code prefix followed + by a \* wildcard, a range between two postal codes or two + postal code prefixes of equal length. + min_handling_time (int): + Minimum handling time (inclusive) between when the order is + received and shipped in business days. 0 means that the + order is shipped on the same day as it is received if it + happens before the cut-off time. + [minHandlingTime][google.shopping.content.bundles.Products.Shipping.min_handling_time] + can only be present together with + [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time]; + but it is not required if + [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time] + is present. + + This field is a member of `oneof`_ ``_min_handling_time``. + max_handling_time (int): + Maximum handling time (inclusive) between when the order is + received and shipped in business days. 0 means that the + order is shipped on the same day as it is received if it + happens before the cut-off time. Both + [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time] + and + [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time] + are required if providing shipping speeds. + [minHandlingTime][google.shopping.content.bundles.Products.Shipping.min_handling_time] + is optional if + [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time] + is present. + + This field is a member of `oneof`_ ``_max_handling_time``. + min_transit_time (int): + Minimum transit time (inclusive) between when the order has + shipped and when it is delivered in business days. 0 means + that the order is delivered on the same day as it ships. + [minTransitTime][google.shopping.content.bundles.Products.Shipping.min_transit_time] + can only be present together with + [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time]; + but it is not required if + [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time] + is present. + + This field is a member of `oneof`_ ``_min_transit_time``. + max_transit_time (int): + Maximum transit time (inclusive) between when the order has + shipped and when it is delivered in business days. 0 means + that the order is delivered on the same day as it ships. + Both + [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time] + and + [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time] + are required if providing shipping speeds. + [minTransitTime][google.shopping.content.bundles.Products.Shipping.min_transit_time] + is optional if + [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time] + is present. + + This field is a member of `oneof`_ ``_max_transit_time``. + """ + + price: types.Price = proto.Field( + proto.MESSAGE, + number=1, + message=types.Price, + ) + country: str = proto.Field( + proto.STRING, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=3, + ) + service: str = proto.Field( + proto.STRING, + number=4, + ) + location_id: int = proto.Field( + proto.INT64, + number=5, + ) + location_group_name: str = proto.Field( + proto.STRING, + number=6, + ) + postal_code: str = proto.Field( + proto.STRING, + number=7, + ) + min_handling_time: int = proto.Field( + proto.INT64, + number=8, + optional=True, + ) + max_handling_time: int = proto.Field( + proto.INT64, + number=9, + optional=True, + ) + min_transit_time: int = proto.Field( + proto.INT64, + number=10, + optional=True, + ) + max_transit_time: int = proto.Field( + proto.INT64, + number=11, + optional=True, + ) + + +class FreeShippingThreshold(proto.Message): + r"""Conditions to be met for a product to have free shipping. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + country (str): + The `CLDR territory + code `__ + of the country to which an item will ship. + + This field is a member of `oneof`_ ``_country``. + price_threshold (google.shopping.type.types.Price): + The minimum product price for the shipping + cost to become free. Represented as a number. + + This field is a member of `oneof`_ ``_price_threshold``. + """ + + country: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + price_threshold: types.Price = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=types.Price, + ) + + +class ProductDetail(proto.Message): + r"""The product details. + + Attributes: + section_name (str): + The section header used to group a set of + product details. + attribute_name (str): + The name of the product detail. + attribute_value (str): + The value of the product detail. + """ + + section_name: str = proto.Field( + proto.STRING, + number=1, + ) + attribute_name: str = proto.Field( + proto.STRING, + number=2, + ) + attribute_value: str = proto.Field( + proto.STRING, + number=3, + ) + + +class Certification(proto.Message): + r"""Product + `certification `__, + initially introduced for EU energy efficiency labeling compliance + using the EU EPREL database. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + certification_authority (str): + The certification authority, for example + "European_Commission". Maximum length is 2000 characters. + + This field is a member of `oneof`_ ``_certification_authority``. + certification_name (str): + The name of the certification, for example + "EPREL". Maximum length is 2000 characters. + + This field is a member of `oneof`_ ``_certification_name``. + certification_code (str): + The certification code. + Maximum length is 2000 characters. + + This field is a member of `oneof`_ ``_certification_code``. + certification_value (str): + The certification value (also known as class, + level or grade), for example "A+", "C", "gold". + Maximum length is 2000 characters. + + This field is a member of `oneof`_ ``_certification_value``. + """ + + certification_authority: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + certification_name: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + certification_code: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + certification_value: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + + +class ProductStructuredTitle(proto.Message): + r"""Structured title, for algorithmically (AI)-generated titles. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + digital_source_type (str): + The digital source type, for example + "trained_algorithmic_media". Following + `IPTC `__. + Maximum length is 40 characters. + + This field is a member of `oneof`_ ``_digital_source_type``. + content (str): + The title text + Maximum length is 150 characters + + This field is a member of `oneof`_ ``_content``. + """ + + digital_source_type: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + content: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + +class ProductStructuredDescription(proto.Message): + r"""Structured description, for algorithmically (AI)-generated + descriptions. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + digital_source_type (str): + The digital source type, for example + "trained_algorithmic_media". Following + `IPTC `__. + Maximum length is 40 characters. + + This field is a member of `oneof`_ ``_digital_source_type``. + content (str): + The description text + Maximum length is 5000 characters + + This field is a member of `oneof`_ ``_content``. + """ + + digital_source_type: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + content: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + +class ProductDimension(proto.Message): + r"""The dimension of the product. + + Attributes: + value (float): + Required. The dimension value represented as + a number. The value can have a maximum precision + of four decimal places. + unit (str): + Required. The dimension units. Acceptable values are: + + - "``in``" + - "``cm``". + """ + + value: float = proto.Field( + proto.DOUBLE, + number=1, + ) + unit: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ProductWeight(proto.Message): + r"""The weight of the product. + + Attributes: + value (float): + Required. The weight represented as a number. + The weight can have a maximum precision of four + decimal places. + unit (str): + Required. The weight unit. Acceptable values are: + + - "``g``" + - "``kg``" + - "``oz``" + - "``lb``". + """ + + value: float = proto.Field( + proto.DOUBLE, + number=1, + ) + unit: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ProductStatus(proto.Message): + r"""The status of a product, data validation issues, that is, + information about a product computed asynchronously. + + Attributes: + destination_statuses (MutableSequence[google.shopping.merchant_products_v1beta.types.ProductStatus.DestinationStatus]): + The intended destinations for the product. + item_level_issues (MutableSequence[google.shopping.merchant_products_v1beta.types.ProductStatus.ItemLevelIssue]): + A list of all issues associated with the + product. + creation_date (google.protobuf.timestamp_pb2.Timestamp): + Date on which the item has been created, in `ISO + 8601 `__ format. + last_update_date (google.protobuf.timestamp_pb2.Timestamp): + Date on which the item has been last updated, in `ISO + 8601 `__ format. + google_expiration_date (google.protobuf.timestamp_pb2.Timestamp): + Date on which the item expires, in `ISO + 8601 `__ format. + """ + + class DestinationStatus(proto.Message): + r"""The destination status of the product status. + + Attributes: + reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): + The name of the reporting context. + approved_countries (MutableSequence[str]): + List of country codes (ISO 3166-1 alpha-2) + where the offer is approved. + pending_countries (MutableSequence[str]): + List of country codes (ISO 3166-1 alpha-2) + where the offer is pending approval. + disapproved_countries (MutableSequence[str]): + List of country codes (ISO 3166-1 alpha-2) + where the offer is disapproved. + """ + + reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( + proto.ENUM, + number=1, + enum=types.ReportingContext.ReportingContextEnum, + ) + approved_countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + pending_countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + disapproved_countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + class ItemLevelIssue(proto.Message): + r"""The ItemLevelIssue of the product status. + + Attributes: + code (str): + The error code of the issue. + severity (google.shopping.merchant_products_v1beta.types.ProductStatus.ItemLevelIssue.Severity): + How this issue affects serving of the offer. + resolution (str): + Whether the issue can be resolved by the + merchant. + attribute (str): + The attribute's name, if the issue is caused + by a single attribute. + reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): + The reporting context the issue applies to. + description (str): + A short issue description in English. + detail (str): + A detailed issue description in English. + documentation (str): + The URL of a web page to help with resolving + this issue. + applicable_countries (MutableSequence[str]): + List of country codes (ISO 3166-1 alpha-2) + where issue applies to the offer. + """ + class Severity(proto.Enum): + r"""How the issue affects the serving of the product. + + Values: + SEVERITY_UNSPECIFIED (0): + Not specified. + NOT_IMPACTED (1): + This issue represents a warning and does not + have a direct affect on the product. + DEMOTED (2): + The product is demoted and most likely have + limited performance in search results + DISAPPROVED (3): + Issue disapproves the product. + """ + SEVERITY_UNSPECIFIED = 0 + NOT_IMPACTED = 1 + DEMOTED = 2 + DISAPPROVED = 3 + + code: str = proto.Field( + proto.STRING, + number=1, + ) + severity: 'ProductStatus.ItemLevelIssue.Severity' = proto.Field( + proto.ENUM, + number=2, + enum='ProductStatus.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=3, + message=DestinationStatus, + ) + item_level_issues: MutableSequence[ItemLevelIssue] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=ItemLevelIssue, + ) + creation_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + last_update_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + google_expiration_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + +class CloudExportAdditionalProperties(proto.Message): + r"""Product property for the Cloud Retail API. + For example, properties for a TV product could be + "Screen-Resolution" or "Screen-Size". + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + property_name (str): + Name of the given property. For example, + "Screen-Resolution" for a TV product. Maximum + string size is 256 characters. + + This field is a member of `oneof`_ ``_property_name``. + text_value (MutableSequence[str]): + Text value of the given property. For + example, "8K(UHD)" could be a text value for a + TV product. Maximum repeatedness of this value + is 400. Values are stored in an arbitrary but + consistent order. Maximum string size is 256 + characters. + bool_value (bool): + Boolean value of the given property. For + example for a TV product, "True" or "False" if + the screen is UHD. + + This field is a member of `oneof`_ ``_bool_value``. + int_value (MutableSequence[int]): + Integer values of the given property. For + example, 1080 for a TV product's Screen + Resolution. Maximum repeatedness of this value + is 400. Values are stored in an arbitrary but + consistent order. + float_value (MutableSequence[float]): + Float values of the given property. For + example for a TV product 1.2345. Maximum + repeatedness of this value is 400. Values are + stored in an arbitrary but consistent order. + min_value (float): + Minimum float value of the given property. + For example for a TV product 1.00. + + This field is a member of `oneof`_ ``_min_value``. + max_value (float): + Maximum float value of the given property. + For example for a TV product 100.00. + + This field is a member of `oneof`_ ``_max_value``. + unit_code (str): + Unit of the given property. For example, + "Pixels" for a TV product. Maximum string size + is 256B. + + This field is a member of `oneof`_ ``_unit_code``. + """ + + property_name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + text_value: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + int_value: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=4, + ) + float_value: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=5, + ) + min_value: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + max_value: float = proto.Field( + proto.FLOAT, + number=7, + optional=True, + ) + unit_code: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-products/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/noxfile.py new file mode 100644 index 000000000000..1379acce6dcc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products' + +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_products_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_products_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-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py new file mode 100644 index 000000000000..6674700d5aad --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_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 DeleteProductInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-products + + +# [START merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_products_v1beta + + +async def sample_delete_product_input(): + # Create a client + client = merchant_products_v1beta.ProductInputsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.DeleteProductInputRequest( + name="name_value", + data_source="data_source_value", + ) + + # Make the request + await client.delete_product_input(request=request) + + +# [END merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_async] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py new file mode 100644 index 000000000000..9124f5eb48f6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_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 DeleteProductInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-products + + +# [START merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_products_v1beta + + +def sample_delete_product_input(): + # Create a client + client = merchant_products_v1beta.ProductInputsServiceClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.DeleteProductInputRequest( + name="name_value", + data_source="data_source_value", + ) + + # Make the request + client.delete_product_input(request=request) + + +# [END merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_sync] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_async.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_async.py new file mode 100644 index 000000000000..f42f63bd9437 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_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 InsertProductInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-products + + +# [START merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_products_v1beta + + +async def sample_insert_product_input(): + # Create a client + client = merchant_products_v1beta.ProductInputsServiceAsyncClient() + + # Initialize request argument(s) + product_input = merchant_products_v1beta.ProductInput() + product_input.channel = "LOCAL" + product_input.offer_id = "offer_id_value" + product_input.content_language = "content_language_value" + product_input.feed_label = "feed_label_value" + + request = merchant_products_v1beta.InsertProductInputRequest( + parent="parent_value", + product_input=product_input, + data_source="data_source_value", + ) + + # Make the request + response = await client.insert_product_input(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_async] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_sync.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_sync.py new file mode 100644 index 000000000000..2a339ed09b3c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_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 InsertProductInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-products + + +# [START merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_products_v1beta + + +def sample_insert_product_input(): + # Create a client + client = merchant_products_v1beta.ProductInputsServiceClient() + + # Initialize request argument(s) + product_input = merchant_products_v1beta.ProductInput() + product_input.channel = "LOCAL" + product_input.offer_id = "offer_id_value" + product_input.content_language = "content_language_value" + product_input.feed_label = "feed_label_value" + + request = merchant_products_v1beta.InsertProductInputRequest( + parent="parent_value", + product_input=product_input, + data_source="data_source_value", + ) + + # Make the request + response = client.insert_product_input(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_sync] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_async.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_async.py new file mode 100644 index 000000000000..6f176867a7f1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_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 GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-products + + +# [START merchantapi_v1beta_generated_ProductsService_GetProduct_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_products_v1beta + + +async def sample_get_product(): + # Create a client + client = merchant_products_v1beta.ProductsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = await client.get_product(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProductsService_GetProduct_async] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_sync.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_sync.py new file mode 100644 index 000000000000..9cbb8a0c4bba --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_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 GetProduct +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-products + + +# [START merchantapi_v1beta_generated_ProductsService_GetProduct_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_products_v1beta + + +def sample_get_product(): + # Create a client + client = merchant_products_v1beta.ProductsServiceClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.GetProductRequest( + name="name_value", + ) + + # Make the request + response = client.get_product(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProductsService_GetProduct_sync] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_async.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_async.py new file mode 100644 index 000000000000..2c618af2956b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_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 ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-products + + +# [START merchantapi_v1beta_generated_ProductsService_ListProducts_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_products_v1beta + + +async def sample_list_products(): + # Create a client + client = merchant_products_v1beta.ProductsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_ProductsService_ListProducts_async] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_sync.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_sync.py new file mode 100644 index 000000000000..b76624178a59 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_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 ListProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-products + + +# [START merchantapi_v1beta_generated_ProductsService_ListProducts_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_products_v1beta + + +def sample_list_products(): + # Create a client + client = merchant_products_v1beta.ProductsServiceClient() + + # Initialize request argument(s) + request = merchant_products_v1beta.ListProductsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_ProductsService_ListProducts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.products.v1beta.json b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.products.v1beta.json new file mode 100644 index 000000000000..10f94f8cadc7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.products.v1beta.json @@ -0,0 +1,645 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.products.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-products", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceAsyncClient", + "shortName": "ProductInputsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceAsyncClient.delete_product_input", + "method": { + "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService.DeleteProductInput", + "service": { + "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService", + "shortName": "ProductInputsService" + }, + "shortName": "DeleteProductInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_products_v1beta.types.DeleteProductInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_product_input" + }, + "description": "Sample for DeleteProductInput", + "file": "merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceClient", + "shortName": "ProductInputsServiceClient" + }, + "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceClient.delete_product_input", + "method": { + "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService.DeleteProductInput", + "service": { + "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService", + "shortName": "ProductInputsService" + }, + "shortName": "DeleteProductInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_products_v1beta.types.DeleteProductInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_product_input" + }, + "description": "Sample for DeleteProductInput", + "file": "merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceAsyncClient", + "shortName": "ProductInputsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceAsyncClient.insert_product_input", + "method": { + "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService.InsertProductInput", + "service": { + "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService", + "shortName": "ProductInputsService" + }, + "shortName": "InsertProductInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_products_v1beta.types.InsertProductInputRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.shopping.merchant_products_v1beta.types.ProductInput", + "shortName": "insert_product_input" + }, + "description": "Sample for InsertProductInput", + "file": "merchantapi_v1beta_generated_product_inputs_service_insert_product_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_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_product_inputs_service_insert_product_input_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceClient", + "shortName": "ProductInputsServiceClient" + }, + "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceClient.insert_product_input", + "method": { + "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService.InsertProductInput", + "service": { + "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService", + "shortName": "ProductInputsService" + }, + "shortName": "InsertProductInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_products_v1beta.types.InsertProductInputRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.shopping.merchant_products_v1beta.types.ProductInput", + "shortName": "insert_product_input" + }, + "description": "Sample for InsertProductInput", + "file": "merchantapi_v1beta_generated_product_inputs_service_insert_product_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_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_product_inputs_service_insert_product_input_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceAsyncClient", + "shortName": "ProductsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceAsyncClient.get_product", + "method": { + "fullName": "google.shopping.merchant.products.v1beta.ProductsService.GetProduct", + "service": { + "fullName": "google.shopping.merchant.products.v1beta.ProductsService", + "shortName": "ProductsService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_products_v1beta.types.GetProductRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.shopping.merchant_products_v1beta.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "merchantapi_v1beta_generated_products_service_get_product_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProductsService_GetProduct_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_products_service_get_product_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceClient", + "shortName": "ProductsServiceClient" + }, + "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceClient.get_product", + "method": { + "fullName": "google.shopping.merchant.products.v1beta.ProductsService.GetProduct", + "service": { + "fullName": "google.shopping.merchant.products.v1beta.ProductsService", + "shortName": "ProductsService" + }, + "shortName": "GetProduct" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_products_v1beta.types.GetProductRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.shopping.merchant_products_v1beta.types.Product", + "shortName": "get_product" + }, + "description": "Sample for GetProduct", + "file": "merchantapi_v1beta_generated_products_service_get_product_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProductsService_GetProduct_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_products_service_get_product_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceAsyncClient", + "shortName": "ProductsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceAsyncClient.list_products", + "method": { + "fullName": "google.shopping.merchant.products.v1beta.ProductsService.ListProducts", + "service": { + "fullName": "google.shopping.merchant.products.v1beta.ProductsService", + "shortName": "ProductsService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_products_v1beta.types.ListProductsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.shopping.merchant_products_v1beta.services.products_service.pagers.ListProductsAsyncPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "merchantapi_v1beta_generated_products_service_list_products_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProductsService_ListProducts_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_products_service_list_products_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceClient", + "shortName": "ProductsServiceClient" + }, + "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceClient.list_products", + "method": { + "fullName": "google.shopping.merchant.products.v1beta.ProductsService.ListProducts", + "service": { + "fullName": "google.shopping.merchant.products.v1beta.ProductsService", + "shortName": "ProductsService" + }, + "shortName": "ListProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_products_v1beta.types.ListProductsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.shopping.merchant_products_v1beta.services.products_service.pagers.ListProductsPager", + "shortName": "list_products" + }, + "description": "Sample for ListProducts", + "file": "merchantapi_v1beta_generated_products_service_list_products_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProductsService_ListProducts_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_products_service_list_products_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/scripts/fixup_merchant_products_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/scripts/fixup_merchant_products_v1beta_keywords.py new file mode 100644 index 000000000000..9ec72e193341 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/scripts/fixup_merchant_products_v1beta_keywords.py @@ -0,0 +1,179 @@ +#! /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_productsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'delete_product_input': ('name', 'data_source', ), + 'get_product': ('name', ), + 'insert_product_input': ('parent', 'product_input', 'data_source', ), + 'list_products': ('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_productsCallTransformer(), +): + """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_products 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-products/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/setup.py new file mode 100644 index 000000000000..2463758762c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products' + + +description = "Google Shopping Merchant Products API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_products/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-products" + +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-products/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..130a0c0f80ab --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/tests/unit/gapic/merchant_products_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_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-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_product_inputs_service.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_product_inputs_service.py new file mode 100644 index 000000000000..86ae41a6011d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_product_inputs_service.py @@ -0,0 +1,2788 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_products_v1beta.services.product_inputs_service import ProductInputsServiceAsyncClient +from google.shopping.merchant_products_v1beta.services.product_inputs_service import ProductInputsServiceClient +from google.shopping.merchant_products_v1beta.services.product_inputs_service import transports +from google.shopping.merchant_products_v1beta.types import productinputs +from google.shopping.merchant_products_v1beta.types import products_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 ProductInputsServiceClient._get_default_mtls_endpoint(None) is None + assert ProductInputsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductInputsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductInputsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductInputsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductInputsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ProductInputsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ProductInputsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ProductInputsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ProductInputsServiceClient._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 ProductInputsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ProductInputsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ProductInputsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ProductInputsServiceClient._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 ProductInputsServiceClient._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 ProductInputsServiceClient._get_client_cert_source(None, False) is None + assert ProductInputsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ProductInputsServiceClient._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 ProductInputsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ProductInputsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ProductInputsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceClient)) +@mock.patch.object(ProductInputsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ProductInputsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ProductInputsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ProductInputsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ProductInputsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ProductInputsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProductInputsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ProductInputsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProductInputsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProductInputsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ProductInputsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ProductInputsServiceClient._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 ProductInputsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ProductInputsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ProductInputsServiceClient._get_universe_domain(None, None) == ProductInputsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ProductInputsServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc"), + (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductInputsServiceClient, "grpc"), + (ProductInputsServiceAsyncClient, "grpc_asyncio"), + (ProductInputsServiceClient, "rest"), +]) +def test_product_inputs_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.ProductInputsServiceGrpcTransport, "grpc"), + (transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProductInputsServiceRestTransport, "rest"), +]) +def test_product_inputs_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", [ + (ProductInputsServiceClient, "grpc"), + (ProductInputsServiceAsyncClient, "grpc_asyncio"), + (ProductInputsServiceClient, "rest"), +]) +def test_product_inputs_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_product_inputs_service_client_get_transport_class(): + transport = ProductInputsServiceClient.get_transport_class() + available_transports = [ + transports.ProductInputsServiceGrpcTransport, + transports.ProductInputsServiceRestTransport, + ] + assert transport in available_transports + + transport = ProductInputsServiceClient.get_transport_class("grpc") + assert transport == transports.ProductInputsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc"), + (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest"), +]) +@mock.patch.object(ProductInputsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceClient)) +@mock.patch.object(ProductInputsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceAsyncClient)) +def test_product_inputs_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(ProductInputsServiceClient, '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(ProductInputsServiceClient, '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", [ + (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc", "true"), + (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc", "false"), + (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest", "true"), + (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ProductInputsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceClient)) +@mock.patch.object(ProductInputsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_inputs_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", [ + ProductInputsServiceClient, ProductInputsServiceAsyncClient +]) +@mock.patch.object(ProductInputsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductInputsServiceClient)) +@mock.patch.object(ProductInputsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductInputsServiceAsyncClient)) +def test_product_inputs_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", [ + ProductInputsServiceClient, ProductInputsServiceAsyncClient +]) +@mock.patch.object(ProductInputsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceClient)) +@mock.patch.object(ProductInputsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceAsyncClient)) +def test_product_inputs_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ProductInputsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ProductInputsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ProductInputsServiceClient._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", [ + (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc"), + (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest"), +]) +def test_product_inputs_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", [ + (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc", grpc_helpers), + (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest", None), +]) +def test_product_inputs_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_product_inputs_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_products_v1beta.services.product_inputs_service.transports.ProductInputsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductInputsServiceClient( + 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", [ + (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc", grpc_helpers), + (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_inputs_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", [ + productinputs.InsertProductInputRequest, + dict, +]) +def test_insert_product_input(request_type, transport: str = 'grpc'): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = productinputs.ProductInput( + name='name_value', + product='product_value', + channel=types.Channel.ChannelEnum.ONLINE, + offer_id='offer_id_value', + content_language='content_language_value', + feed_label='feed_label_value', + version_number=1518, + ) + response = client.insert_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = productinputs.InsertProductInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, productinputs.ProductInput) + assert response.name == 'name_value' + assert response.product == 'product_value' + assert response.channel == types.Channel.ChannelEnum.ONLINE + assert response.offer_id == 'offer_id_value' + assert response.content_language == 'content_language_value' + assert response.feed_label == 'feed_label_value' + assert response.version_number == 1518 + + +def test_insert_product_input_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = productinputs.InsertProductInputRequest( + 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_product_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_product_input(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == productinputs.InsertProductInputRequest( + parent='parent_value', + data_source='data_source_value', + ) + +def test_insert_product_input_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_product_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_product_input] = mock_rpc + request = {} + client.insert_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_product_input(request) + + # Establish that a new wrapper 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_product_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ProductInputsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_product_input in client._client._transport._wrapped_methods + + # 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_product_input] = mock_rpc + + request = {} + await client.insert_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_product_input(request) + + # Establish that a new wrapper 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_product_input_async(transport: str = 'grpc_asyncio', request_type=productinputs.InsertProductInputRequest): + client = ProductInputsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(productinputs.ProductInput( + name='name_value', + product='product_value', + channel=types.Channel.ChannelEnum.ONLINE, + offer_id='offer_id_value', + content_language='content_language_value', + feed_label='feed_label_value', + version_number=1518, + )) + response = await client.insert_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = productinputs.InsertProductInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, productinputs.ProductInput) + assert response.name == 'name_value' + assert response.product == 'product_value' + assert response.channel == types.Channel.ChannelEnum.ONLINE + assert response.offer_id == 'offer_id_value' + assert response.content_language == 'content_language_value' + assert response.feed_label == 'feed_label_value' + assert response.version_number == 1518 + + +@pytest.mark.asyncio +async def test_insert_product_input_async_from_dict(): + await test_insert_product_input_async(request_type=dict) + +def test_insert_product_input_field_headers(): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = productinputs.InsertProductInputRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_product_input), + '__call__') as call: + call.return_value = productinputs.ProductInput() + client.insert_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_input_field_headers_async(): + client = ProductInputsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = productinputs.InsertProductInputRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_product_input), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(productinputs.ProductInput()) + await client.insert_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + productinputs.DeleteProductInputRequest, + dict, +]) +def test_delete_product_input(request_type, transport: str = 'grpc'): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = productinputs.DeleteProductInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_input_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = productinputs.DeleteProductInputRequest( + name='name_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.delete_product_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_product_input(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == productinputs.DeleteProductInputRequest( + name='name_value', + data_source='data_source_value', + ) + +def test_delete_product_input_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_product_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_product_input] = mock_rpc + request = {} + client.delete_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_product_input(request) + + # Establish that a new wrapper 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_product_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ProductInputsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_product_input in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_product_input] = mock_rpc + + request = {} + await client.delete_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_product_input(request) + + # Establish that a new wrapper 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_product_input_async(transport: str = 'grpc_asyncio', request_type=productinputs.DeleteProductInputRequest): + client = ProductInputsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = productinputs.DeleteProductInputRequest() + 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_product_input_async_from_dict(): + await test_delete_product_input_async(request_type=dict) + +def test_delete_product_input_field_headers(): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = productinputs.DeleteProductInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product_input), + '__call__') as call: + call.return_value = None + client.delete_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_input_field_headers_async(): + client = ProductInputsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = productinputs.DeleteProductInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product_input), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_input_flattened(): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_product_input( + 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_product_input_flattened_error(): + client = ProductInputsServiceClient( + credentials=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_product_input( + productinputs.DeleteProductInputRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_product_input_flattened_async(): + client = ProductInputsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_product_input), + '__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_product_input( + 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_product_input_flattened_error_async(): + client = ProductInputsServiceAsyncClient( + credentials=async_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_product_input( + productinputs.DeleteProductInputRequest(), + name='name_value', + ) + + +def test_insert_product_input_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_product_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_product_input] = mock_rpc + + request = {} + client.insert_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_product_input(request) + + # Establish 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_product_input_rest_required_fields(request_type=productinputs.InsertProductInputRequest): + transport_class = transports.ProductInputsServiceRestTransport + + 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 + assert "dataSource" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_product_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "dataSource" in jsonified_request + assert jsonified_request["dataSource"] == request_init["data_source"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["dataSource"] = 'data_source_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_product_input._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("data_source", )) + 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 = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = productinputs.ProductInput() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = productinputs.ProductInput.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.insert_product_input(request) + + expected_params = [ + ( + "dataSource", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_product_input_rest_unset_required_fields(): + transport = transports.ProductInputsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_product_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(("dataSource", )) & set(("parent", "productInput", "dataSource", ))) + + +def test_delete_product_input_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_product_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_product_input] = mock_rpc + + request = {} + client.delete_product_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_product_input(request) + + # Establish 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_product_input_rest_required_fields(request_type=productinputs.DeleteProductInputRequest): + transport_class = transports.ProductInputsServiceRestTransport + + request_init = {} + request_init["name"] = "" + 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 + assert "dataSource" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "dataSource" in jsonified_request + assert jsonified_request["dataSource"] == request_init["data_source"] + + jsonified_request["name"] = 'name_value' + jsonified_request["dataSource"] = 'data_source_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_input._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("data_source", )) + jsonified_request.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 "dataSource" in jsonified_request + assert jsonified_request["dataSource"] == 'data_source_value' + + client = ProductInputsServiceClient( + 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 + + response = client.delete_product_input(request) + + expected_params = [ + ( + "dataSource", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_product_input_rest_unset_required_fields(): + transport = transports.ProductInputsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_product_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(("dataSource", )) & set(("name", "dataSource", ))) + + +def test_delete_product_input_rest_flattened(): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/productInputs/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 + + client.delete_product_input(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/products/v1beta/{name=accounts/*/productInputs/*}" % client.transport._host, args[1]) + + +def test_delete_product_input_rest_flattened_error(transport: str = 'rest'): + client = ProductInputsServiceClient( + credentials=ga_credentials.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_product_input( + productinputs.DeleteProductInputRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductInputsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductInputsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductInputsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductInputsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductInputsServiceClient( + 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 = ProductInputsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductInputsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductInputsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductInputsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductInputsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductInputsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductInputsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductInputsServiceGrpcTransport, + transports.ProductInputsServiceGrpcAsyncIOTransport, + transports.ProductInputsServiceRestTransport, +]) +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 = ProductInputsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProductInputsServiceClient( + 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_product_input_empty_call_grpc(): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_product_input), + '__call__') as call: + call.return_value = productinputs.ProductInput() + client.insert_product_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = productinputs.InsertProductInputRequest() + + assert args[0] == request_msg + + +# This 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_product_input_empty_call_grpc(): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_product_input), + '__call__') as call: + call.return_value = None + client.delete_product_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = productinputs.DeleteProductInputRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProductInputsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProductInputsServiceAsyncClient( + 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_product_input_empty_call_grpc_asyncio(): + client = ProductInputsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_product_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(productinputs.ProductInput( + name='name_value', + product='product_value', + channel=types.Channel.ChannelEnum.ONLINE, + offer_id='offer_id_value', + content_language='content_language_value', + feed_label='feed_label_value', + version_number=1518, + )) + await client.insert_product_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = productinputs.InsertProductInputRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_product_input_empty_call_grpc_asyncio(): + client = ProductInputsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_product_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = productinputs.DeleteProductInputRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProductInputsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_insert_product_input_rest_bad_request(request_type=productinputs.InsertProductInputRequest): + client = ProductInputsServiceClient( + 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 + client.insert_product_input(request) + + +@pytest.mark.parametrize("request_type", [ + productinputs.InsertProductInputRequest, + dict, +]) +def test_insert_product_input_rest_call_success(request_type): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["product_input"] = {'name': 'name_value', 'product': 'product_value', 'channel': 1, 'offer_id': 'offer_id_value', 'content_language': 'content_language_value', 'feed_label': 'feed_label_value', 'version_number': 1518, 'attributes': {'identifier_exists': True, 'is_bundle': True, 'title': 'title_value', 'description': 'description_value', 'link': 'link_value', 'mobile_link': 'mobile_link_value', 'canonical_link': 'canonical_link_value', 'image_link': 'image_link_value', 'additional_image_links': ['additional_image_links_value1', 'additional_image_links_value2'], 'expiration_date': {'seconds': 751, 'nanos': 543}, 'disclosure_date': {}, 'adult': True, 'age_group': 'age_group_value', 'availability': 'availability_value', 'availability_date': {}, 'brand': 'brand_value', 'color': 'color_value', 'condition': 'condition_value', 'gender': 'gender_value', 'google_product_category': 'google_product_category_value', 'gtin': 'gtin_value', 'item_group_id': 'item_group_id_value', 'material': 'material_value', 'mpn': 'mpn_value', 'pattern': 'pattern_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'installment': {'months': 665, 'amount': {}, 'downpayment': {}, 'credit_type': 'credit_type_value'}, 'subscription_cost': {'period': 1, 'period_length': 1380, 'amount': {}}, 'loyalty_points': {'name': 'name_value', 'points_value': 1305, 'ratio': 0.543}, 'loyalty_programs': [{'program_label': 'program_label_value', 'tier_label': 'tier_label_value', 'price': {}, 'cashback_for_future_use': {}, 'loyalty_points': 1546}], 'product_types': ['product_types_value1', 'product_types_value2'], 'sale_price': {}, 'sale_price_effective_date': {'start_time': {}, 'end_time': {}}, 'sell_on_google_quantity': 2470, 'product_height': {'value': 0.541, 'unit': 'unit_value'}, 'product_length': {}, 'product_width': {}, 'product_weight': {'value': 0.541, 'unit': 'unit_value'}, 'shipping': [{'price': {}, 'country': 'country_value', 'region': 'region_value', 'service': 'service_value', 'location_id': 1157, 'location_group_name': 'location_group_name_value', 'postal_code': 'postal_code_value', 'min_handling_time': 1782, 'max_handling_time': 1784, 'min_transit_time': 1718, 'max_transit_time': 1720}], 'free_shipping_threshold': [{'country': 'country_value', 'price_threshold': {}}], 'shipping_weight': {'value': 0.541, 'unit': 'unit_value'}, 'shipping_length': {'value': 0.541, 'unit': 'unit_value'}, 'shipping_width': {}, 'shipping_height': {}, 'max_handling_time': 1784, 'min_handling_time': 1782, 'shipping_label': 'shipping_label_value', 'transit_time_label': 'transit_time_label_value', 'size': 'size_value', 'size_system': 'size_system_value', 'size_types': ['size_types_value1', 'size_types_value2'], 'taxes': [{'rate': 0.428, 'country': 'country_value', 'region': 'region_value', 'tax_ship': True, 'location_id': 1157, 'postal_code': 'postal_code_value'}], 'tax_category': 'tax_category_value', 'energy_efficiency_class': 'energy_efficiency_class_value', 'min_energy_efficiency_class': 'min_energy_efficiency_class_value', 'max_energy_efficiency_class': 'max_energy_efficiency_class_value', 'unit_pricing_measure': {'value': 0.541, 'unit': 'unit_value'}, 'unit_pricing_base_measure': {'value': 541, 'unit': 'unit_value'}, 'multipack': 970, 'ads_grouping': 'ads_grouping_value', 'ads_labels': ['ads_labels_value1', 'ads_labels_value2'], 'ads_redirect': 'ads_redirect_value', 'cost_of_goods_sold': {}, 'product_details': [{'section_name': 'section_name_value', 'attribute_name': 'attribute_name_value', 'attribute_value': 'attribute_value_value'}], 'product_highlights': ['product_highlights_value1', 'product_highlights_value2'], 'display_ads_id': 'display_ads_id_value', 'display_ads_similar_ids': ['display_ads_similar_ids_value1', 'display_ads_similar_ids_value2'], 'display_ads_title': 'display_ads_title_value', 'display_ads_link': 'display_ads_link_value', 'display_ads_value': 0.1801, 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2'], 'pickup_method': 'pickup_method_value', 'pickup_sla': 'pickup_sla_value', 'link_template': 'link_template_value', 'mobile_link_template': 'mobile_link_template_value', 'custom_label_0': 'custom_label_0_value', 'custom_label_1': 'custom_label_1_value', 'custom_label_2': 'custom_label_2_value', 'custom_label_3': 'custom_label_3_value', 'custom_label_4': 'custom_label_4_value', 'included_destinations': ['included_destinations_value1', 'included_destinations_value2'], 'excluded_destinations': ['excluded_destinations_value1', 'excluded_destinations_value2'], 'shopping_ads_excluded_countries': ['shopping_ads_excluded_countries_value1', 'shopping_ads_excluded_countries_value2'], 'external_seller_id': 'external_seller_id_value', 'pause': 'pause_value', 'lifestyle_image_links': ['lifestyle_image_links_value1', 'lifestyle_image_links_value2'], 'cloud_export_additional_properties': [{'property_name': 'property_name_value', 'text_value': ['text_value_value1', 'text_value_value2'], 'bool_value': True, 'int_value': [968, 969], 'float_value': [0.11710000000000001, 0.11720000000000001], 'min_value': 0.96, 'max_value': 0.962, 'unit_code': 'unit_code_value'}], 'virtual_model_link': 'virtual_model_link_value', 'certifications': [{'certification_authority': 'certification_authority_value', 'certification_name': 'certification_name_value', 'certification_code': 'certification_code_value', 'certification_value': 'certification_value_value'}], 'structured_title': {'digital_source_type': 'digital_source_type_value', 'content': 'content_value'}, 'structured_description': {'digital_source_type': 'digital_source_type_value', 'content': 'content_value'}, 'auto_pricing_min_price': {}}, '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 = productinputs.InsertProductInputRequest.meta.fields["product_input"] + + 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["product_input"].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["product_input"][field])): + del request_init["product_input"][field][i][subfield] + else: + del request_init["product_input"][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 = productinputs.ProductInput( + name='name_value', + product='product_value', + channel=types.Channel.ChannelEnum.ONLINE, + offer_id='offer_id_value', + content_language='content_language_value', + feed_label='feed_label_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 = productinputs.ProductInput.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.insert_product_input(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, productinputs.ProductInput) + assert response.name == 'name_value' + assert response.product == 'product_value' + assert response.channel == types.Channel.ChannelEnum.ONLINE + assert response.offer_id == 'offer_id_value' + assert response.content_language == 'content_language_value' + assert response.feed_label == 'feed_label_value' + assert response.version_number == 1518 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_product_input_rest_interceptors(null_interceptor): + transport = transports.ProductInputsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProductInputsServiceRestInterceptor(), + ) + client = ProductInputsServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductInputsServiceRestInterceptor, "post_insert_product_input") as post, \ + mock.patch.object(transports.ProductInputsServiceRestInterceptor, "pre_insert_product_input") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = productinputs.InsertProductInputRequest.pb(productinputs.InsertProductInputRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = productinputs.ProductInput.to_json(productinputs.ProductInput()) + req.return_value.content = return_value + + request = productinputs.InsertProductInputRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = productinputs.ProductInput() + + client.insert_product_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_product_input_rest_bad_request(request_type=productinputs.DeleteProductInputRequest): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/productInputs/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 + client.delete_product_input(request) + + +@pytest.mark.parametrize("request_type", [ + productinputs.DeleteProductInputRequest, + dict, +]) +def test_delete_product_input_rest_call_success(request_type): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/productInputs/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 + response = client.delete_product_input(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_product_input_rest_interceptors(null_interceptor): + transport = transports.ProductInputsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProductInputsServiceRestInterceptor(), + ) + client = ProductInputsServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductInputsServiceRestInterceptor, "pre_delete_product_input") as pre: + pre.assert_not_called() + pb_message = productinputs.DeleteProductInputRequest.pb(productinputs.DeleteProductInputRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = productinputs.DeleteProductInputRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_product_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = ProductInputsServiceClient( + 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_product_input_empty_call_rest(): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_product_input), + '__call__') as call: + client.insert_product_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = productinputs.InsertProductInputRequest() + + assert args[0] == request_msg + + +# This 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_product_input_empty_call_rest(): + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_product_input), + '__call__') as call: + client.delete_product_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = productinputs.DeleteProductInputRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductInputsServiceGrpcTransport, + ) + +def test_product_inputs_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductInputsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_product_inputs_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_products_v1beta.services.product_inputs_service.transports.ProductInputsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductInputsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'insert_product_input', + 'delete_product_input', + ) + 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_product_inputs_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_products_v1beta.services.product_inputs_service.transports.ProductInputsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductInputsServiceTransport( + 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_product_inputs_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_products_v1beta.services.product_inputs_service.transports.ProductInputsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductInputsServiceTransport() + adc.assert_called_once() + + +def test_product_inputs_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) + ProductInputsServiceClient() + 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.ProductInputsServiceGrpcTransport, + transports.ProductInputsServiceGrpcAsyncIOTransport, + ], +) +def test_product_inputs_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.ProductInputsServiceGrpcTransport, + transports.ProductInputsServiceGrpcAsyncIOTransport, + transports.ProductInputsServiceRestTransport, + ], +) +def test_product_inputs_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.ProductInputsServiceGrpcTransport, grpc_helpers), + (transports.ProductInputsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_product_inputs_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.ProductInputsServiceGrpcTransport, transports.ProductInputsServiceGrpcAsyncIOTransport]) +def test_product_inputs_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_product_inputs_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.ProductInputsServiceRestTransport ( + 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_product_inputs_service_host_no_port(transport_name): + client = ProductInputsServiceClient( + 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_product_inputs_service_host_with_port(transport_name): + client = ProductInputsServiceClient( + 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_product_inputs_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ProductInputsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ProductInputsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.insert_product_input._session + session2 = client2.transport.insert_product_input._session + assert session1 != session2 + session1 = client1.transport.delete_product_input._session + session2 = client2.transport.delete_product_input._session + assert session1 != session2 +def test_product_inputs_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductInputsServiceGrpcTransport( + 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_product_inputs_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductInputsServiceGrpcAsyncIOTransport( + 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.ProductInputsServiceGrpcTransport, transports.ProductInputsServiceGrpcAsyncIOTransport]) +def test_product_inputs_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.ProductInputsServiceGrpcTransport, transports.ProductInputsServiceGrpcAsyncIOTransport]) +def test_product_inputs_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_product_path(): + account = "squid" + product = "clam" + expected = "accounts/{account}/products/{product}".format(account=account, product=product, ) + actual = ProductInputsServiceClient.product_path(account, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "account": "whelk", + "product": "octopus", + } + path = ProductInputsServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductInputsServiceClient.parse_product_path(path) + assert expected == actual + +def test_product_input_path(): + account = "oyster" + productinput = "nudibranch" + expected = "accounts/{account}/productInputs/{productinput}".format(account=account, productinput=productinput, ) + actual = ProductInputsServiceClient.product_input_path(account, productinput) + assert expected == actual + + +def test_parse_product_input_path(): + expected = { + "account": "cuttlefish", + "productinput": "mussel", + } + path = ProductInputsServiceClient.product_input_path(**expected) + + # Check that the path construction is reversible. + actual = ProductInputsServiceClient.parse_product_input_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductInputsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ProductInputsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductInputsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductInputsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ProductInputsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductInputsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductInputsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ProductInputsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductInputsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = ProductInputsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ProductInputsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductInputsServiceClient.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 = ProductInputsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ProductInputsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductInputsServiceClient.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.ProductInputsServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductInputsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductInputsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductInputsServiceClient.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 = ProductInputsServiceClient( + 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 = ProductInputsServiceAsyncClient( + 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 = ProductInputsServiceClient( + 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 = ProductInputsServiceClient( + 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", [ + (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport), + (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport), +]) +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-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_products_service.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_products_service.py new file mode 100644 index 000000000000..1a5ebb547cb6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_products_service.py @@ -0,0 +1,3096 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_products_v1beta.services.products_service import ProductsServiceAsyncClient +from google.shopping.merchant_products_v1beta.services.products_service import ProductsServiceClient +from google.shopping.merchant_products_v1beta.services.products_service import pagers +from google.shopping.merchant_products_v1beta.services.products_service import transports +from google.shopping.merchant_products_v1beta.types import products +from google.shopping.merchant_products_v1beta.types import products_common +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 ProductsServiceClient._get_default_mtls_endpoint(None) is None + assert ProductsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ProductsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ProductsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ProductsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ProductsServiceClient._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 ProductsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ProductsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ProductsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ProductsServiceClient._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 ProductsServiceClient._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 ProductsServiceClient._get_client_cert_source(None, False) is None + assert ProductsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ProductsServiceClient._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 ProductsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ProductsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ProductsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceClient)) +@mock.patch.object(ProductsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ProductsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ProductsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ProductsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ProductsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ProductsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProductsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProductsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ProductsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ProductsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProductsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProductsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProductsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ProductsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ProductsServiceClient._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 ProductsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ProductsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ProductsServiceClient._get_universe_domain(None, None) == ProductsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ProductsServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc"), + (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductsServiceClient, "grpc"), + (ProductsServiceAsyncClient, "grpc_asyncio"), + (ProductsServiceClient, "rest"), +]) +def test_products_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.ProductsServiceGrpcTransport, "grpc"), + (transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProductsServiceRestTransport, "rest"), +]) +def test_products_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", [ + (ProductsServiceClient, "grpc"), + (ProductsServiceAsyncClient, "grpc_asyncio"), + (ProductsServiceClient, "rest"), +]) +def test_products_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_products_service_client_get_transport_class(): + transport = ProductsServiceClient.get_transport_class() + available_transports = [ + transports.ProductsServiceGrpcTransport, + transports.ProductsServiceRestTransport, + ] + assert transport in available_transports + + transport = ProductsServiceClient.get_transport_class("grpc") + assert transport == transports.ProductsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc"), + (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest"), +]) +@mock.patch.object(ProductsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceClient)) +@mock.patch.object(ProductsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceAsyncClient)) +def test_products_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(ProductsServiceClient, '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(ProductsServiceClient, '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", [ + (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc", "true"), + (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc", "false"), + (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest", "true"), + (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ProductsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceClient)) +@mock.patch.object(ProductsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_products_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", [ + ProductsServiceClient, ProductsServiceAsyncClient +]) +@mock.patch.object(ProductsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductsServiceClient)) +@mock.patch.object(ProductsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductsServiceAsyncClient)) +def test_products_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", [ + ProductsServiceClient, ProductsServiceAsyncClient +]) +@mock.patch.object(ProductsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceClient)) +@mock.patch.object(ProductsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceAsyncClient)) +def test_products_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ProductsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ProductsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ProductsServiceClient._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", [ + (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc"), + (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest"), +]) +def test_products_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", [ + (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc", grpc_helpers), + (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest", None), +]) +def test_products_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_products_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_products_v1beta.services.products_service.transports.ProductsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProductsServiceClient( + 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", [ + (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc", grpc_helpers), + (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_products_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", [ + products.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = products.Product( + name='name_value', + channel=types.Channel.ChannelEnum.ONLINE, + offer_id='offer_id_value', + content_language='content_language_value', + feed_label='feed_label_value', + data_source='data_source_value', + version_number=1518, + ) + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = products.GetProductRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, products.Product) + assert response.name == 'name_value' + assert response.channel == types.Channel.ChannelEnum.ONLINE + assert response.offer_id == 'offer_id_value' + assert response.content_language == 'content_language_value' + assert response.feed_label == 'feed_label_value' + assert response.data_source == 'data_source_value' + assert response.version_number == 1518 + + +def test_get_product_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = products.GetProductRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_product(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == products.GetProductRequest( + name='name_value', + ) + +def test_get_product_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_product in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_product] = mock_rpc + request = {} + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_product(request) + + # Establish that a new wrapper 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_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_product in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_product] = mock_rpc + + request = {} + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_product(request) + + # Establish that a new wrapper 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_product_async(transport: str = 'grpc_asyncio', request_type=products.GetProductRequest): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(products.Product( + name='name_value', + channel=types.Channel.ChannelEnum.ONLINE, + offer_id='offer_id_value', + content_language='content_language_value', + feed_label='feed_label_value', + data_source='data_source_value', + version_number=1518, + )) + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = products.GetProductRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, products.Product) + assert response.name == 'name_value' + assert response.channel == types.Channel.ChannelEnum.ONLINE + assert response.offer_id == 'offer_id_value' + assert response.content_language == 'content_language_value' + assert response.feed_label == 'feed_label_value' + assert response.data_source == 'data_source_value' + assert response.version_number == 1518 + + +@pytest.mark.asyncio +async def test_get_product_async_from_dict(): + await test_get_product_async(request_type=dict) + +def test_get_product_field_headers(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = products.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = products.Product() + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_field_headers_async(): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = products.GetProductRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.Product()) + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_product_flattened(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = products.Product() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product( + name='name_value', + ) + + # Establish that the 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_product_flattened_error(): + client = ProductsServiceClient( + credentials=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_product( + products.GetProductRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = products.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.Product()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product( + name='name_value', + ) + + # Establish that 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_product_flattened_error_async(): + client = ProductsServiceAsyncClient( + credentials=async_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_product( + products.GetProductRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + products.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = products.ListProductsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = products.ListProductsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_products_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = products.ListProductsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_products(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == products.ListProductsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_products_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_products in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_products] = mock_rpc + request = {} + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_products(request) + + # Establish that a new wrapper 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_products_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_products in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_products] = mock_rpc + + request = {} + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_products(request) + + # Establish that a new wrapper 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_products_async(transport: str = 'grpc_asyncio', request_type=products.ListProductsRequest): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(products.ListProductsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = products.ListProductsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_products_async_from_dict(): + await test_list_products_async(request_type=dict) + +def test_list_products_field_headers(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = products.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = products.ListProductsResponse() + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_field_headers_async(): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = products.ListProductsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.ListProductsResponse()) + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_products_flattened(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = products.ListProductsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products( + parent='parent_value', + ) + + # Establish that the 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_products_flattened_error(): + client = ProductsServiceClient( + credentials=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_products( + products.ListProductsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = products.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.ListProductsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products( + parent='parent_value', + ) + + # Establish that 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_products_flattened_error_async(): + client = ProductsServiceAsyncClient( + credentials=async_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_products( + products.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_pager(transport_name: str = "grpc"): + client = ProductsServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + products.Product(), + ], + next_page_token='abc', + ), + products.ListProductsResponse( + products=[], + next_page_token='def', + ), + products.ListProductsResponse( + products=[ + products.Product(), + ], + next_page_token='ghi', + ), + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_products(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, products.Product) + for i in results) +def test_list_products_pages(transport_name: str = "grpc"): + client = ProductsServiceClient( + 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_products), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + products.Product(), + ], + next_page_token='abc', + ), + products.ListProductsResponse( + products=[], + next_page_token='def', + ), + products.ListProductsResponse( + products=[ + products.Product(), + ], + next_page_token='ghi', + ), + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(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_products_async_pager(): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + products.Product(), + ], + next_page_token='abc', + ), + products.ListProductsResponse( + products=[], + next_page_token='def', + ), + products.ListProductsResponse( + products=[ + products.Product(), + ], + next_page_token='ghi', + ), + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(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, products.Product) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + products.Product(), + ], + next_page_token='abc', + ), + products.ListProductsResponse( + products=[], + next_page_token='def', + ), + products.ListProductsResponse( + products=[ + products.Product(), + ], + next_page_token='ghi', + ), + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + ], + ), + 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_products(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_product_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_product in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_product] = mock_rpc + + request = {} + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_product(request) + + # Establish 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_product_rest_required_fields(request_type=products.GetProductRequest): + transport_class = transports.ProductsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product._get_unset_required_fields(jsonified_request) + 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_product._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = products.Product() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = products.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_product(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_product_rest_unset_required_fields(): + transport = transports.ProductsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_product._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_product_rest_flattened(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = products.Product() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/products/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 = products.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_product(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/products/v1beta/{name=accounts/*/products/*}" % client.transport._host, args[1]) + + +def test_get_product_rest_flattened_error(transport: str = 'rest'): + client = ProductsServiceClient( + credentials=ga_credentials.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_product( + products.GetProductRequest(), + name='name_value', + ) + + +def test_list_products_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_products in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_products] = mock_rpc + + request = {} + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_products(request) + + # Establish 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_products_rest_required_fields(request_type=products.ListProductsRequest): + transport_class = transports.ProductsServiceRestTransport + + 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_products._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + 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 = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = products.ListProductsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = products.ListProductsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_products(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_products_rest_unset_required_fields(): + transport = transports.ProductsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_products._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_products_rest_flattened(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = products.ListProductsResponse() + + # 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 = products.ListProductsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_products(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/products/v1beta/{parent=accounts/*}/products" % client.transport._host, args[1]) + + +def test_list_products_rest_flattened_error(transport: str = 'rest'): + client = ProductsServiceClient( + credentials=ga_credentials.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_products( + products.ListProductsRequest(), + parent='parent_value', + ) + + +def test_list_products_rest_pager(transport: str = 'rest'): + client = ProductsServiceClient( + 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 = ( + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + products.Product(), + ], + next_page_token='abc', + ), + products.ListProductsResponse( + products=[], + next_page_token='def', + ), + products.ListProductsResponse( + products=[ + products.Product(), + ], + next_page_token='ghi', + ), + products.ListProductsResponse( + products=[ + products.Product(), + products.Product(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(products.ListProductsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'accounts/sample1'} + + pager = client.list_products(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, products.Product) + for i in results) + + pages = list(client.list_products(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.ProductsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductsServiceClient( + 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 = ProductsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProductsServiceGrpcTransport, + transports.ProductsServiceGrpcAsyncIOTransport, + transports.ProductsServiceRestTransport, +]) +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 = ProductsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProductsServiceClient( + 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_product_empty_call_grpc(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = products.Product() + client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = products.GetProductRequest() + + assert args[0] == request_msg + + +# This 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_products_empty_call_grpc(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = products.ListProductsResponse() + client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = products.ListProductsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProductsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProductsServiceAsyncClient( + 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_product_empty_call_grpc_asyncio(): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.Product( + name='name_value', + channel=types.Channel.ChannelEnum.ONLINE, + offer_id='offer_id_value', + content_language='content_language_value', + feed_label='feed_label_value', + data_source='data_source_value', + version_number=1518, + )) + await client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = products.GetProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_products_empty_call_grpc_asyncio(): + client = ProductsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.ListProductsResponse( + next_page_token='next_page_token_value', + )) + await client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = products.ListProductsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProductsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_product_rest_bad_request(request_type=products.GetProductRequest): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': '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 + client.get_product(request) + + +@pytest.mark.parametrize("request_type", [ + products.GetProductRequest, + dict, +]) +def test_get_product_rest_call_success(request_type): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': '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 = products.Product( + name='name_value', + channel=types.Channel.ChannelEnum.ONLINE, + offer_id='offer_id_value', + content_language='content_language_value', + feed_label='feed_label_value', + 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 = products.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_product(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, products.Product) + assert response.name == 'name_value' + assert response.channel == types.Channel.ChannelEnum.ONLINE + assert response.offer_id == 'offer_id_value' + assert response.content_language == 'content_language_value' + assert response.feed_label == 'feed_label_value' + assert response.data_source == 'data_source_value' + assert response.version_number == 1518 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_product_rest_interceptors(null_interceptor): + transport = transports.ProductsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProductsServiceRestInterceptor(), + ) + client = ProductsServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductsServiceRestInterceptor, "post_get_product") as post, \ + mock.patch.object(transports.ProductsServiceRestInterceptor, "pre_get_product") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = products.GetProductRequest.pb(products.GetProductRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = products.Product.to_json(products.Product()) + req.return_value.content = return_value + + request = products.GetProductRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = products.Product() + + client.get_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_products_rest_bad_request(request_type=products.ListProductsRequest): + client = ProductsServiceClient( + 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 + client.list_products(request) + + +@pytest.mark.parametrize("request_type", [ + products.ListProductsRequest, + dict, +]) +def test_list_products_rest_call_success(request_type): + client = ProductsServiceClient( + 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 = products.ListProductsResponse( + 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 = products.ListProductsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_products(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_products_rest_interceptors(null_interceptor): + transport = transports.ProductsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProductsServiceRestInterceptor(), + ) + client = ProductsServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductsServiceRestInterceptor, "post_list_products") as post, \ + mock.patch.object(transports.ProductsServiceRestInterceptor, "pre_list_products") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = products.ListProductsRequest.pb(products.ListProductsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = products.ListProductsResponse.to_json(products.ListProductsResponse()) + req.return_value.content = return_value + + request = products.ListProductsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = products.ListProductsResponse() + + client.list_products(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + +def test_initialize_client_w_rest(): + client = ProductsServiceClient( + 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_product_empty_call_rest(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = products.GetProductRequest() + + assert args[0] == request_msg + + +# This 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_products_empty_call_rest(): + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = products.ListProductsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProductsServiceGrpcTransport, + ) + +def test_products_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProductsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_products_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_products_v1beta.services.products_service.transports.ProductsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProductsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_product', + 'list_products', + ) + 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_products_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_products_v1beta.services.products_service.transports.ProductsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductsServiceTransport( + 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_products_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_products_v1beta.services.products_service.transports.ProductsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductsServiceTransport() + adc.assert_called_once() + + +def test_products_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) + ProductsServiceClient() + 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.ProductsServiceGrpcTransport, + transports.ProductsServiceGrpcAsyncIOTransport, + ], +) +def test_products_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.ProductsServiceGrpcTransport, + transports.ProductsServiceGrpcAsyncIOTransport, + transports.ProductsServiceRestTransport, + ], +) +def test_products_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.ProductsServiceGrpcTransport, grpc_helpers), + (transports.ProductsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_products_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.ProductsServiceGrpcTransport, transports.ProductsServiceGrpcAsyncIOTransport]) +def test_products_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_products_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.ProductsServiceRestTransport ( + 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_products_service_host_no_port(transport_name): + client = ProductsServiceClient( + 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_products_service_host_with_port(transport_name): + client = ProductsServiceClient( + 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_products_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ProductsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ProductsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_product._session + session2 = client2.transport.get_product._session + assert session1 != session2 + session1 = client1.transport.list_products._session + session2 = client2.transport.list_products._session + assert session1 != session2 +def test_products_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductsServiceGrpcTransport( + 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_products_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProductsServiceGrpcAsyncIOTransport( + 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.ProductsServiceGrpcTransport, transports.ProductsServiceGrpcAsyncIOTransport]) +def test_products_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.ProductsServiceGrpcTransport, transports.ProductsServiceGrpcAsyncIOTransport]) +def test_products_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_product_path(): + account = "squid" + product = "clam" + expected = "accounts/{account}/products/{product}".format(account=account, product=product, ) + actual = ProductsServiceClient.product_path(account, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "account": "whelk", + "product": "octopus", + } + path = ProductsServiceClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductsServiceClient.parse_product_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProductsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ProductsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProductsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProductsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ProductsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProductsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProductsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ProductsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProductsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ProductsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ProductsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProductsServiceClient.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 = ProductsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ProductsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProductsServiceClient.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.ProductsServiceTransport, '_prep_wrapped_messages') as prep: + client = ProductsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProductsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProductsServiceClient.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 = ProductsServiceClient( + 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 = ProductsServiceAsyncClient( + 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 = ProductsServiceClient( + 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 = ProductsServiceClient( + 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", [ + (ProductsServiceClient, transports.ProductsServiceGrpcTransport), + (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport), +]) +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 2044471907b53e57e92862e2f1139c5d719c1652 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 24 Oct 2024 22:23:22 +0000 Subject: [PATCH 2/3] update replacement for docs/index.rst --- .../docs-index-rst-for-unversioned-apis.yaml | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/scripts/client-post-processing/docs-index-rst-for-unversioned-apis.yaml b/scripts/client-post-processing/docs-index-rst-for-unversioned-apis.yaml index 122e91810bbd..21643914a677 100644 --- a/scripts/client-post-processing/docs-index-rst-for-unversioned-apis.yaml +++ b/scripts/client-post-processing/docs-index-rst-for-unversioned-apis.yaml @@ -62,8 +62,8 @@ replacements: .. toctree:: :maxdepth: 2 - type/services - type/types + type/services_ + type/types_ after: | .. include:: README.rst @@ -74,6 +74,7 @@ replacements: .. toctree:: :maxdepth: 2 + type/services_ type/types_ @@ -96,8 +97,8 @@ replacements: .. toctree:: :maxdepth: 2 - type/services - type/types + type/services_ + type/types_ after: | .. include:: README.rst @@ -108,6 +109,7 @@ replacements: .. toctree:: :maxdepth: 2 + calendar/services_ calendar/types_ docs/services_ @@ -143,8 +145,8 @@ replacements: .. toctree:: :maxdepth: 2 - type/services - type/types + type/services_ + type/types_ after: | .. include:: README.rst @@ -155,6 +157,7 @@ replacements: .. toctree:: :maxdepth: 2 + type/services_ type/types_ From c0a8e548dc78099e1f080a3db9216403f44f29ba Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 24 Oct 2024 23:02:13 +0000 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../v1/.coveragerc | 13 - .../v1/.flake8 | 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 - .../docs/websecurityscanner_v1/services_.rst | 6 - .../v1/docs/websecurityscanner_v1/types_.rst | 6 - .../web_security_scanner.rst | 10 - .../cloud/websecurityscanner/__init__.py | 95 - .../cloud/websecurityscanner/gapic_version.py | 16 - .../google/cloud/websecurityscanner/py.typed | 2 - .../cloud/websecurityscanner_v1/__init__.py | 96 - .../websecurityscanner_v1/gapic_metadata.json | 223 - .../websecurityscanner_v1/gapic_version.py | 16 - .../cloud/websecurityscanner_v1/py.typed | 2 - .../services/__init__.py | 15 - .../services/web_security_scanner/__init__.py | 22 - .../web_security_scanner/async_client.py | 1353 -- .../services/web_security_scanner/client.py | 1710 -- .../services/web_security_scanner/pagers.py | 571 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../web_security_scanner/transports/base.py | 416 - .../web_security_scanner/transports/grpc.py | 592 - .../transports/grpc_asyncio.py | 763 - .../web_security_scanner/transports/rest.py | 1532 -- .../transports/rest_base.py | 512 - .../websecurityscanner_v1/types/__init__.py | 108 - .../types/crawled_url.py | 62 - .../websecurityscanner_v1/types/finding.py | 209 - .../types/finding_addon.py | 303 - .../types/finding_type_stats.py | 54 - .../types/scan_config.py | 361 - .../types/scan_config_error.py | 241 - .../websecurityscanner_v1/types/scan_run.py | 181 - .../types/scan_run_error_trace.py | 107 - .../types/scan_run_log.py | 98 - .../types/scan_run_warning_trace.py | 82 - .../types/web_security_scanner.py | 484 - .../v1/mypy.ini | 3 - .../v1/noxfile.py | 280 - ...ta_google.cloud.websecurityscanner.v1.json | 1998 -- ...curity_scanner_create_scan_config_async.py | 51 - ...ecurity_scanner_create_scan_config_sync.py | 51 - ...curity_scanner_delete_scan_config_async.py | 49 - ...ecurity_scanner_delete_scan_config_sync.py | 49 - ..._web_security_scanner_get_finding_async.py | 51 - ...d_web_security_scanner_get_finding_sync.py | 51 - ..._security_scanner_get_scan_config_async.py | 51 - ...b_security_scanner_get_scan_config_sync.py | 51 - ...web_security_scanner_get_scan_run_async.py | 51 - ..._web_security_scanner_get_scan_run_sync.py | 51 - ...ecurity_scanner_list_crawled_urls_async.py | 52 - ...security_scanner_list_crawled_urls_sync.py | 52 - ...y_scanner_list_finding_type_stats_async.py | 51 - ...ty_scanner_list_finding_type_stats_sync.py | 51 - ...eb_security_scanner_list_findings_async.py | 52 - ...web_security_scanner_list_findings_sync.py | 52 - ...ecurity_scanner_list_scan_configs_async.py | 52 - ...security_scanner_list_scan_configs_sync.py | 52 - ...b_security_scanner_list_scan_runs_async.py | 52 - ...eb_security_scanner_list_scan_runs_sync.py | 52 - ...b_security_scanner_start_scan_run_async.py | 51 - ...eb_security_scanner_start_scan_run_sync.py | 51 - ...eb_security_scanner_stop_scan_run_async.py | 51 - ...web_security_scanner_stop_scan_run_sync.py | 51 - ...curity_scanner_update_scan_config_async.py | 51 - ...ecurity_scanner_update_scan_config_sync.py | 51 - .../fixup_websecurityscanner_v1_keywords.py | 188 - .../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.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/websecurityscanner_v1/__init__.py | 16 - .../test_web_security_scanner.py | 8720 -------- .../v1alpha/.coveragerc | 13 - .../v1alpha/.flake8 | 33 - .../v1alpha/MANIFEST.in | 2 - .../v1alpha/README.rst | 49 - .../v1alpha/docs/_static/custom.css | 3 - .../v1alpha/docs/conf.py | 376 - .../v1alpha/docs/index.rst | 7 - .../websecurityscanner_v1alpha/services_.rst | 6 - .../websecurityscanner_v1alpha/types_.rst | 6 - .../web_security_scanner.rst | 10 - .../cloud/websecurityscanner/__init__.py | 83 - .../cloud/websecurityscanner/gapic_version.py | 16 - .../google/cloud/websecurityscanner/py.typed | 2 - .../websecurityscanner_v1alpha/__init__.py | 84 - .../gapic_metadata.json | 223 - .../gapic_version.py | 16 - .../cloud/websecurityscanner_v1alpha/py.typed | 2 - .../services/__init__.py | 15 - .../services/web_security_scanner/__init__.py | 22 - .../web_security_scanner/async_client.py | 1698 -- .../services/web_security_scanner/client.py | 2060 -- .../services/web_security_scanner/pagers.py | 571 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../web_security_scanner/transports/base.py | 417 - .../web_security_scanner/transports/grpc.py | 593 - .../transports/grpc_asyncio.py | 764 - .../web_security_scanner/transports/rest.py | 1533 -- .../transports/rest_base.py | 617 - .../types/__init__.py | 88 - .../types/crawled_url.py | 62 - .../types/finding.py | 241 - .../types/finding_addon.py | 160 - .../types/finding_type_stats.py | 56 - .../types/scan_config.py | 268 - .../types/scan_run.py | 159 - .../types/web_security_scanner.py | 485 - .../v1alpha/mypy.ini | 3 - .../v1alpha/noxfile.py | 280 - ...ogle.cloud.websecurityscanner.v1alpha.json | 2126 -- ...curity_scanner_create_scan_config_async.py | 57 - ...ecurity_scanner_create_scan_config_sync.py | 57 - ...curity_scanner_delete_scan_config_async.py | 50 - ...ecurity_scanner_delete_scan_config_sync.py | 50 - ..._web_security_scanner_get_finding_async.py | 52 - ...d_web_security_scanner_get_finding_sync.py | 52 - ..._security_scanner_get_scan_config_async.py | 52 - ...b_security_scanner_get_scan_config_sync.py | 52 - ...web_security_scanner_get_scan_run_async.py | 52 - ..._web_security_scanner_get_scan_run_sync.py | 52 - ...ecurity_scanner_list_crawled_urls_async.py | 53 - ...security_scanner_list_crawled_urls_sync.py | 53 - ...y_scanner_list_finding_type_stats_async.py | 52 - ...ty_scanner_list_finding_type_stats_sync.py | 52 - ...eb_security_scanner_list_findings_async.py | 54 - ...web_security_scanner_list_findings_sync.py | 54 - ...ecurity_scanner_list_scan_configs_async.py | 53 - ...security_scanner_list_scan_configs_sync.py | 53 - ...b_security_scanner_list_scan_runs_async.py | 53 - ...eb_security_scanner_list_scan_runs_sync.py | 53 - ...b_security_scanner_start_scan_run_async.py | 52 - ...eb_security_scanner_start_scan_run_sync.py | 52 - ...eb_security_scanner_stop_scan_run_async.py | 52 - ...web_security_scanner_stop_scan_run_sync.py | 52 - ...curity_scanner_update_scan_config_async.py | 56 - ...ecurity_scanner_update_scan_config_sync.py | 56 - ...xup_websecurityscanner_v1alpha_keywords.py | 188 - .../v1alpha/setup.py | 98 - .../v1alpha/testing/constraints-3.10.txt | 6 - .../v1alpha/testing/constraints-3.11.txt | 6 - .../v1alpha/testing/constraints-3.12.txt | 6 - .../v1alpha/testing/constraints-3.7.txt | 10 - .../v1alpha/testing/constraints-3.8.txt | 6 - .../v1alpha/testing/constraints-3.9.txt | 6 - .../v1alpha/tests/__init__.py | 16 - .../v1alpha/tests/unit/__init__.py | 16 - .../v1alpha/tests/unit/gapic/__init__.py | 16 - .../websecurityscanner_v1alpha/__init__.py | 16 - .../test_web_security_scanner.py | 11488 ---------- .../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 - .../websecurityscanner_v1beta/services_.rst | 6 - .../docs/websecurityscanner_v1beta/types_.rst | 6 - .../web_security_scanner.rst | 10 - .../cloud/websecurityscanner/__init__.py | 91 - .../cloud/websecurityscanner/gapic_version.py | 16 - .../google/cloud/websecurityscanner/py.typed | 2 - .../websecurityscanner_v1beta/__init__.py | 92 - .../gapic_metadata.json | 223 - .../gapic_version.py | 16 - .../cloud/websecurityscanner_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../services/web_security_scanner/__init__.py | 22 - .../web_security_scanner/async_client.py | 1700 -- .../services/web_security_scanner/client.py | 2062 -- .../services/web_security_scanner/pagers.py | 571 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../web_security_scanner/transports/base.py | 417 - .../web_security_scanner/transports/grpc.py | 593 - .../transports/grpc_asyncio.py | 764 - .../web_security_scanner/transports/rest.py | 1533 -- .../transports/rest_base.py | 617 - .../types/__init__.py | 102 - .../types/crawled_url.py | 62 - .../types/finding.py | 169 - .../types/finding_addon.py | 183 - .../types/finding_type_stats.py | 53 - .../types/scan_config.py | 319 - .../types/scan_config_error.py | 241 - .../types/scan_run.py | 178 - .../types/scan_run_error_trace.py | 106 - .../types/scan_run_warning_trace.py | 79 - .../types/web_security_scanner.py | 485 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ...oogle.cloud.websecurityscanner.v1beta.json | 2126 -- ...curity_scanner_create_scan_config_async.py | 57 - ...ecurity_scanner_create_scan_config_sync.py | 57 - ...curity_scanner_delete_scan_config_async.py | 50 - ...ecurity_scanner_delete_scan_config_sync.py | 50 - ..._web_security_scanner_get_finding_async.py | 52 - ...d_web_security_scanner_get_finding_sync.py | 52 - ..._security_scanner_get_scan_config_async.py | 52 - ...b_security_scanner_get_scan_config_sync.py | 52 - ...web_security_scanner_get_scan_run_async.py | 52 - ..._web_security_scanner_get_scan_run_sync.py | 52 - ...ecurity_scanner_list_crawled_urls_async.py | 53 - ...security_scanner_list_crawled_urls_sync.py | 53 - ...y_scanner_list_finding_type_stats_async.py | 52 - ...ty_scanner_list_finding_type_stats_sync.py | 52 - ...eb_security_scanner_list_findings_async.py | 54 - ...web_security_scanner_list_findings_sync.py | 54 - ...ecurity_scanner_list_scan_configs_async.py | 53 - ...security_scanner_list_scan_configs_sync.py | 53 - ...b_security_scanner_list_scan_runs_async.py | 53 - ...eb_security_scanner_list_scan_runs_sync.py | 53 - ...b_security_scanner_start_scan_run_async.py | 52 - ...eb_security_scanner_start_scan_run_sync.py | 52 - ...eb_security_scanner_stop_scan_run_async.py | 52 - ...web_security_scanner_stop_scan_run_sync.py | 52 - ...curity_scanner_update_scan_config_async.py | 56 - ...ecurity_scanner_update_scan_config_sync.py | 56 - ...ixup_websecurityscanner_v1beta_keywords.py | 188 - .../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.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 - .../websecurityscanner_v1beta/__init__.py | 16 - .../test_web_security_scanner.py | 11533 ---------- .../google-cloud-workflows/v1/.coveragerc | 13 - .../google-cloud-workflows/v1/.flake8 | 33 - .../google-cloud-workflows/v1/MANIFEST.in | 2 - .../google-cloud-workflows/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-cloud-workflows/v1/docs/conf.py | 376 - .../v1/docs/executions_v1/executions.rst | 10 - .../v1/docs/executions_v1/services_.rst | 6 - .../v1/docs/executions_v1/types_.rst | 6 - .../google-cloud-workflows/v1/docs/index.rst | 7 - .../v1/docs/workflows_v1/services_.rst | 6 - .../v1/docs/workflows_v1/types_.rst | 6 - .../v1/docs/workflows_v1/workflows.rst | 10 - .../v1/google/cloud/workflows/__init__.py | 43 - .../cloud/workflows/executions/__init__.py | 41 - .../workflows/executions/gapic_version.py | 16 - .../cloud/workflows/executions/py.typed | 2 - .../cloud/workflows/executions_v1/__init__.py | 42 - .../executions_v1/gapic_metadata.json | 63 - .../workflows/executions_v1/gapic_version.py | 16 - .../cloud/workflows/executions_v1/py.typed | 2 - .../executions_v1/services/__init__.py | 15 - .../services/executions/__init__.py | 22 - .../services/executions/async_client.py | 697 - .../services/executions/client.py | 1057 - .../services/executions/pagers.py | 162 - .../services/executions/transports/README.rst | 9 - .../executions/transports/__init__.py | 33 - .../services/executions/transports/base.py | 196 - .../services/executions/transports/grpc.py | 354 - .../executions/transports/grpc_asyncio.py | 390 - .../workflows/executions_v1/types/__init__.py | 34 - .../executions_v1/types/executions.py | 580 - .../google/cloud/workflows/gapic_version.py | 16 - .../v1/google/cloud/workflows/py.typed | 2 - .../v1/google/cloud/workflows_v1/__init__.py | 44 - .../cloud/workflows_v1/gapic_metadata.json | 103 - .../cloud/workflows_v1/gapic_version.py | 16 - .../v1/google/cloud/workflows_v1/py.typed | 2 - .../cloud/workflows_v1/services/__init__.py | 15 - .../services/workflows/__init__.py | 22 - .../services/workflows/async_client.py | 1149 - .../workflows_v1/services/workflows/client.py | 1505 -- .../workflows_v1/services/workflows/pagers.py | 162 - .../services/workflows/transports/README.rst | 9 - .../services/workflows/transports/__init__.py | 38 - .../services/workflows/transports/base.py | 286 - .../services/workflows/transports/grpc.py | 497 - .../workflows/transports/grpc_asyncio.py | 563 - .../services/workflows/transports/rest.py | 1224 -- .../workflows/transports/rest_base.py | 423 - .../cloud/workflows_v1/types/__init__.py | 36 - .../cloud/workflows_v1/types/workflows.py | 521 - .../google-cloud-workflows/v1/mypy.ini | 3 - .../google-cloud-workflows/v1/noxfile.py | 280 - ..._google.cloud.workflows.executions.v1.json | 667 - ...et_metadata_google.cloud.workflows.v1.json | 844 - ...rated_executions_cancel_execution_async.py | 52 - ...erated_executions_cancel_execution_sync.py | 52 - ...rated_executions_create_execution_async.py | 52 - ...erated_executions_create_execution_sync.py | 52 - ...enerated_executions_get_execution_async.py | 52 - ...generated_executions_get_execution_sync.py | 52 - ...erated_executions_list_executions_async.py | 53 - ...nerated_executions_list_executions_sync.py | 53 - ...nerated_workflows_create_workflow_async.py | 61 - ...enerated_workflows_create_workflow_sync.py | 61 - ...nerated_workflows_delete_workflow_async.py | 56 - ...enerated_workflows_delete_workflow_sync.py | 56 - ..._generated_workflows_get_workflow_async.py | 52 - ...1_generated_workflows_get_workflow_sync.py | 52 - ...enerated_workflows_list_workflows_async.py | 53 - ...generated_workflows_list_workflows_sync.py | 53 - ...nerated_workflows_update_workflow_async.py | 59 - ...enerated_workflows_update_workflow_sync.py | 59 - .../scripts/fixup_executions_v1_keywords.py | 179 - .../v1/scripts/fixup_workflows_v1_keywords.py | 180 - .../google-cloud-workflows/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.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 - .../unit/gapic/executions_v1/__init__.py | 16 - .../gapic/executions_v1/test_executions.py | 3165 --- .../tests/unit/gapic/workflows_v1/__init__.py | 16 - .../unit/gapic/workflows_v1/test_workflows.py | 6232 ------ .../google-cloud-workflows/v1beta/.coveragerc | 13 - .../google-cloud-workflows/v1beta/.flake8 | 33 - .../google-cloud-workflows/v1beta/MANIFEST.in | 2 - .../google-cloud-workflows/v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../docs/executions_v1beta/executions.rst | 10 - .../docs/executions_v1beta/services_.rst | 6 - .../v1beta/docs/executions_v1beta/types_.rst | 6 - .../v1beta/docs/index.rst | 7 - .../docs/workflows_v1beta/services_.rst | 6 - .../v1beta/docs/workflows_v1beta/types_.rst | 6 - .../docs/workflows_v1beta/workflows.rst | 10 - .../v1beta/google/cloud/workflows/__init__.py | 43 - .../cloud/workflows/executions/__init__.py | 41 - .../workflows/executions/gapic_version.py | 16 - .../cloud/workflows/executions/py.typed | 2 - .../workflows/executions_v1beta/__init__.py | 42 - .../executions_v1beta/gapic_metadata.json | 63 - .../executions_v1beta/gapic_version.py | 16 - .../workflows/executions_v1beta/py.typed | 2 - .../executions_v1beta/services/__init__.py | 15 - .../services/executions/__init__.py | 22 - .../services/executions/async_client.py | 699 - .../services/executions/client.py | 1059 - .../services/executions/pagers.py | 162 - .../services/executions/transports/README.rst | 9 - .../executions/transports/__init__.py | 33 - .../services/executions/transports/base.py | 196 - .../services/executions/transports/grpc.py | 355 - .../executions/transports/grpc_asyncio.py | 391 - .../executions_v1beta/types/__init__.py | 34 - .../executions_v1beta/types/executions.py | 324 - .../google/cloud/workflows/gapic_version.py | 16 - .../v1beta/google/cloud/workflows/py.typed | 2 - .../google/cloud/workflows_v1beta/__init__.py | 44 - .../workflows_v1beta/gapic_metadata.json | 103 - .../cloud/workflows_v1beta/gapic_version.py | 16 - .../google/cloud/workflows_v1beta/py.typed | 2 - .../workflows_v1beta/services/__init__.py | 15 - .../services/workflows/__init__.py | 22 - .../services/workflows/async_client.py | 894 - .../services/workflows/client.py | 1246 -- .../services/workflows/pagers.py | 162 - .../services/workflows/transports/README.rst | 9 - .../services/workflows/transports/__init__.py | 38 - .../services/workflows/transports/base.py | 217 - .../services/workflows/transports/grpc.py | 406 - .../workflows/transports/grpc_asyncio.py | 447 - .../services/workflows/transports/rest.py | 760 - .../workflows/transports/rest_base.py | 297 - .../cloud/workflows_v1beta/types/__init__.py | 36 - .../cloud/workflows_v1beta/types/workflows.py | 403 - .../google-cloud-workflows/v1beta/mypy.ini | 3 - .../google-cloud-workflows/v1beta/noxfile.py | 280 - ...gle.cloud.workflows.executions.v1beta.json | 667 - ...etadata_google.cloud.workflows.v1beta.json | 844 - ...rated_executions_cancel_execution_async.py | 52 - ...erated_executions_cancel_execution_sync.py | 52 - ...rated_executions_create_execution_async.py | 52 - ...erated_executions_create_execution_sync.py | 52 - ...enerated_executions_get_execution_async.py | 52 - ...generated_executions_get_execution_sync.py | 52 - ...erated_executions_list_executions_async.py | 53 - ...nerated_executions_list_executions_sync.py | 53 - ...nerated_workflows_create_workflow_async.py | 61 - ...enerated_workflows_create_workflow_sync.py | 61 - ...nerated_workflows_delete_workflow_async.py | 56 - ...enerated_workflows_delete_workflow_sync.py | 56 - ..._generated_workflows_get_workflow_async.py | 52 - ...a_generated_workflows_get_workflow_sync.py | 52 - ...enerated_workflows_list_workflows_async.py | 53 - ...generated_workflows_list_workflows_sync.py | 53 - ...nerated_workflows_update_workflow_async.py | 59 - ...enerated_workflows_update_workflow_sync.py | 59 - .../fixup_executions_v1beta_keywords.py | 179 - .../fixup_workflows_v1beta_keywords.py | 180 - .../google-cloud-workflows/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.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 - .../unit/gapic/executions_v1beta/__init__.py | 16 - .../executions_v1beta/test_executions.py | 3145 --- .../unit/gapic/workflows_v1beta/__init__.py | 16 - .../gapic/workflows_v1beta/test_workflows.py | 5286 ----- .../google-cloud-workstations/v1/.coveragerc | 13 - .../google-cloud-workstations/v1/.flake8 | 33 - .../google-cloud-workstations/v1/MANIFEST.in | 2 - .../google-cloud-workstations/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-cloud-workstations/v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../v1/docs/workstations_v1/services_.rst | 6 - .../v1/docs/workstations_v1/types_.rst | 6 - .../v1/docs/workstations_v1/workstations.rst | 10 - .../v1/google/cloud/workstations/__init__.py | 87 - .../cloud/workstations/gapic_version.py | 16 - .../v1/google/cloud/workstations/py.typed | 2 - .../google/cloud/workstations_v1/__init__.py | 88 - .../cloud/workstations_v1/gapic_metadata.json | 328 - .../cloud/workstations_v1/gapic_version.py | 16 - .../v1/google/cloud/workstations_v1/py.typed | 2 - .../workstations_v1/services/__init__.py | 15 - .../services/workstations/__init__.py | 22 - .../services/workstations/async_client.py | 3183 --- .../services/workstations/client.py | 3536 --- .../services/workstations/pagers.py | 702 - .../workstations/transports/README.rst | 9 - .../workstations/transports/__init__.py | 38 - .../services/workstations/transports/base.py | 612 - .../services/workstations/transports/grpc.py | 948 - .../workstations/transports/grpc_asyncio.py | 1180 - .../services/workstations/transports/rest.py | 3048 --- .../workstations/transports/rest_base.py | 1129 - .../cloud/workstations_v1/types/__init__.py | 80 - .../workstations_v1/types/workstations.py | 1953 -- .../google-cloud-workstations/v1/mypy.ini | 3 - .../google-cloud-workstations/v1/noxfile.py | 280 - ...metadata_google.cloud.workstations.v1.json | 3307 --- ...d_workstations_create_workstation_async.py | 57 - ...ations_create_workstation_cluster_async.py | 57 - ...tations_create_workstation_cluster_sync.py | 57 - ...tations_create_workstation_config_async.py | 57 - ...stations_create_workstation_config_sync.py | 57 - ...ed_workstations_create_workstation_sync.py | 57 - ...d_workstations_delete_workstation_async.py | 56 - ...ations_delete_workstation_cluster_async.py | 56 - ...tations_delete_workstation_cluster_sync.py | 56 - ...tations_delete_workstation_config_async.py | 56 - ...stations_delete_workstation_config_sync.py | 56 - ...ed_workstations_delete_workstation_sync.py | 56 - ...orkstations_generate_access_token_async.py | 52 - ...workstations_generate_access_token_sync.py | 52 - ...ated_workstations_get_workstation_async.py | 52 - ...kstations_get_workstation_cluster_async.py | 52 - ...rkstations_get_workstation_cluster_sync.py | 52 - ...rkstations_get_workstation_config_async.py | 52 - ...orkstations_get_workstation_config_sync.py | 52 - ...rated_workstations_get_workstation_sync.py | 52 - ...s_list_usable_workstation_configs_async.py | 53 - ...ns_list_usable_workstation_configs_sync.py | 53 - ...stations_list_usable_workstations_async.py | 53 - ...kstations_list_usable_workstations_sync.py | 53 - ...tations_list_workstation_clusters_async.py | 53 - ...stations_list_workstation_clusters_sync.py | 53 - ...stations_list_workstation_configs_async.py | 53 - ...kstations_list_workstation_configs_sync.py | 53 - ...ed_workstations_list_workstations_async.py | 53 - ...ted_workstations_list_workstations_sync.py | 53 - ...ed_workstations_start_workstation_async.py | 56 - ...ted_workstations_start_workstation_sync.py | 56 - ...ted_workstations_stop_workstation_async.py | 56 - ...ated_workstations_stop_workstation_sync.py | 56 - ...d_workstations_update_workstation_async.py | 55 - ...ations_update_workstation_cluster_async.py | 55 - ...tations_update_workstation_cluster_sync.py | 55 - ...tations_update_workstation_config_async.py | 55 - ...stations_update_workstation_config_sync.py | 55 - ...ed_workstations_update_workstation_sync.py | 55 - .../scripts/fixup_workstations_v1_keywords.py | 195 - .../google-cloud-workstations/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.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/workstations_v1/__init__.py | 16 - .../workstations_v1/test_workstations.py | 17992 --------------- .../v1beta/.coveragerc | 13 - .../google-cloud-workstations/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 - .../docs/workstations_v1beta/services_.rst | 6 - .../docs/workstations_v1beta/types_.rst | 6 - .../docs/workstations_v1beta/workstations.rst | 10 - .../google/cloud/workstations/__init__.py | 87 - .../cloud/workstations/gapic_version.py | 16 - .../v1beta/google/cloud/workstations/py.typed | 2 - .../cloud/workstations_v1beta/__init__.py | 88 - .../workstations_v1beta/gapic_metadata.json | 328 - .../workstations_v1beta/gapic_version.py | 16 - .../google/cloud/workstations_v1beta/py.typed | 2 - .../workstations_v1beta/services/__init__.py | 15 - .../services/workstations/__init__.py | 22 - .../services/workstations/async_client.py | 3183 --- .../services/workstations/client.py | 3536 --- .../services/workstations/pagers.py | 702 - .../workstations/transports/README.rst | 9 - .../workstations/transports/__init__.py | 38 - .../services/workstations/transports/base.py | 612 - .../services/workstations/transports/grpc.py | 948 - .../workstations/transports/grpc_asyncio.py | 1180 - .../services/workstations/transports/rest.py | 3048 --- .../workstations/transports/rest_base.py | 1129 - .../workstations_v1beta/types/__init__.py | 80 - .../workstations_v1beta/types/workstations.py | 2087 -- .../google-cloud-workstations/v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ...data_google.cloud.workstations.v1beta.json | 3307 --- ...d_workstations_create_workstation_async.py | 57 - ...ations_create_workstation_cluster_async.py | 57 - ...tations_create_workstation_cluster_sync.py | 57 - ...tations_create_workstation_config_async.py | 57 - ...stations_create_workstation_config_sync.py | 57 - ...ed_workstations_create_workstation_sync.py | 57 - ...d_workstations_delete_workstation_async.py | 56 - ...ations_delete_workstation_cluster_async.py | 56 - ...tations_delete_workstation_cluster_sync.py | 56 - ...tations_delete_workstation_config_async.py | 56 - ...stations_delete_workstation_config_sync.py | 56 - ...ed_workstations_delete_workstation_sync.py | 56 - ...orkstations_generate_access_token_async.py | 52 - ...workstations_generate_access_token_sync.py | 52 - ...ated_workstations_get_workstation_async.py | 52 - ...kstations_get_workstation_cluster_async.py | 52 - ...rkstations_get_workstation_cluster_sync.py | 52 - ...rkstations_get_workstation_config_async.py | 52 - ...orkstations_get_workstation_config_sync.py | 52 - ...rated_workstations_get_workstation_sync.py | 52 - ...s_list_usable_workstation_configs_async.py | 53 - ...ns_list_usable_workstation_configs_sync.py | 53 - ...stations_list_usable_workstations_async.py | 53 - ...kstations_list_usable_workstations_sync.py | 53 - ...tations_list_workstation_clusters_async.py | 53 - ...stations_list_workstation_clusters_sync.py | 53 - ...stations_list_workstation_configs_async.py | 53 - ...kstations_list_workstation_configs_sync.py | 53 - ...ed_workstations_list_workstations_async.py | 53 - ...ted_workstations_list_workstations_sync.py | 53 - ...ed_workstations_start_workstation_async.py | 56 - ...ted_workstations_start_workstation_sync.py | 56 - ...ted_workstations_stop_workstation_async.py | 56 - ...ated_workstations_stop_workstation_sync.py | 56 - ...d_workstations_update_workstation_async.py | 55 - ...ations_update_workstation_cluster_async.py | 55 - ...tations_update_workstation_cluster_sync.py | 55 - ...tations_update_workstation_config_async.py | 55 - ...stations_update_workstation_config_sync.py | 55 - ...ed_workstations_update_workstation_sync.py | 55 - .../fixup_workstations_v1beta_keywords.py | 195 - .../google-cloud-workstations/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/workstations_v1beta/__init__.py | 16 - .../workstations_v1beta/test_workstations.py | 17999 ---------------- .../google-geo-type/viewport-py/.coveragerc | 13 - .../google-geo-type/viewport-py/.flake8 | 33 - .../google-geo-type/viewport-py/MANIFEST.in | 2 - .../google-geo-type/viewport-py/README.rst | 49 - .../viewport-py/docs/_static/custom.css | 3 - .../google-geo-type/viewport-py/docs/conf.py | 376 - .../viewport-py/docs/index.rst | 7 - .../viewport-py/docs/type/services_.rst | 4 - .../viewport-py/docs/type/types_.rst | 6 - .../viewport-py/google/geo/type/__init__.py | 26 - .../google/geo/type/gapic_metadata.json | 7 - .../google/geo/type/gapic_version.py | 16 - .../viewport-py/google/geo/type/py.typed | 2 - .../google/geo/type/services/__init__.py | 15 - .../google/geo/type/types/__init__.py | 22 - .../google/geo/type/types/viewport.py | 84 - .../google-geo-type/viewport-py/mypy.ini | 3 - .../google-geo-type/viewport-py/noxfile.py | 280 - .../scripts/fixup_type_keywords.py | 175 - .../google-geo-type/viewport-py/setup.py | 98 - .../viewport-py/testing/constraints-3.10.txt | 6 - .../viewport-py/testing/constraints-3.11.txt | 6 - .../viewport-py/testing/constraints-3.12.txt | 6 - .../viewport-py/testing/constraints-3.7.txt | 10 - .../viewport-py/testing/constraints-3.8.txt | 6 - .../viewport-py/testing/constraints-3.9.txt | 6 - .../viewport-py/tests/__init__.py | 16 - .../viewport-py/tests/unit/__init__.py | 16 - .../viewport-py/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/type/__init__.py | 16 - .../v1/.coveragerc | 13 - .../google-maps-addressvalidation/v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../address_validation.rst | 6 - .../docs/addressvalidation_v1/services_.rst | 6 - .../v1/docs/addressvalidation_v1/types_.rst | 6 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../google/maps/addressvalidation/__init__.py | 55 - .../maps/addressvalidation/gapic_version.py | 16 - .../v1/google/maps/addressvalidation/py.typed | 2 - .../maps/addressvalidation_v1/__init__.py | 56 - .../addressvalidation_v1/gapic_metadata.json | 58 - .../addressvalidation_v1/gapic_version.py | 16 - .../google/maps/addressvalidation_v1/py.typed | 2 - .../addressvalidation_v1/services/__init__.py | 15 - .../services/address_validation/__init__.py | 22 - .../address_validation/async_client.py | 392 - .../services/address_validation/client.py | 740 - .../address_validation/transports/README.rst | 9 - .../address_validation/transports/__init__.py | 38 - .../address_validation/transports/base.py | 167 - .../address_validation/transports/grpc.py | 301 - .../transports/grpc_asyncio.py | 327 - .../address_validation/transports/rest.py | 391 - .../transports/rest_base.py | 185 - .../addressvalidation_v1/types/__init__.py | 56 - .../addressvalidation_v1/types/address.py | 244 - .../types/address_validation_service.py | 413 - .../addressvalidation_v1/types/geocode.py | 132 - .../addressvalidation_v1/types/metadata_.py | 76 - .../addressvalidation_v1/types/usps_data.py | 493 - .../google-maps-addressvalidation/v1/mypy.ini | 3 - .../v1/noxfile.py | 280 - ...ation_provide_validation_feedback_async.py | 53 - ...dation_provide_validation_feedback_sync.py | 53 - ...dress_validation_validate_address_async.py | 51 - ...ddress_validation_validate_address_sync.py | 51 - ...data_google.maps.addressvalidation.v1.json | 321 - .../fixup_addressvalidation_v1_keywords.py | 177 - .../google-maps-addressvalidation/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.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/addressvalidation_v1/__init__.py | 16 - .../test_address_validation.py | 2364 -- .../google-maps-areainsights/v1/.coveragerc | 13 - .../google-maps-areainsights/v1/.flake8 | 33 - .../google-maps-areainsights/v1/MANIFEST.in | 2 - .../google-maps-areainsights/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/areainsights_v1/area_insights.rst | 6 - .../v1/docs/areainsights_v1/services_.rst | 6 - .../v1/docs/areainsights_v1/types_.rst | 6 - .../google-maps-areainsights/v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../v1/google/maps/areainsights/__init__.py | 47 - .../google/maps/areainsights/gapic_version.py | 16 - .../v1/google/maps/areainsights/py.typed | 2 - .../google/maps/areainsights_v1/__init__.py | 48 - .../maps/areainsights_v1/gapic_metadata.json | 43 - .../maps/areainsights_v1/gapic_version.py | 16 - .../v1/google/maps/areainsights_v1/py.typed | 2 - .../maps/areainsights_v1/services/__init__.py | 15 - .../services/area_insights/__init__.py | 22 - .../services/area_insights/async_client.py | 321 - .../services/area_insights/client.py | 678 - .../area_insights/transports/README.rst | 9 - .../area_insights/transports/__init__.py | 38 - .../services/area_insights/transports/base.py | 163 - .../services/area_insights/transports/grpc.py | 282 - .../area_insights/transports/grpc_asyncio.py | 312 - .../services/area_insights/transports/rest.py | 275 - .../area_insights/transports/rest_base.py | 138 - .../maps/areainsights_v1/types/__init__.py | 40 - .../types/area_insights_service.py | 512 - .../google-maps-areainsights/v1/mypy.ini | 3 - .../google-maps-areainsights/v1/noxfile.py | 280 - ...ed_area_insights_compute_insights_async.py | 52 - ...ted_area_insights_compute_insights_sync.py | 52 - ..._metadata_google.maps.areainsights.v1.json | 168 - .../scripts/fixup_areainsights_v1_keywords.py | 176 - .../google-maps-areainsights/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.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 - .../unit/gapic/areainsights_v1/__init__.py | 16 - .../areainsights_v1/test_area_insights.py | 1935 -- .../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 - .../delivery_service.rst | 10 - .../fleetengine_delivery_v1/services_.rst | 6 - .../docs/fleetengine_delivery_v1/types_.rst | 6 - .../v1/docs/index.rst | 7 - .../maps/fleetengine_delivery/__init__.py | 81 - .../fleetengine_delivery/gapic_version.py | 16 - .../google/maps/fleetengine_delivery/py.typed | 2 - .../maps/fleetengine_delivery_v1/__init__.py | 82 - .../gapic_metadata.json | 178 - .../fleetengine_delivery_v1/gapic_version.py | 16 - .../maps/fleetengine_delivery_v1/py.typed | 2 - .../services/__init__.py | 15 - .../services/delivery_service/__init__.py | 22 - .../services/delivery_service/async_client.py | 1558 -- .../services/delivery_service/client.py | 1924 -- .../services/delivery_service/pagers.py | 299 - .../delivery_service/transports/README.rst | 9 - .../delivery_service/transports/__init__.py | 38 - .../delivery_service/transports/base.py | 373 - .../delivery_service/transports/grpc.py | 516 - .../transports/grpc_asyncio.py | 672 - .../delivery_service/transports/rest.py | 1318 -- .../delivery_service/transports/rest_base.py | 514 - .../fleetengine_delivery_v1/types/__init__.py | 84 - .../fleetengine_delivery_v1/types/common.py | 471 - .../types/delivery_api.py | 603 - .../types/delivery_vehicles.py | 414 - .../fleetengine_delivery_v1/types/header.py | 168 - .../types/task_tracking_info.py | 166 - .../fleetengine_delivery_v1/types/tasks.py | 473 - .../v1/mypy.ini | 3 - .../v1/noxfile.py | 280 - ...livery_service_batch_create_tasks_async.py | 59 - ...elivery_service_batch_create_tasks_sync.py | 59 - ...y_service_create_delivery_vehicle_async.py | 53 - ...ry_service_create_delivery_vehicle_sync.py | 53 - ...ated_delivery_service_create_task_async.py | 58 - ...rated_delivery_service_create_task_sync.py | 58 - ...very_service_get_delivery_vehicle_async.py | 52 - ...ivery_service_get_delivery_vehicle_sync.py | 52 - ...nerated_delivery_service_get_task_async.py | 52 - ...enerated_delivery_service_get_task_sync.py | 52 - ...ry_service_get_task_tracking_info_async.py | 52 - ...ery_service_get_task_tracking_info_sync.py | 52 - ...ry_service_list_delivery_vehicles_async.py | 53 - ...ery_service_list_delivery_vehicles_sync.py | 53 - ...rated_delivery_service_list_tasks_async.py | 53 - ...erated_delivery_service_list_tasks_sync.py | 53 - ...y_service_update_delivery_vehicle_async.py | 51 - ...ry_service_update_delivery_vehicle_sync.py | 51 - ...ated_delivery_service_update_task_async.py | 56 - ...rated_delivery_service_update_task_sync.py | 56 - ...metadata_maps.fleetengine.delivery.v1.json | 1665 -- .../fixup_fleetengine_delivery_v1_keywords.py | 185 - .../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.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/fleetengine_delivery_v1/__init__.py | 16 - .../test_delivery_service.py | 9124 -------- .../google-maps-fleetengine/v1/.coveragerc | 13 - .../google-maps-fleetengine/v1/.flake8 | 33 - .../google-maps-fleetengine/v1/MANIFEST.in | 2 - .../google-maps-fleetengine/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-maps-fleetengine/v1/docs/conf.py | 376 - .../v1/docs/fleetengine_v1/services_.rst | 7 - .../v1/docs/fleetengine_v1/trip_service.rst | 10 - .../v1/docs/fleetengine_v1/types_.rst | 6 - .../docs/fleetengine_v1/vehicle_service.rst | 10 - .../google-maps-fleetengine/v1/docs/index.rst | 7 - .../v1/google/maps/fleetengine/__init__.py | 123 - .../google/maps/fleetengine/gapic_version.py | 16 - .../v1/google/maps/fleetengine/py.typed | 2 - .../v1/google/maps/fleetengine_v1/__init__.py | 124 - .../maps/fleetengine_v1/gapic_metadata.json | 147 - .../maps/fleetengine_v1/gapic_version.py | 16 - .../v1/google/maps/fleetengine_v1/py.typed | 2 - .../maps/fleetengine_v1/services/__init__.py | 15 - .../services/trip_service/__init__.py | 22 - .../services/trip_service/async_client.py | 675 - .../services/trip_service/client.py | 1030 - .../services/trip_service/pagers.py | 163 - .../trip_service/transports/README.rst | 9 - .../trip_service/transports/__init__.py | 33 - .../services/trip_service/transports/base.py | 248 - .../services/trip_service/transports/grpc.py | 377 - .../trip_service/transports/grpc_asyncio.py | 454 - .../services/vehicle_service/__init__.py | 22 - .../services/vehicle_service/async_client.py | 827 - .../services/vehicle_service/client.py | 1182 - .../services/vehicle_service/pagers.py | 163 - .../vehicle_service/transports/README.rst | 9 - .../vehicle_service/transports/__init__.py | 33 - .../vehicle_service/transports/base.py | 270 - .../vehicle_service/transports/grpc.py | 455 - .../transports/grpc_asyncio.py | 546 - .../maps/fleetengine_v1/types/__init__.py | 124 - .../maps/fleetengine_v1/types/fleetengine.py | 628 - .../maps/fleetengine_v1/types/header.py | 168 - .../maps/fleetengine_v1/types/traffic.py | 108 - .../maps/fleetengine_v1/types/trip_api.py | 460 - .../google/maps/fleetengine_v1/types/trips.py | 490 - .../maps/fleetengine_v1/types/vehicle_api.py | 1050 - .../maps/fleetengine_v1/types/vehicles.py | 580 - .../google-maps-fleetengine/v1/mypy.ini | 3 - .../google-maps-fleetengine/v1/noxfile.py | 280 - ...enerated_trip_service_create_trip_async.py | 53 - ...generated_trip_service_create_trip_sync.py | 53 - ...1_generated_trip_service_get_trip_async.py | 52 - ...v1_generated_trip_service_get_trip_sync.py | 52 - ...trip_service_report_billable_trip_async.py | 51 - ..._trip_service_report_billable_trip_sync.py | 51 - ...nerated_trip_service_search_trips_async.py | 53 - ...enerated_trip_service_search_trips_sync.py | 53 - ...enerated_trip_service_update_trip_async.py | 52 - ...generated_trip_service_update_trip_sync.py | 52 - ...ed_vehicle_service_create_vehicle_async.py | 53 - ...ted_vehicle_service_create_vehicle_sync.py | 53 - ...rated_vehicle_service_get_vehicle_async.py | 52 - ...erated_vehicle_service_get_vehicle_sync.py | 52 - ...ted_vehicle_service_list_vehicles_async.py | 54 - ...ated_vehicle_service_list_vehicles_sync.py | 54 - ...d_vehicle_service_search_vehicles_async.py | 57 - ...ed_vehicle_service_search_vehicles_sync.py | 57 - ...ed_vehicle_service_update_vehicle_async.py | 52 - ...service_update_vehicle_attributes_async.py | 56 - ..._service_update_vehicle_attributes_sync.py | 56 - ...ted_vehicle_service_update_vehicle_sync.py | 52 - .../snippet_metadata_maps.fleetengine.v1.json | 1692 -- .../scripts/fixup_fleetengine_v1_keywords.py | 186 - .../google-maps-fleetengine/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.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/fleetengine_v1/__init__.py | 16 - .../gapic/fleetengine_v1/test_trip_service.py | 3085 --- .../fleetengine_v1/test_vehicle_service.py | 3340 --- .../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 | 907 - .../services/maps_platform_datasets/client.py | 1258 -- .../services/maps_platform_datasets/pagers.py | 299 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../maps_platform_datasets/transports/base.py | 254 - .../maps_platform_datasets/transports/grpc.py | 403 - .../transports/grpc_asyncio.py | 476 - .../maps_platform_datasets/transports/rest.py | 787 - .../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.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 | 6146 ------ .../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 | 81 - .../v1/google/maps/places/gapic_version.py | 16 - .../v1/google/maps/places/py.typed | 2 - .../v1/google/maps/places_v1/__init__.py | 82 - .../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 | 691 - .../maps/places_v1/services/places/client.py | 1073 - .../services/places/transports/README.rst | 9 - .../services/places/transports/__init__.py | 38 - .../services/places/transports/base.py | 210 - .../services/places/transports/grpc.py | 380 - .../places/transports/grpc_asyncio.py | 421 - .../services/places/transports/rest.py | 708 - .../services/places/transports/rest_base.py | 307 - .../google/maps/places_v1/types/__init__.py | 104 - .../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 | 1208 -- .../maps/places_v1/types/places_service.py | 1316 -- .../google/maps/places_v1/types/polyline.py | 62 - .../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 | 83 - .../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.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 | 4498 ---- .../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 | 548 - .../services/route_optimization/client.py | 898 - .../route_optimization/transports/README.rst | 9 - .../route_optimization/transports/__init__.py | 38 - .../route_optimization/transports/base.py | 198 - .../route_optimization/transports/grpc.py | 394 - .../transports/grpc_asyncio.py | 434 - .../route_optimization/transports/rest.py | 547 - .../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.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 | 2749 --- .../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 | 113 - .../v2/google/maps/routing/gapic_version.py | 16 - .../v2/google/maps/routing/py.typed | 2 - .../v2/google/maps/routing_v2/__init__.py | 114 - .../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 | 460 - .../maps/routing_v2/services/routes/client.py | 808 - .../services/routes/transports/README.rst | 9 - .../services/routes/transports/__init__.py | 38 - .../services/routes/transports/base.py | 167 - .../services/routes/transports/grpc.py | 369 - .../routes/transports/grpc_asyncio.py | 395 - .../services/routes/transports/rest.py | 384 - .../services/routes/transports/rest_base.py | 185 - .../google/maps/routing_v2/types/__init__.py | 150 - .../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 - .../v2/google/maps/routing_v2/types/route.py | 787 - .../maps/routing_v2/types/route_label.py | 58 - .../maps/routing_v2/types/route_modifiers.py | 98 - .../routing_v2/types/route_travel_mode.py | 63 - .../maps/routing_v2/types/routes_service.py | 713 - .../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.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 | 2389 -- .../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 | 521 - .../maps/solar_v1/services/solar/client.py | 869 - .../services/solar/transports/README.rst | 9 - .../services/solar/transports/__init__.py | 38 - .../services/solar/transports/base.py | 210 - .../services/solar/transports/grpc.py | 327 - .../services/solar/transports/grpc_asyncio.py | 385 - .../services/solar/transports/rest.py | 548 - .../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 | 2921 --- .../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 | 357 - .../services/account_issue_service/client.py | 722 - .../services/account_issue_service/pagers.py | 162 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../account_issue_service/transports/base.py | 154 - .../account_issue_service/transports/grpc.py | 271 - .../transports/grpc_asyncio.py | 292 - .../account_issue_service/transports/rest.py | 272 - .../transports/rest_base.py | 128 - .../services/account_tax_service/__init__.py | 22 - .../account_tax_service/async_client.py | 588 - .../services/account_tax_service/client.py | 942 - .../services/account_tax_service/pagers.py | 162 - .../account_tax_service/transports/README.rst | 9 - .../transports/__init__.py | 38 - .../account_tax_service/transports/base.py | 183 - .../account_tax_service/transports/grpc.py | 331 - .../transports/grpc_asyncio.py | 362 - .../account_tax_service/transports/rest.py | 502 - .../transports/rest_base.py | 213 - .../services/accounts_service/__init__.py | 22 - .../services/accounts_service/async_client.py | 852 - .../services/accounts_service/client.py | 1223 -- .../services/accounts_service/pagers.py | 297 - .../accounts_service/transports/README.rst | 9 - .../accounts_service/transports/__init__.py | 38 - .../accounts_service/transports/base.py | 225 - .../accounts_service/transports/grpc.py | 425 - .../transports/grpc_asyncio.py | 471 - .../accounts_service/transports/rest.py | 776 - .../accounts_service/transports/rest_base.py | 326 - .../autofeed_settings_service/__init__.py | 22 - .../autofeed_settings_service/async_client.py | 461 - .../autofeed_settings_service/client.py | 816 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 298 - .../transports/grpc_asyncio.py | 324 - .../transports/rest.py | 388 - .../transports/rest_base.py | 175 - .../business_identity_service/__init__.py | 22 - .../business_identity_service/async_client.py | 456 - .../business_identity_service/client.py | 811 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 299 - .../transports/grpc_asyncio.py | 325 - .../transports/rest.py | 386 - .../transports/rest_base.py | 175 - .../business_info_service/__init__.py | 22 - .../business_info_service/async_client.py | 456 - .../services/business_info_service/client.py | 811 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../business_info_service/transports/base.py | 168 - .../business_info_service/transports/grpc.py | 297 - .../transports/grpc_asyncio.py | 323 - .../business_info_service/transports/rest.py | 383 - .../transports/rest_base.py | 175 - .../email_preferences_service/__init__.py | 22 - .../email_preferences_service/async_client.py | 479 - .../email_preferences_service/client.py | 834 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 314 - .../transports/grpc_asyncio.py | 340 - .../transports/rest.py | 394 - .../transports/rest_base.py | 175 - .../services/homepage_service/__init__.py | 22 - .../services/homepage_service/async_client.py | 622 - .../services/homepage_service/client.py | 977 - .../homepage_service/transports/README.rst | 9 - .../homepage_service/transports/__init__.py | 38 - .../homepage_service/transports/base.py | 197 - .../homepage_service/transports/grpc.py | 363 - .../transports/grpc_asyncio.py | 399 - .../homepage_service/transports/rest.py | 594 - .../homepage_service/transports/rest_base.py | 270 - .../online_return_policy_service/__init__.py | 22 - .../async_client.py | 469 - .../online_return_policy_service/client.py | 824 - .../online_return_policy_service/pagers.py | 162 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 303 - .../transports/grpc_asyncio.py | 329 - .../transports/rest.py | 392 - .../transports/rest_base.py | 165 - .../services/programs_service/__init__.py | 22 - .../services/programs_service/async_client.py | 702 - .../services/programs_service/client.py | 1055 - .../services/programs_service/pagers.py | 162 - .../programs_service/transports/README.rst | 9 - .../programs_service/transports/__init__.py | 38 - .../programs_service/transports/base.py | 196 - .../programs_service/transports/grpc.py | 361 - .../transports/grpc_asyncio.py | 397 - .../programs_service/transports/rest.py | 633 - .../programs_service/transports/rest_base.py | 259 - .../services/regions_service/__init__.py | 22 - .../services/regions_service/async_client.py | 806 - .../services/regions_service/client.py | 1167 - .../services/regions_service/pagers.py | 162 - .../regions_service/transports/README.rst | 9 - .../regions_service/transports/__init__.py | 38 - .../regions_service/transports/base.py | 211 - .../regions_service/transports/grpc.py | 383 - .../transports/grpc_asyncio.py | 424 - .../regions_service/transports/rest.py | 698 - .../regions_service/transports/rest_base.py | 297 - .../shipping_settings_service/__init__.py | 22 - .../shipping_settings_service/async_client.py | 430 - .../shipping_settings_service/client.py | 786 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 299 - .../transports/grpc_asyncio.py | 325 - .../transports/rest.py | 385 - .../transports/rest_base.py | 175 - .../__init__.py | 22 - .../async_client.py | 504 - .../client.py | 877 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 168 - .../transports/grpc.py | 299 - .../transports/grpc_asyncio.py | 325 - .../transports/rest.py | 437 - .../transports/rest_base.py | 165 - .../terms_of_service_service/__init__.py | 22 - .../terms_of_service_service/async_client.py | 509 - .../terms_of_service_service/client.py | 873 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 183 - .../transports/grpc.py | 327 - .../transports/grpc_asyncio.py | 358 - .../transports/rest.py | 458 - .../transports/rest_base.py | 203 - .../services/user_service/__init__.py | 22 - .../services/user_service/async_client.py | 786 - .../services/user_service/client.py | 1147 - .../services/user_service/pagers.py | 162 - .../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 | 379 - .../user_service/transports/grpc_asyncio.py | 420 - .../services/user_service/transports/rest.py | 677 - .../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.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 | 2424 --- .../test_account_tax_service.py | 3791 ---- .../test_accounts_service.py | 5618 ----- .../test_autofeed_settings_service.py | 2887 --- .../test_business_identity_service.py | 2873 --- .../test_business_info_service.py | 2891 --- .../test_email_preferences_service.py | 2875 --- .../test_homepage_service.py | 3946 ---- .../test_online_return_policy_service.py | 3115 --- .../test_programs_service.py | 4414 ---- .../test_regions_service.py | 5190 ----- .../test_shipping_settings_service.py | 2731 --- ...erms_of_service_agreement_state_service.py | 2851 --- .../test_terms_of_service_service.py | 3324 --- .../test_user_service.py | 5200 ----- .../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 | 894 - .../conversion_sources_service/client.py | 1246 -- .../conversion_sources_service/pagers.py | 162 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 225 - .../transports/grpc.py | 411 - .../transports/grpc_asyncio.py | 457 - .../transports/rest.py | 803 - .../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 | 5696 ----- .../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 | 879 - .../services/data_sources_service/client.py | 1231 -- .../services/data_sources_service/pagers.py | 162 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../data_sources_service/transports/base.py | 225 - .../data_sources_service/transports/grpc.py | 416 - .../transports/grpc_asyncio.py | 462 - .../data_sources_service/transports/rest.py | 772 - .../transports/rest_base.py | 344 - .../services/file_uploads_service/__init__.py | 22 - .../file_uploads_service/async_client.py | 348 - .../services/file_uploads_service/client.py | 704 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../file_uploads_service/transports/base.py | 154 - .../file_uploads_service/transports/grpc.py | 271 - .../transports/grpc_asyncio.py | 292 - .../file_uploads_service/transports/rest.py | 280 - .../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 | 5682 ----- .../test_file_uploads_service.py | 2177 -- .../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 | 557 - .../local_inventory_service/client.py | 912 - .../local_inventory_service/pagers.py | 162 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 183 - .../transports/grpc.py | 342 - .../transports/grpc_asyncio.py | 373 - .../transports/rest.py | 468 - .../transports/rest_base.py | 213 - .../regional_inventory_service/__init__.py | 22 - .../async_client.py | 563 - .../regional_inventory_service/client.py | 918 - .../regional_inventory_service/pagers.py | 162 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 183 - .../transports/grpc.py | 343 - .../transports/grpc_asyncio.py | 374 - .../transports/rest.py | 472 - .../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.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 | 3659 ---- .../test_regional_inventory_service.py | 3631 ---- .../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 | 333 - .../services/lfp_inventory_service/client.py | 690 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../lfp_inventory_service/transports/base.py | 154 - .../lfp_inventory_service/transports/grpc.py | 274 - .../transports/grpc_asyncio.py | 295 - .../lfp_inventory_service/transports/rest.py | 277 - .../transports/rest_base.py | 138 - .../services/lfp_sale_service/__init__.py | 22 - .../services/lfp_sale_service/async_client.py | 333 - .../services/lfp_sale_service/client.py | 690 - .../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 | 272 - .../transports/grpc_asyncio.py | 293 - .../lfp_sale_service/transports/rest.py | 278 - .../lfp_sale_service/transports/rest_base.py | 138 - .../services/lfp_store_service/__init__.py | 22 - .../lfp_store_service/async_client.py | 684 - .../services/lfp_store_service/client.py | 1037 - .../services/lfp_store_service/pagers.py | 162 - .../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 | 354 - .../transports/grpc_asyncio.py | 390 - .../lfp_store_service/transports/rest.py | 584 - .../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.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 | 2152 -- .../test_lfp_sale_service.py | 2134 -- .../test_lfp_store_service.py | 4555 ---- .../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 | 804 - .../notifications_api_service/client.py | 1156 - .../notifications_api_service/pagers.py | 162 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 211 - .../transports/grpc.py | 398 - .../transports/grpc_asyncio.py | 439 - .../transports/rest.py | 691 - .../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.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 | 5172 ----- .../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 - .../product_inputs_service.rst | 6 - .../products_service.rst | 10 - .../merchant_products_v1beta/services_.rst | 7 - .../docs/merchant_products_v1beta/types_.rst | 6 - .../shopping/merchant_products/__init__.py | 87 - .../merchant_products/gapic_version.py | 16 - .../shopping/merchant_products/py.typed | 2 - .../merchant_products_v1beta/__init__.py | 88 - .../gapic_metadata.json | 107 - .../merchant_products_v1beta/gapic_version.py | 16 - .../merchant_products_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../product_inputs_service/__init__.py | 22 - .../product_inputs_service/async_client.py | 462 - .../services/product_inputs_service/client.py | 827 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../product_inputs_service/transports/base.py | 169 - .../product_inputs_service/transports/grpc.py | 309 - .../transports/grpc_asyncio.py | 335 - .../product_inputs_service/transports/rest.py | 384 - .../transports/rest_base.py | 176 - .../services/products_service/__init__.py | 22 - .../services/products_service/async_client.py | 490 - .../services/products_service/client.py | 845 - .../services/products_service/pagers.py | 162 - .../products_service/transports/README.rst | 9 - .../products_service/transports/__init__.py | 38 - .../products_service/transports/base.py | 168 - .../products_service/transports/grpc.py | 308 - .../transports/grpc_asyncio.py | 334 - .../products_service/transports/rest.py | 398 - .../products_service/transports/rest_base.py | 165 - .../types/__init__.py | 80 - .../types/productinputs.py | 220 - .../types/products.py | 240 - .../types/products_common.py | 1906 -- .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 280 - ...puts_service_delete_product_input_async.py | 51 - ...nputs_service_delete_product_input_sync.py | 51 - ...puts_service_insert_product_input_async.py | 60 - ...nputs_service_insert_product_input_sync.py | 60 - ...ated_products_service_get_product_async.py | 52 - ...rated_products_service_get_product_sync.py | 52 - ...ed_products_service_list_products_async.py | 53 - ...ted_products_service_list_products_sync.py | 53 - ...gle.shopping.merchant.products.v1beta.json | 645 - ...fixup_merchant_products_v1beta_keywords.py | 179 - .../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.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_products_v1beta/__init__.py | 16 - .../test_product_inputs_service.py | 2788 --- .../test_products_service.py | 3096 --- .../google-cloud-websecurityscanner/.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../web_security_scanner/transports/rest.py | 2 +- .../web_security_scanner/transports/rest.py | 2 +- .../web_security_scanner/transports/rest.py | 2 +- .../noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../google-cloud-websecurityscanner/setup.py | 2 + .../testing/constraints-3.13.txt | 0 packages/google-cloud-workflows/.flake8 | 2 +- .../google-cloud-workflows/CONTRIBUTING.rst | 10 +- packages/google-cloud-workflows/MANIFEST.in | 2 +- packages/google-cloud-workflows/docs/conf.py | 2 +- .../services/workflows/transports/rest.py | 2 +- .../services/workflows/transports/rest.py | 2 +- packages/google-cloud-workflows/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- packages/google-cloud-workflows/setup.py | 2 + .../testing/constraints-3.13.txt | 0 packages/google-cloud-workstations/.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../google-cloud-workstations/MANIFEST.in | 2 +- .../google-cloud-workstations/docs/conf.py | 2 +- .../services/workstations/transports/rest.py | 2 +- .../services/workstations/transports/rest.py | 2 +- packages/google-cloud-workstations/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- packages/google-cloud-workstations/setup.py | 2 + .../testing/constraints-3.13.txt | 0 packages/google-geo-type/.flake8 | 2 +- packages/google-geo-type/CONTRIBUTING.rst | 10 +- packages/google-geo-type/MANIFEST.in | 2 +- packages/google-geo-type/docs/conf.py | 2 +- packages/google-geo-type/docs/index.rst | 1 + packages/google-geo-type/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- packages/google-geo-type/setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../google-maps-addressvalidation/.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../google-maps-addressvalidation/MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../address_validation/transports/rest.py | 2 +- .../google-maps-addressvalidation/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../google-maps-addressvalidation/setup.py | 2 + .../testing/constraints-3.13.txt | 0 packages/google-maps-areainsights/.flake8 | 2 +- .../google-maps-areainsights/CONTRIBUTING.rst | 10 +- packages/google-maps-areainsights/MANIFEST.in | 2 +- .../google-maps-areainsights/docs/conf.py | 2 +- .../services/area_insights/transports/rest.py | 2 +- packages/google-maps-areainsights/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- packages/google-maps-areainsights/setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../google-maps-fleetengine-delivery/.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../delivery_service/transports/rest.py | 2 +- .../maps-fleetengine-delivery-v1-py.tar.gz | 0 .../noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../google-maps-fleetengine-delivery/setup.py | 2 + .../testing/constraints-3.13.txt | 0 packages/google-maps-fleetengine/.flake8 | 2 +- .../google-maps-fleetengine/CONTRIBUTING.rst | 10 +- packages/google-maps-fleetengine/MANIFEST.in | 2 +- packages/google-maps-fleetengine/docs/conf.py | 2 +- packages/google-maps-fleetengine/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- packages/google-maps-fleetengine/setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../google-maps-mapsplatformdatasets/.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../maps_platform_datasets/transports/rest.py | 2 +- .../noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../google-maps-mapsplatformdatasets/setup.py | 2 + .../testing/constraints-3.13.txt | 0 packages/google-maps-places/.flake8 | 2 +- packages/google-maps-places/CONTRIBUTING.rst | 10 +- packages/google-maps-places/MANIFEST.in | 2 +- packages/google-maps-places/docs/conf.py | 2 +- .../services/places/transports/rest.py | 2 +- packages/google-maps-places/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- packages/google-maps-places/setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../google-maps-routeoptimization/.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../google-maps-routeoptimization/MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../route_optimization/transports/rest.py | 2 +- .../google-maps-routeoptimization/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../google-maps-routeoptimization/setup.py | 2 + .../testing/constraints-3.13.txt | 0 packages/google-maps-routing/.flake8 | 2 +- packages/google-maps-routing/CONTRIBUTING.rst | 10 +- packages/google-maps-routing/MANIFEST.in | 2 +- packages/google-maps-routing/docs/conf.py | 2 +- .../services/routes/transports/rest.py | 2 +- packages/google-maps-routing/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- packages/google-maps-routing/setup.py | 2 + .../testing/constraints-3.13.txt | 0 packages/google-maps-solar/.flake8 | 2 +- packages/google-maps-solar/CONTRIBUTING.rst | 10 +- packages/google-maps-solar/MANIFEST.in | 2 +- packages/google-maps-solar/docs/conf.py | 2 +- .../services/solar/transports/rest.py | 2 +- packages/google-maps-solar/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- packages/google-maps-solar/setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../google-shopping-merchant-accounts/.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../account_issue_service/transports/rest.py | 2 +- .../account_tax_service/transports/rest.py | 2 +- .../accounts_service/transports/rest.py | 2 +- .../transports/rest.py | 2 +- .../transports/rest.py | 2 +- .../business_info_service/transports/rest.py | 2 +- .../transports/rest.py | 2 +- .../homepage_service/transports/rest.py | 2 +- .../transports/rest.py | 2 +- .../programs_service/transports/rest.py | 2 +- .../regions_service/transports/rest.py | 2 +- .../transports/rest.py | 2 +- .../transports/rest.py | 2 +- .../transports/rest.py | 2 +- .../services/user_service/transports/rest.py | 2 +- .../merchant-accounts-v1beta-py.tar.gz | Bin .../noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../transports/rest.py | 2 +- .../noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../data_sources_service/transports/rest.py | 2 +- .../file_uploads_service/transports/rest.py | 2 +- .../noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../transports/rest.py | 2 +- .../transports/rest.py | 2 +- .../noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../setup.py | 2 + .../testing/constraints-3.13.txt | 0 packages/google-shopping-merchant-lfp/.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../google-shopping-merchant-lfp/MANIFEST.in | 2 +- .../google-shopping-merchant-lfp/docs/conf.py | 2 +- .../lfp_inventory_service/transports/rest.py | 2 +- .../lfp_sale_service/transports/rest.py | 2 +- .../lfp_store_service/transports/rest.py | 2 +- .../google-shopping-merchant-lfp/noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../google-shopping-merchant-lfp/setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../transports/rest.py | 2 +- .../noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../setup.py | 2 + .../testing/constraints-3.13.txt | 0 .../google-shopping-merchant-products/.flake8 | 2 +- .../CONTRIBUTING.rst | 10 +- .../MANIFEST.in | 2 +- .../docs/conf.py | 2 +- .../product_inputs_service/transports/rest.py | 2 +- .../products_service/transports/rest.py | 2 +- .../noxfile.py | 20 +- .../scripts/decrypt-secrets.sh | 2 +- .../setup.py | 2 + .../testing/constraints-3.13.txt | 0 2153 files changed, 562 insertions(+), 551193 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/web_security_scanner.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/py.typed delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_log.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/scripts/fixup_websecurityscanner_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.flake8 delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/README.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/services_.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/types_.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/py.typed delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/setup.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/README.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/py.typed delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/py.typed delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/setup.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/executions.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/workflows.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/py.typed delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/async_client.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/client.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/pagers.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/executions.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/py.typed delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/async_client.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/client.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/pagers.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/workflows.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_executions_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_workflows_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/test_executions.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/test_workflows.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/README.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/executions.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/workflows.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/py.typed delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/py.typed delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/async_client.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/client.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/pagers.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/executions.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/py.typed delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/py.typed delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/async_client.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/client.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/pagers.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/workflows.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_async.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_sync.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_executions_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_workflows_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/setup.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/test_executions.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/test_workflows.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/README.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/setup.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/.coveragerc delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/.flake8 delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/MANIFEST.in delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/README.rst delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/conf.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/index.rst delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/type/services_.rst delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/docs/type/types_.rst delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/__init__.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_metadata.json delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_version.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/py.typed delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/services/__init__.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/__init__.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/viewport.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/mypy.ini delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/noxfile.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/scripts/fixup_type_keywords.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/setup.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/tests/__init__.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/type/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/address_validation.rst delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/py.typed delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/async_client.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/client.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/base.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest_base.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address_validation_service.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/geocode.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/metadata_.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/usps_data.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_async.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_sync.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/scripts/fixup_addressvalidation_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/test_address_validation.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/area_insights.rst delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/py.typed delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/async_client.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/client.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/base.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest_base.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/area_insights_service.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_async.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_sync.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/snippet_metadata_google.maps.areainsights.v1.json delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/scripts/fixup_areainsights_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/test_area_insights.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py 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.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/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.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.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/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.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.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.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.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.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-products/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/product_inputs_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/products_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/productinputs.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products_common.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.products.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/scripts/fixup_merchant_products_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_product_inputs_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_products_service.py rename {owl-bot-staging/google-cloud-websecurityscanner/v1 => packages/google-cloud-websecurityscanner}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-cloud-websecurityscanner/v1alpha => packages/google-cloud-workflows}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-cloud-workstations/v1 => packages/google-cloud-workstations}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-cloud-websecurityscanner/v1beta => packages/google-geo-type}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-maps-addressvalidation/v1 => packages/google-maps-addressvalidation}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-cloud-workflows/v1 => packages/google-maps-areainsights}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-maps-fleetengine-delivery/v1 => packages/google-maps-fleetengine-delivery}/maps-fleetengine-delivery-v1-py.tar.gz (100%) rename {owl-bot-staging/google-maps-fleetengine-delivery/v1 => packages/google-maps-fleetengine-delivery}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-maps-fleetengine/v1 => packages/google-maps-fleetengine}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-cloud-workflows/v1beta => packages/google-maps-mapsplatformdatasets}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-maps-places/v1 => packages/google-maps-places}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-geo-type/viewport-py => packages/google-maps-routeoptimization}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-maps-routing/v2 => packages/google-maps-routing}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-maps-areainsights/v1 => packages/google-maps-solar}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta => packages/google-shopping-merchant-accounts}/merchant-accounts-v1beta-py.tar.gz (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta => packages/google-shopping-merchant-accounts}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-maps-mapsplatformdatasets/v1 => packages/google-shopping-merchant-conversions}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-maps-routeoptimization/v1 => packages/google-shopping-merchant-datasources}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1beta => packages/google-shopping-merchant-inventories}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-shopping-merchant-lfp/v1beta => packages/google-shopping-merchant-lfp}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-shopping-merchant-notifications/v1beta => packages/google-shopping-merchant-notifications}/testing/constraints-3.13.txt (100%) rename {owl-bot-staging/google-shopping-merchant-products/v1beta => packages/google-shopping-merchant-products}/testing/constraints-3.13.txt (100%) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/.coveragerc b/owl-bot-staging/google-cloud-websecurityscanner/v1/.coveragerc deleted file mode 100644 index 085a92b30288..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/websecurityscanner/__init__.py - google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1/.flake8 b/owl-bot-staging/google-cloud-websecurityscanner/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/MANIFEST.in b/owl-bot-staging/google-cloud-websecurityscanner/v1/MANIFEST.in deleted file mode 100644 index 9d26e3bccd4a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/websecurityscanner *.py -recursive-include google/cloud/websecurityscanner_v1 *.py diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/README.rst deleted file mode 100644 index 4de4c103eee6..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Websecurityscanner 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 Cloud Websecurityscanner 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-cloud-websecurityscanner/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/docs/conf.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/conf.py deleted file mode 100644 index 40ff11b301ef..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner 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-cloud-websecurityscanner" -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 Cloud 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-cloud-websecurityscanner-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-cloud-websecurityscanner.tex", - u"google-cloud-websecurityscanner 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-cloud-websecurityscanner", - u"Google Cloud Websecurityscanner 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-cloud-websecurityscanner", - u"google-cloud-websecurityscanner Documentation", - author, - "google-cloud-websecurityscanner", - "GAPIC library for Google Cloud Websecurityscanner 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-cloud-websecurityscanner/v1/docs/index.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/index.rst deleted file mode 100644 index 44c047fb4284..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - websecurityscanner_v1/services_ - websecurityscanner_v1/types_ diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/services_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/services_.rst deleted file mode 100644 index 6fb98e606cb4..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Websecurityscanner v1 API -=================================================== -.. toctree:: - :maxdepth: 2 - - web_security_scanner diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/types_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/types_.rst deleted file mode 100644 index ad00a256c35d..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Websecurityscanner v1 API -================================================ - -.. automodule:: google.cloud.websecurityscanner_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/web_security_scanner.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/web_security_scanner.rst deleted file mode 100644 index 4925421b2eda..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/docs/websecurityscanner_v1/web_security_scanner.rst +++ /dev/null @@ -1,10 +0,0 @@ -WebSecurityScanner ------------------------------------- - -.. automodule:: google.cloud.websecurityscanner_v1.services.web_security_scanner - :members: - :inherited-members: - -.. automodule:: google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/__init__.py deleted file mode 100644 index 8e29513bc1fb..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/__init__.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 google.cloud.websecurityscanner import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.websecurityscanner_v1.services.web_security_scanner.client import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient - -from google.cloud.websecurityscanner_v1.types.crawled_url import CrawledUrl -from google.cloud.websecurityscanner_v1.types.finding import Finding -from google.cloud.websecurityscanner_v1.types.finding_addon import Form -from google.cloud.websecurityscanner_v1.types.finding_addon import OutdatedLibrary -from google.cloud.websecurityscanner_v1.types.finding_addon import ViolatingResource -from google.cloud.websecurityscanner_v1.types.finding_addon import VulnerableHeaders -from google.cloud.websecurityscanner_v1.types.finding_addon import VulnerableParameters -from google.cloud.websecurityscanner_v1.types.finding_addon import Xss -from google.cloud.websecurityscanner_v1.types.finding_addon import Xxe -from google.cloud.websecurityscanner_v1.types.finding_type_stats import FindingTypeStats -from google.cloud.websecurityscanner_v1.types.scan_config import ScanConfig -from google.cloud.websecurityscanner_v1.types.scan_config_error import ScanConfigError -from google.cloud.websecurityscanner_v1.types.scan_run import ScanRun -from google.cloud.websecurityscanner_v1.types.scan_run_error_trace import ScanRunErrorTrace -from google.cloud.websecurityscanner_v1.types.scan_run_log import ScanRunLog -from google.cloud.websecurityscanner_v1.types.scan_run_warning_trace import ScanRunWarningTrace -from google.cloud.websecurityscanner_v1.types.web_security_scanner import CreateScanConfigRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import DeleteScanConfigRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetFindingRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetScanConfigRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetScanRunRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListCrawledUrlsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListCrawledUrlsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingTypeStatsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingTypeStatsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanConfigsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanConfigsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanRunsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanRunsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import StartScanRunRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import StopScanRunRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ('WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', - 'CrawledUrl', - 'Finding', - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'Xxe', - 'FindingTypeStats', - 'ScanConfig', - 'ScanConfigError', - 'ScanRun', - 'ScanRunErrorTrace', - 'ScanRunLog', - 'ScanRunWarningTrace', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/py.typed deleted file mode 100644 index 8cfb5d256398..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/__init__.py deleted file mode 100644 index 5f1bfbc58721..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/__init__.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.web_security_scanner import WebSecurityScannerClient -from .services.web_security_scanner import WebSecurityScannerAsyncClient - -from .types.crawled_url import CrawledUrl -from .types.finding import Finding -from .types.finding_addon import Form -from .types.finding_addon import OutdatedLibrary -from .types.finding_addon import ViolatingResource -from .types.finding_addon import VulnerableHeaders -from .types.finding_addon import VulnerableParameters -from .types.finding_addon import Xss -from .types.finding_addon import Xxe -from .types.finding_type_stats import FindingTypeStats -from .types.scan_config import ScanConfig -from .types.scan_config_error import ScanConfigError -from .types.scan_run import ScanRun -from .types.scan_run_error_trace import ScanRunErrorTrace -from .types.scan_run_log import ScanRunLog -from .types.scan_run_warning_trace import ScanRunWarningTrace -from .types.web_security_scanner import CreateScanConfigRequest -from .types.web_security_scanner import DeleteScanConfigRequest -from .types.web_security_scanner import GetFindingRequest -from .types.web_security_scanner import GetScanConfigRequest -from .types.web_security_scanner import GetScanRunRequest -from .types.web_security_scanner import ListCrawledUrlsRequest -from .types.web_security_scanner import ListCrawledUrlsResponse -from .types.web_security_scanner import ListFindingsRequest -from .types.web_security_scanner import ListFindingsResponse -from .types.web_security_scanner import ListFindingTypeStatsRequest -from .types.web_security_scanner import ListFindingTypeStatsResponse -from .types.web_security_scanner import ListScanConfigsRequest -from .types.web_security_scanner import ListScanConfigsResponse -from .types.web_security_scanner import ListScanRunsRequest -from .types.web_security_scanner import ListScanRunsResponse -from .types.web_security_scanner import StartScanRunRequest -from .types.web_security_scanner import StopScanRunRequest -from .types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ( - 'WebSecurityScannerAsyncClient', -'CrawledUrl', -'CreateScanConfigRequest', -'DeleteScanConfigRequest', -'Finding', -'FindingTypeStats', -'Form', -'GetFindingRequest', -'GetScanConfigRequest', -'GetScanRunRequest', -'ListCrawledUrlsRequest', -'ListCrawledUrlsResponse', -'ListFindingTypeStatsRequest', -'ListFindingTypeStatsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListScanConfigsRequest', -'ListScanConfigsResponse', -'ListScanRunsRequest', -'ListScanRunsResponse', -'OutdatedLibrary', -'ScanConfig', -'ScanConfigError', -'ScanRun', -'ScanRunErrorTrace', -'ScanRunLog', -'ScanRunWarningTrace', -'StartScanRunRequest', -'StopScanRunRequest', -'UpdateScanConfigRequest', -'ViolatingResource', -'VulnerableHeaders', -'VulnerableParameters', -'WebSecurityScannerClient', -'Xss', -'Xxe', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json deleted file mode 100644 index 9f9d16e522dc..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json +++ /dev/null @@ -1,223 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.websecurityscanner_v1", - "protoPackage": "google.cloud.websecurityscanner.v1", - "schema": "1.0", - "services": { - "WebSecurityScanner": { - "clients": { - "grpc": { - "libraryClient": "WebSecurityScannerClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WebSecurityScannerAsyncClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - }, - "rest": { - "libraryClient": "WebSecurityScannerClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/py.typed deleted file mode 100644 index 8cfb5d256398..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py deleted file mode 100644 index 3aeec5e07d95..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__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 WebSecurityScannerClient -from .async_client import WebSecurityScannerAsyncClient - -__all__ = ( - 'WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py deleted file mode 100644 index 428a9bc8f21c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py +++ /dev/null @@ -1,1353 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.websecurityscanner_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.cloud.websecurityscanner_v1.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import finding_addon -from google.cloud.websecurityscanner_v1.types import finding_type_stats -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .client import WebSecurityScannerClient - - -class WebSecurityScannerAsyncClient: - """Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud. It - crawls your application, and attempts to exercise as many user - inputs and event handlers as possible. - """ - - _client: WebSecurityScannerClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = WebSecurityScannerClient._DEFAULT_UNIVERSE - - finding_path = staticmethod(WebSecurityScannerClient.finding_path) - parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) - common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) - parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) - common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) - parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) - common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) - parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) - common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) - parse_common_location_path = staticmethod(WebSecurityScannerClient.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: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, 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: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, 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 WebSecurityScannerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: 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 = WebSecurityScannerClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner 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,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): - 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 WebSecurityScannerTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WebSecurityScannerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_scan_config(self, - request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.CreateScanConfigRequest( - ) - - # Make the request - response = await client.create_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest, dict]]): - The request object. Request for the ``CreateScanConfig`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # 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, web_security_scanner.CreateScanConfigRequest): - request = web_security_scanner.CreateScanConfigRequest(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_scan_config] - - # Certain fields should be provided within 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_scan_config(self, - request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.DeleteScanConfigRequest( - ) - - # Make the request - await client.delete_scan_config(request=request) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest, dict]]): - The request object. Request for the ``DeleteScanConfig`` 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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, web_security_scanner.DeleteScanConfigRequest): - request = web_security_scanner.DeleteScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_scan_config] - - # Certain fields should be provided within 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 get_scan_config(self, - request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetScanConfigRequest( - ) - - # Make the request - response = await client.get_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.GetScanConfigRequest, dict]]): - The request object. Request for the ``GetScanConfig`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # 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, web_security_scanner.GetScanConfigRequest): - request = web_security_scanner.GetScanConfigRequest(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_scan_config] - - # Certain fields should be provided within 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_scan_configs(self, - request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsAsyncPager: - r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1 - - async def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListScanConfigsRequest( - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest, dict]]): - The request object. Request for the ``ListScanConfigs`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: - Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): - request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] - - # Certain fields should be provided within 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.ListScanConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_scan_config(self, - request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.UpdateScanConfigRequest( - ) - - # Make the request - response = await client.update_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest, dict]]): - The request object. Request for the ``UpdateScanConfigRequest`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # 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, web_security_scanner.UpdateScanConfigRequest): - request = web_security_scanner.UpdateScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_scan_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.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 start_scan_run(self, - request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.StartScanRunRequest( - ) - - # Make the request - response = await client.start_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.StartScanRunRequest, dict]]): - The request object. Request for the ``StartScanRun`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # 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, web_security_scanner.StartScanRunRequest): - request = web_security_scanner.StartScanRunRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.start_scan_run] - - # Certain fields should be provided within 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_scan_run(self, - request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetScanRunRequest( - ) - - # Make the request - response = await client.get_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.GetScanRunRequest, dict]]): - The request object. Request for the ``GetScanRun`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # 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, web_security_scanner.GetScanRunRequest): - request = web_security_scanner.GetScanRunRequest(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_scan_run] - - # Certain fields should be provided within 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_scan_runs(self, - request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsAsyncPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListScanRunsRequest( - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListScanRunsRequest, dict]]): - The request object. Request for the ``ListScanRuns`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsAsyncPager: - Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): - request = web_security_scanner.ListScanRunsRequest(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_scan_runs] - - # Certain fields should be provided within 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.ListScanRunsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def stop_scan_run(self, - request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.StopScanRunRequest( - ) - - # Make the request - response = await client.stop_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.StopScanRunRequest, dict]]): - The request object. Request for the ``StopScanRun`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # 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, web_security_scanner.StopScanRunRequest): - request = web_security_scanner.StopScanRunRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.stop_scan_run] - - # Certain fields should be provided within 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_crawled_urls(self, - request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsAsyncPager: - r"""List CrawledUrls under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListCrawledUrlsRequest( - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest, dict]]): - The request object. Request for the ``ListCrawledUrls`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: - Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] - - # Certain fields should be provided within 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.ListCrawledUrlsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_finding(self, - request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_get_finding(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetFindingRequest( - ) - - # Make the request - response = await client.get_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.GetFindingRequest, dict]]): - The request object. Request for the ``GetFinding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # 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, web_security_scanner.GetFindingRequest): - request = web_security_scanner.GetFindingRequest(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_finding] - - # Certain fields should be provided within 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_findings(self, - request: Optional[Union[web_security_scanner.ListFindingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""List Findings under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_list_findings(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListFindingsRequest( - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListFindingsRequest, dict]]): - The request object. Request for the ``ListFindings`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsAsyncPager: - Response for the ListFindings 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, web_security_scanner.ListFindingsRequest): - request = web_security_scanner.ListFindingsRequest(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_findings] - - # Certain fields should be provided within 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.ListFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_finding_type_stats(self, - request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - async def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListFindingTypeStatsRequest( - ) - - # Make the request - response = await client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest, dict]]): - The request object. Request for the ``ListFindingTypeStats`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats method. - """ - # 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, web_security_scanner.ListFindingTypeStatsRequest): - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] - - # Certain fields should be provided within 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) -> "WebSecurityScannerAsyncClient": - 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__ = ( - "WebSecurityScannerAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py deleted file mode 100644 index 001f1d5c2c43..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py +++ /dev/null @@ -1,1710 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.websecurityscanner_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 - -from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import finding_addon -from google.cloud.websecurityscanner_v1.types import finding_type_stats -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WebSecurityScannerGrpcTransport -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .transports.rest import WebSecurityScannerRestTransport - - -class WebSecurityScannerClientMeta(type): - """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] - _transport_registry["grpc"] = WebSecurityScannerGrpcTransport - _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport - _transport_registry["rest"] = WebSecurityScannerRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[WebSecurityScannerTransport]: - """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 WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): - """Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud. It - crawls your application, and attempts to exercise as many user - inputs and event handlers as possible. - """ - - @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 = "websecurityscanner.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "websecurityscanner.{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: - WebSecurityScannerClient: 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: - WebSecurityScannerClient: 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) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?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 = WebSecurityScannerClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = WebSecurityScannerClient._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 = WebSecurityScannerClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - WebSecurityScannerClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): - 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 WebSecurityScannerTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WebSecurityScannerClient._read_environment_variables() - self._client_cert_source = WebSecurityScannerClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = WebSecurityScannerClient._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 - - 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, WebSecurityScannerTransport) - if transport_provided: - # transport is a WebSecurityScannerTransport 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(WebSecurityScannerTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - WebSecurityScannerClient._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[WebSecurityScannerTransport], Callable[..., WebSecurityScannerTransport]] = ( - WebSecurityScannerClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., WebSecurityScannerTransport], 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, - ) - - def create_scan_config(self, - request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.CreateScanConfigRequest( - ) - - # Make the request - response = client.create_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest, dict]): - The request object. Request for the ``CreateScanConfig`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # 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, web_security_scanner.CreateScanConfigRequest): - request = web_security_scanner.CreateScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_scan_config] - - # Certain fields should be provided within 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_scan_config(self, - request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.DeleteScanConfigRequest( - ) - - # Make the request - client.delete_scan_config(request=request) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest, dict]): - The request object. Request for the ``DeleteScanConfig`` method. - retry (google.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. - """ - # 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, web_security_scanner.DeleteScanConfigRequest): - request = web_security_scanner.DeleteScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_scan_config] - - # Certain fields should be provided within 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 get_scan_config(self, - request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetScanConfigRequest( - ) - - # Make the request - response = client.get_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.GetScanConfigRequest, dict]): - The request object. Request for the ``GetScanConfig`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # 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, web_security_scanner.GetScanConfigRequest): - request = web_security_scanner.GetScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_scan_config] - - # Certain fields should be provided within 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_scan_configs(self, - request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsPager: - r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1 - - def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListScanConfigsRequest( - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest, dict]): - The request object. Request for the ``ListScanConfigs`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsPager: - Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): - request = web_security_scanner.ListScanConfigsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_scan_configs] - - # Certain fields should be provided within 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.ListScanConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_scan_config(self, - request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.UpdateScanConfigRequest( - ) - - # Make the request - response = client.update_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest, dict]): - The request object. Request for the ``UpdateScanConfigRequest`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # 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, web_security_scanner.UpdateScanConfigRequest): - request = web_security_scanner.UpdateScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_scan_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.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 start_scan_run(self, - request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.StartScanRunRequest( - ) - - # Make the request - response = client.start_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.StartScanRunRequest, dict]): - The request object. Request for the ``StartScanRun`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # 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, web_security_scanner.StartScanRunRequest): - request = web_security_scanner.StartScanRunRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.start_scan_run] - - # Certain fields should be provided within 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_scan_run(self, - request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetScanRunRequest( - ) - - # Make the request - response = client.get_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.GetScanRunRequest, dict]): - The request object. Request for the ``GetScanRun`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # 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, web_security_scanner.GetScanRunRequest): - request = web_security_scanner.GetScanRunRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_scan_run] - - # Certain fields should be provided within 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_scan_runs(self, - request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListScanRunsRequest( - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListScanRunsRequest, dict]): - The request object. Request for the ``ListScanRuns`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsPager: - Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): - request = web_security_scanner.ListScanRunsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_scan_runs] - - # Certain fields should be provided within 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.ListScanRunsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def stop_scan_run(self, - request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.StopScanRunRequest( - ) - - # Make the request - response = client.stop_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.StopScanRunRequest, dict]): - The request object. Request for the ``StopScanRun`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # 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, web_security_scanner.StopScanRunRequest): - request = web_security_scanner.StopScanRunRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.stop_scan_run] - - # Certain fields should be provided within 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_crawled_urls(self, - request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsPager: - r"""List CrawledUrls under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListCrawledUrlsRequest( - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest, dict]): - The request object. Request for the ``ListCrawledUrls`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsPager: - Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): - request = web_security_scanner.ListCrawledUrlsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_crawled_urls] - - # Certain fields should be provided within 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.ListCrawledUrlsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_finding(self, - request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_get_finding(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetFindingRequest( - ) - - # Make the request - response = client.get_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.GetFindingRequest, dict]): - The request object. Request for the ``GetFinding`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # 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, web_security_scanner.GetFindingRequest): - request = web_security_scanner.GetFindingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_finding] - - # Certain fields should be provided within 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_findings(self, - request: Optional[Union[web_security_scanner.ListFindingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""List Findings under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_list_findings(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListFindingsRequest( - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListFindingsRequest, dict]): - The request object. Request for the ``ListFindings`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsPager: - Response for the ListFindings 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, web_security_scanner.ListFindingsRequest): - request = web_security_scanner.ListFindingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_findings] - - # Certain fields should be provided within 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.ListFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_finding_type_stats(self, - request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1 - - def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListFindingTypeStatsRequest( - ) - - # Make the request - response = client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest, dict]): - The request object. Request for the ``ListFindingTypeStats`` method. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats method. - """ - # 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, web_security_scanner.ListFindingTypeStatsRequest): - request = web_security_scanner.ListFindingTypeStatsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_finding_type_stats] - - # Certain fields should be provided within 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) -> "WebSecurityScannerClient": - 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__ = ( - "WebSecurityScannerClient", -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py deleted file mode 100644 index 1f2e9022259c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py +++ /dev/null @@ -1,571 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner - - -class ListScanConfigsPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListScanConfigsResponse], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - for page in self.pages: - yield from page.scan_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanConfigsAsyncPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` - attributes are available on the 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[web_security_scanner.ListScanConfigsResponse]], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListScanRunsResponse], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListScanRunsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - for page in self.pages: - yield from page.scan_runs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsAsyncPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` - attributes are available on the 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[web_security_scanner.ListScanRunsResponse]], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListScanRunsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_runs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListCrawledUrlsResponse], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - for page in self.pages: - yield from page.crawled_urls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsAsyncPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` - attributes are available on the 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[web_security_scanner.ListCrawledUrlsResponse]], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - async def async_generator(): - async for page in self.pages: - for response in page.crawled_urls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListFindingsResponse], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListFindingsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: - 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[finding.Finding]: - for page in self.pages: - yield from page.findings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` - attributes are available on the 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[web_security_scanner.ListFindingsResponse]], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListFindingsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: - 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[finding.Finding]: - async def async_generator(): - async for page in self.pages: - for response in page.findings: - 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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/README.rst deleted file mode 100644 index 3479ee767648..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`WebSecurityScannerTransport` is the ABC for all transports. -- public child `WebSecurityScannerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `WebSecurityScannerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseWebSecurityScannerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `WebSecurityScannerRestTransport` 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-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py deleted file mode 100644 index e24819a4ee07..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/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 WebSecurityScannerTransport -from .grpc import WebSecurityScannerGrpcTransport -from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .rest import WebSecurityScannerRestTransport -from .rest import WebSecurityScannerRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] -_transport_registry['grpc'] = WebSecurityScannerGrpcTransport -_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport -_transport_registry['rest'] = WebSecurityScannerRestTransport - -__all__ = ( - 'WebSecurityScannerTransport', - 'WebSecurityScannerGrpcTransport', - 'WebSecurityScannerGrpcAsyncIOTransport', - 'WebSecurityScannerRestTransport', - 'WebSecurityScannerRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py deleted file mode 100644 index 9e3ddff0edf5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/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 google.cloud.websecurityscanner_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.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class WebSecurityScannerTransport(abc.ABC): - """Abstract transport class for WebSecurityScanner.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_scan_config: gapic_v1.method.wrap_method( - self.create_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.delete_scan_config: gapic_v1.method.wrap_method( - self.delete_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_config: gapic_v1.method.wrap_method( - self.get_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_configs: gapic_v1.method.wrap_method( - self.list_scan_configs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_scan_config: gapic_v1.method.wrap_method( - self.update_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.start_scan_run: gapic_v1.method.wrap_method( - self.start_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_run: gapic_v1.method.wrap_method( - self.get_scan_run, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_runs: gapic_v1.method.wrap_method( - self.list_scan_runs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.stop_scan_run: gapic_v1.method.wrap_method( - self.stop_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.list_crawled_urls: gapic_v1.method.wrap_method( - self.list_crawled_urls, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_finding: gapic_v1.method.wrap_method( - self.get_finding, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_finding_type_stats: gapic_v1.method.wrap_method( - self.list_finding_type_stats, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Union[ - web_security_scanner.ListScanConfigsResponse, - Awaitable[web_security_scanner.ListScanConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Union[ - web_security_scanner.ListScanRunsResponse, - Awaitable[web_security_scanner.ListScanRunsResponse] - ]]: - raise NotImplementedError() - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Union[ - web_security_scanner.ListCrawledUrlsResponse, - Awaitable[web_security_scanner.ListCrawledUrlsResponse] - ]]: - raise NotImplementedError() - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Union[ - web_security_scanner.ListFindingsResponse, - Awaitable[web_security_scanner.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Union[ - web_security_scanner.ListFindingTypeStatsResponse, - Awaitable[web_security_scanner.ListFindingTypeStatsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'WebSecurityScannerTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py deleted file mode 100644 index 65a71b7c972b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py +++ /dev/null @@ -1,592 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO - - -class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): - """gRPC backend transport for WebSecurityScanner. - - Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud. It - crawls your application, and attempts to exercise as many user - inputs and event handlers as possible. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'websecurityscanner.googleapis.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_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - ~.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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - web_security_scanner.ListScanConfigsResponse]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - ~.ListScanConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - web_security_scanner.ListScanRunsResponse]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - ~.ListScanRunsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - web_security_scanner.ListCrawledUrlsResponse]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - ~.ListCrawledUrlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - finding.Finding]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - web_security_scanner.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - Returns: - Callable[[~.ListFindingsRequest], - ~.ListFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - web_security_scanner.ListFindingTypeStatsResponse]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - ~.ListFindingTypeStatsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'WebSecurityScannerGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py deleted file mode 100644 index fecf2a018924..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py +++ /dev/null @@ -1,763 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .grpc import WebSecurityScannerGrpcTransport - - -class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): - """gRPC AsyncIO backend transport for WebSecurityScanner. - - Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud. It - crawls your application, and attempts to exercise as many user - inputs and event handlers as possible. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'websecurityscanner.googleapis.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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - 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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Awaitable[web_security_scanner.ListScanConfigsResponse]]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - Awaitable[~.ListScanConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Awaitable[web_security_scanner.ListScanRunsResponse]]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - Awaitable[~.ListScanRunsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - Awaitable[~.ListCrawledUrlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Awaitable[web_security_scanner.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - Returns: - Callable[[~.ListFindingsRequest], - Awaitable[~.ListFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - Awaitable[~.ListFindingTypeStatsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - 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_scan_config: self._wrap_method( - self.create_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.delete_scan_config: self._wrap_method( - self.delete_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_config: self._wrap_method( - self.get_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_configs: self._wrap_method( - self.list_scan_configs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_scan_config: self._wrap_method( - self.update_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.start_scan_run: self._wrap_method( - self.start_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_run: self._wrap_method( - self.get_scan_run, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_runs: self._wrap_method( - self.list_scan_runs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.stop_scan_run: self._wrap_method( - self.stop_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.list_crawled_urls: self._wrap_method( - self.list_crawled_urls, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_finding: self._wrap_method( - self.get_finding, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_findings: self._wrap_method( - self.list_findings, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_finding_type_stats: self._wrap_method( - self.list_finding_type_stats, - 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=600.0, - ), - default_timeout=600.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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'WebSecurityScannerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py deleted file mode 100644 index 1a84eb8b4067..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py +++ /dev/null @@ -1,1532 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - - -from .rest_base import _BaseWebSecurityScannerRestTransport -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 - - -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 WebSecurityScannerRestInterceptor: - """Interceptor for WebSecurityScanner. - - 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 WebSecurityScannerRestTransport. - - .. code-block:: python - class MyCustomWebSecurityScannerInterceptor(WebSecurityScannerRestInterceptor): - def pre_create_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_scan_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_scan_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_scan_run(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_scan_run(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_crawled_urls(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_crawled_urls(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_finding_type_stats(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_finding_type_stats(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_scan_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_scan_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_scan_runs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_scan_runs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_start_scan_run(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_start_scan_run(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stop_scan_run(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stop_scan_run(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_scan_config(self, response): - logging.log(f"Received response: {response}") - return response - - transport = WebSecurityScannerRestTransport(interceptor=MyCustomWebSecurityScannerInterceptor()) - client = WebSecurityScannerClient(transport=transport) - - - """ - def pre_create_scan_config(self, request: web_security_scanner.CreateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.CreateScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_create_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: - """Post-rpc interceptor for create_scan_config - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_delete_scan_config(self, request: web_security_scanner.DeleteScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.DeleteScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def pre_get_finding(self, request: web_security_scanner.GetFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_get_finding(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for get_finding - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_get_scan_config(self, request: web_security_scanner.GetScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_get_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: - """Post-rpc interceptor for get_scan_config - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_get_scan_run(self, request: web_security_scanner.GetScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanRunRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_scan_run - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_get_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: - """Post-rpc interceptor for get_scan_run - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_crawled_urls(self, request: web_security_scanner.ListCrawledUrlsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListCrawledUrlsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_crawled_urls - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_crawled_urls(self, response: web_security_scanner.ListCrawledUrlsResponse) -> web_security_scanner.ListCrawledUrlsResponse: - """Post-rpc interceptor for list_crawled_urls - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_findings(self, request: web_security_scanner.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_findings(self, response: web_security_scanner.ListFindingsResponse) -> web_security_scanner.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_finding_type_stats(self, request: web_security_scanner.ListFindingTypeStatsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingTypeStatsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_finding_type_stats - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_finding_type_stats(self, response: web_security_scanner.ListFindingTypeStatsResponse) -> web_security_scanner.ListFindingTypeStatsResponse: - """Post-rpc interceptor for list_finding_type_stats - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_scan_configs(self, request: web_security_scanner.ListScanConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_scan_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_scan_configs(self, response: web_security_scanner.ListScanConfigsResponse) -> web_security_scanner.ListScanConfigsResponse: - """Post-rpc interceptor for list_scan_configs - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_scan_runs(self, request: web_security_scanner.ListScanRunsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanRunsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_scan_runs - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_scan_runs(self, response: web_security_scanner.ListScanRunsResponse) -> web_security_scanner.ListScanRunsResponse: - """Post-rpc interceptor for list_scan_runs - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_start_scan_run(self, request: web_security_scanner.StartScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StartScanRunRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for start_scan_run - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_start_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: - """Post-rpc interceptor for start_scan_run - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_stop_scan_run(self, request: web_security_scanner.StopScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StopScanRunRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for stop_scan_run - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_stop_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: - """Post-rpc interceptor for stop_scan_run - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_update_scan_config(self, request: web_security_scanner.UpdateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.UpdateScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_update_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: - """Post-rpc interceptor for update_scan_config - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class WebSecurityScannerRestStub: - _session: AuthorizedSession - _host: str - _interceptor: WebSecurityScannerRestInterceptor - - -class WebSecurityScannerRestTransport(_BaseWebSecurityScannerRestTransport): - """REST backend synchronous transport for WebSecurityScanner. - - Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud. It - crawls your application, and attempts to exercise as many user - inputs and event handlers as possible. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'websecurityscanner.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[WebSecurityScannerRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 WebSecurityScannerRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateScanConfig(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.CreateScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.CreateScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_config.ScanConfig: - r"""Call the create scan config method over HTTP. - - Args: - request (~.web_security_scanner.CreateScanConfigRequest): - The request object. Request for the ``CreateScanConfig`` method. - retry (google.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. - - Returns: - ~.scan_config.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_http_options() - request, metadata = self._interceptor.pre_create_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._CreateScanConfig._get_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 = scan_config.ScanConfig() - pb_resp = scan_config.ScanConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_scan_config(resp) - return resp - - class _DeleteScanConfig(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.DeleteScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.DeleteScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete scan config method over HTTP. - - Args: - request (~.web_security_scanner.DeleteScanConfigRequest): - The request object. Request for the ``DeleteScanConfig`` method. - retry (google.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. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_http_options() - request, metadata = self._interceptor.pre_delete_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._DeleteScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 _GetFinding(_BaseWebSecurityScannerRestTransport._BaseGetFinding, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.GetFinding") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.GetFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the get finding method over HTTP. - - Args: - request (~.web_security_scanner.GetFindingRequest): - The request object. Request for the ``GetFinding`` method. - retry (google.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. - - Returns: - ~.finding.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_http_options() - request, metadata = self._interceptor.pre_get_finding(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._GetFinding._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = finding.Finding() - pb_resp = finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_finding(resp) - return resp - - class _GetScanConfig(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.GetScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.GetScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_config.ScanConfig: - r"""Call the get scan config method over HTTP. - - Args: - request (~.web_security_scanner.GetScanConfigRequest): - The request object. Request for the ``GetScanConfig`` method. - retry (google.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. - - Returns: - ~.scan_config.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_http_options() - request, metadata = self._interceptor.pre_get_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._GetScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = scan_config.ScanConfig() - pb_resp = scan_config.ScanConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_scan_config(resp) - return resp - - class _GetScanRun(_BaseWebSecurityScannerRestTransport._BaseGetScanRun, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.GetScanRun") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.GetScanRunRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_run.ScanRun: - r"""Call the get scan run method over HTTP. - - Args: - request (~.web_security_scanner.GetScanRunRequest): - The request object. Request for the ``GetScanRun`` method. - retry (google.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. - - Returns: - ~.scan_run.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_http_options() - request, metadata = self._interceptor.pre_get_scan_run(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._GetScanRun._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = scan_run.ScanRun() - pb_resp = scan_run.ScanRun.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_scan_run(resp) - return resp - - class _ListCrawledUrls(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListCrawledUrls") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListCrawledUrlsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListCrawledUrlsResponse: - r"""Call the list crawled urls method over HTTP. - - Args: - request (~.web_security_scanner.ListCrawledUrlsRequest): - The request object. Request for the ``ListCrawledUrls`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListCrawledUrlsResponse: - Response for the ``ListCrawledUrls`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_http_options() - request, metadata = self._interceptor.pre_list_crawled_urls(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListCrawledUrls._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListCrawledUrlsResponse() - pb_resp = web_security_scanner.ListCrawledUrlsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_crawled_urls(resp) - return resp - - class _ListFindings(_BaseWebSecurityScannerRestTransport._BaseListFindings, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListFindings") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.web_security_scanner.ListFindingsRequest): - The request object. Request for the ``ListFindings`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListFindingsResponse: - Response for the ``ListFindings`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_http_options() - request, metadata = self._interceptor.pre_list_findings(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListFindings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListFindingsResponse() - pb_resp = web_security_scanner.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListFindingTypeStats(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListFindingTypeStats") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListFindingTypeStatsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""Call the list finding type stats method over HTTP. - - Args: - request (~.web_security_scanner.ListFindingTypeStatsRequest): - The request object. Request for the ``ListFindingTypeStats`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListFindingTypeStatsResponse: - Response for the ``ListFindingTypeStats`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_http_options() - request, metadata = self._interceptor.pre_list_finding_type_stats(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListFindingTypeStats._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListFindingTypeStatsResponse() - pb_resp = web_security_scanner.ListFindingTypeStatsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_finding_type_stats(resp) - return resp - - class _ListScanConfigs(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListScanConfigs") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListScanConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListScanConfigsResponse: - r"""Call the list scan configs method over HTTP. - - Args: - request (~.web_security_scanner.ListScanConfigsRequest): - The request object. Request for the ``ListScanConfigs`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListScanConfigsResponse: - Response for the ``ListScanConfigs`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_http_options() - request, metadata = self._interceptor.pre_list_scan_configs(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListScanConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListScanConfigsResponse() - pb_resp = web_security_scanner.ListScanConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_scan_configs(resp) - return resp - - class _ListScanRuns(_BaseWebSecurityScannerRestTransport._BaseListScanRuns, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListScanRuns") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListScanRunsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListScanRunsResponse: - r"""Call the list scan runs method over HTTP. - - Args: - request (~.web_security_scanner.ListScanRunsRequest): - The request object. Request for the ``ListScanRuns`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListScanRunsResponse: - Response for the ``ListScanRuns`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_http_options() - request, metadata = self._interceptor.pre_list_scan_runs(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListScanRuns._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListScanRunsResponse() - pb_resp = web_security_scanner.ListScanRunsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_scan_runs(resp) - return resp - - class _StartScanRun(_BaseWebSecurityScannerRestTransport._BaseStartScanRun, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.StartScanRun") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.StartScanRunRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_run.ScanRun: - r"""Call the start scan run method over HTTP. - - Args: - request (~.web_security_scanner.StartScanRunRequest): - The request object. Request for the ``StartScanRun`` method. - retry (google.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. - - Returns: - ~.scan_run.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_http_options() - request, metadata = self._interceptor.pre_start_scan_run(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._StartScanRun._get_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 = scan_run.ScanRun() - pb_resp = scan_run.ScanRun.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_start_scan_run(resp) - return resp - - class _StopScanRun(_BaseWebSecurityScannerRestTransport._BaseStopScanRun, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.StopScanRun") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.StopScanRunRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_run.ScanRun: - r"""Call the stop scan run method over HTTP. - - Args: - request (~.web_security_scanner.StopScanRunRequest): - The request object. Request for the ``StopScanRun`` method. - retry (google.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. - - Returns: - ~.scan_run.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_http_options() - request, metadata = self._interceptor.pre_stop_scan_run(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._StopScanRun._get_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 = scan_run.ScanRun() - pb_resp = scan_run.ScanRun.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_stop_scan_run(resp) - return resp - - class _UpdateScanConfig(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.UpdateScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.UpdateScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_config.ScanConfig: - r"""Call the update scan config method over HTTP. - - Args: - request (~.web_security_scanner.UpdateScanConfigRequest): - The request object. Request for the ``UpdateScanConfigRequest`` method. - retry (google.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. - - Returns: - ~.scan_config.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_http_options() - request, metadata = self._interceptor.pre_update_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._UpdateScanConfig._get_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 = scan_config.ScanConfig() - pb_resp = scan_config.ScanConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_scan_config(resp) - return resp - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - scan_config.ScanConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - 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._DeleteScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - finding.Finding]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - scan_config.ScanConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - scan_run.ScanRun]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetScanRun(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - web_security_scanner.ListCrawledUrlsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListCrawledUrls(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - web_security_scanner.ListFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - web_security_scanner.ListFindingTypeStatsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListFindingTypeStats(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - web_security_scanner.ListScanConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListScanConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - web_security_scanner.ListScanRunsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListScanRuns(self._session, self._host, self._interceptor) # type: ignore - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - scan_run.ScanRun]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StartScanRun(self._session, self._host, self._interceptor) # type: ignore - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - scan_run.ScanRun]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StopScanRun(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - scan_config.ScanConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'WebSecurityScannerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest_base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest_base.py deleted file mode 100644 index 88b128878474..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest_base.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 WebSecurityScannerTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - - -class _BaseWebSecurityScannerRestTransport(WebSecurityScannerTransport): - """Base REST backend transport for WebSecurityScanner. - - 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 = 'websecurityscanner.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: 'websecurityscanner.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 _BaseCreateScanConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/scanConfigs', - 'body': 'scan_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.CreateScanConfigRequest.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["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteScanConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/scanConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.DeleteScanConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _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 _BaseGetFinding: - 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/*/scanConfigs/*/scanRuns/*/findings/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.GetFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _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 _BaseGetScanConfig: - 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/*/scanConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.GetScanConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _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 _BaseGetScanRun: - 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/*/scanConfigs/*/scanRuns/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.GetScanRunRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _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 _BaseListCrawledUrls: - 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/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListCrawledUrlsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _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 _BaseListFindings: - 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/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _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 _BaseListFindingTypeStats: - 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/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListFindingTypeStatsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _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 _BaseListScanConfigs: - 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/{parent=projects/*}/scanConfigs', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListScanConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _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 _BaseListScanRuns: - 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/{parent=projects/*/scanConfigs/*}/scanRuns', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListScanRunsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _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 _BaseStartScanRun: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/scanConfigs/*}:start', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.StartScanRunRequest.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["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStopScanRun: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/scanConfigs/*/scanRuns/*}:stop', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.StopScanRunRequest.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["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateScanConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{scan_config.name=projects/*/scanConfigs/*}', - 'body': 'scan_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.UpdateScanConfigRequest.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["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseWebSecurityScannerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/__init__.py deleted file mode 100644 index cc33ca771c3b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_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 .crawled_url import ( - CrawledUrl, -) -from .finding import ( - Finding, -) -from .finding_addon import ( - Form, - OutdatedLibrary, - ViolatingResource, - VulnerableHeaders, - VulnerableParameters, - Xss, - Xxe, -) -from .finding_type_stats import ( - FindingTypeStats, -) -from .scan_config import ( - ScanConfig, -) -from .scan_config_error import ( - ScanConfigError, -) -from .scan_run import ( - ScanRun, -) -from .scan_run_error_trace import ( - ScanRunErrorTrace, -) -from .scan_run_log import ( - ScanRunLog, -) -from .scan_run_warning_trace import ( - ScanRunWarningTrace, -) -from .web_security_scanner import ( - CreateScanConfigRequest, - DeleteScanConfigRequest, - GetFindingRequest, - GetScanConfigRequest, - GetScanRunRequest, - ListCrawledUrlsRequest, - ListCrawledUrlsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListFindingTypeStatsRequest, - ListFindingTypeStatsResponse, - ListScanConfigsRequest, - ListScanConfigsResponse, - ListScanRunsRequest, - ListScanRunsResponse, - StartScanRunRequest, - StopScanRunRequest, - UpdateScanConfigRequest, -) - -__all__ = ( - 'CrawledUrl', - 'Finding', - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'Xxe', - 'FindingTypeStats', - 'ScanConfig', - 'ScanConfigError', - 'ScanRun', - 'ScanRunErrorTrace', - 'ScanRunLog', - 'ScanRunWarningTrace', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py deleted file mode 100644 index 422126dfc89d..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/crawled_url.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.cloud.websecurityscanner.v1', - manifest={ - 'CrawledUrl', - }, -) - - -class CrawledUrl(proto.Message): - r"""A CrawledUrl resource represents a URL that was crawled - during a ScanRun. Web Security Scanner Service crawls the web - applications, following all links within the scope of sites, to - find the URLs to test against. - - Attributes: - http_method (str): - Output only. The http method of the request - that was used to visit the URL, in uppercase. - url (str): - Output only. The URL that was crawled. - body (str): - Output only. The body of the request that was - used to visit the URL. - """ - - http_method: str = proto.Field( - proto.STRING, - number=1, - ) - url: str = proto.Field( - proto.STRING, - number=2, - ) - body: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding.py deleted file mode 100644 index e40e0b8f7e7b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding.py +++ /dev/null @@ -1,209 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner_v1.types import finding_addon - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""A Finding resource represents a vulnerability instance - identified during a ScanRun. - - Attributes: - name (str): - Output only. The resource name of the - Finding. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. - The finding IDs are generated by the system. - finding_type (str): - Output only. The type of the Finding. - Detailed and up-to-date information on findings - can be found here: - - https://cloud.google.com/security-command-center/docs/how-to-remediate-web-security-scanner-findings - severity (google.cloud.websecurityscanner_v1.types.Finding.Severity): - Output only. The severity level of the - reported vulnerability. - http_method (str): - Output only. The http method of the request - that triggered the vulnerability, in uppercase. - fuzzed_url (str): - Output only. The URL produced by the - server-side fuzzer and used in the request that - triggered the vulnerability. - body (str): - Output only. The body of the request that - triggered the vulnerability. - description (str): - Output only. The description of the - vulnerability. - reproduction_url (str): - Output only. The URL containing - human-readable payload that user can leverage to - reproduce the vulnerability. - frame_url (str): - Output only. If the vulnerability was - originated from nested IFrame, the immediate - parent IFrame is reported. - final_url (str): - Output only. The URL where the browser lands - when the vulnerability is detected. - tracking_id (str): - Output only. The tracking ID uniquely - identifies a vulnerability instance across - multiple ScanRuns. - form (google.cloud.websecurityscanner_v1.types.Form): - Output only. An addon containing information - reported for a vulnerability with an HTML form, - if any. - outdated_library (google.cloud.websecurityscanner_v1.types.OutdatedLibrary): - Output only. An addon containing information - about outdated libraries. - violating_resource (google.cloud.websecurityscanner_v1.types.ViolatingResource): - Output only. An addon containing detailed - information regarding any resource causing the - vulnerability such as JavaScript sources, image, - audio files, etc. - vulnerable_headers (google.cloud.websecurityscanner_v1.types.VulnerableHeaders): - Output only. An addon containing information - about vulnerable or missing HTTP headers. - vulnerable_parameters (google.cloud.websecurityscanner_v1.types.VulnerableParameters): - Output only. An addon containing information - about request parameters which were found to be - vulnerable. - xss (google.cloud.websecurityscanner_v1.types.Xss): - Output only. An addon containing information - reported for an XSS, if any. - xxe (google.cloud.websecurityscanner_v1.types.Xxe): - Output only. An addon containing information - reported for an XXE, if any. - """ - class Severity(proto.Enum): - r"""The severity level of a vulnerability. - - Values: - SEVERITY_UNSPECIFIED (0): - No severity specified. The default value. - CRITICAL (1): - Critical severity. - HIGH (2): - High severity. - MEDIUM (3): - Medium severity. - LOW (4): - Low severity. - """ - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - HIGH = 2 - MEDIUM = 3 - LOW = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - finding_type: str = proto.Field( - proto.STRING, - number=2, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=17, - enum=Severity, - ) - http_method: str = proto.Field( - proto.STRING, - number=3, - ) - fuzzed_url: str = proto.Field( - proto.STRING, - number=4, - ) - body: str = proto.Field( - proto.STRING, - number=5, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - reproduction_url: str = proto.Field( - proto.STRING, - number=7, - ) - frame_url: str = proto.Field( - proto.STRING, - number=8, - ) - final_url: str = proto.Field( - proto.STRING, - number=9, - ) - tracking_id: str = proto.Field( - proto.STRING, - number=10, - ) - form: finding_addon.Form = proto.Field( - proto.MESSAGE, - number=16, - message=finding_addon.Form, - ) - outdated_library: finding_addon.OutdatedLibrary = proto.Field( - proto.MESSAGE, - number=11, - message=finding_addon.OutdatedLibrary, - ) - violating_resource: finding_addon.ViolatingResource = proto.Field( - proto.MESSAGE, - number=12, - message=finding_addon.ViolatingResource, - ) - vulnerable_headers: finding_addon.VulnerableHeaders = proto.Field( - proto.MESSAGE, - number=15, - message=finding_addon.VulnerableHeaders, - ) - vulnerable_parameters: finding_addon.VulnerableParameters = proto.Field( - proto.MESSAGE, - number=13, - message=finding_addon.VulnerableParameters, - ) - xss: finding_addon.Xss = proto.Field( - proto.MESSAGE, - number=14, - message=finding_addon.Xss, - ) - xxe: finding_addon.Xxe = proto.Field( - proto.MESSAGE, - number=18, - message=finding_addon.Xxe, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py deleted file mode 100644 index f60af7eb4bc8..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner.v1', - manifest={ - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableParameters', - 'VulnerableHeaders', - 'Xss', - 'Xxe', - }, -) - - -class Form(proto.Message): - r"""! Information about a vulnerability with an HTML. - - Attributes: - action_uri (str): - ! The URI where to send the form when it's - submitted. - fields (MutableSequence[str]): - ! The names of form fields related to the - vulnerability. - """ - - action_uri: str = proto.Field( - proto.STRING, - number=1, - ) - fields: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class OutdatedLibrary(proto.Message): - r"""Information reported for an outdated library. - - Attributes: - library_name (str): - The name of the outdated library. - version (str): - The version number. - learn_more_urls (MutableSequence[str]): - URLs to learn more information about the - vulnerabilities in the library. - """ - - library_name: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - learn_more_urls: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ViolatingResource(proto.Message): - r"""Information regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, etc. - - Attributes: - content_type (str): - The MIME type of this resource. - resource_url (str): - URL of this violating resource. - """ - - content_type: str = proto.Field( - proto.STRING, - number=1, - ) - resource_url: str = proto.Field( - proto.STRING, - number=2, - ) - - -class VulnerableParameters(proto.Message): - r"""Information about vulnerable request parameters. - - Attributes: - parameter_names (MutableSequence[str]): - The vulnerable parameter names. - """ - - parameter_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class VulnerableHeaders(proto.Message): - r"""Information about vulnerable or missing HTTP Headers. - - Attributes: - headers (MutableSequence[google.cloud.websecurityscanner_v1.types.VulnerableHeaders.Header]): - List of vulnerable headers. - missing_headers (MutableSequence[google.cloud.websecurityscanner_v1.types.VulnerableHeaders.Header]): - List of missing headers. - """ - - class Header(proto.Message): - r"""Describes a HTTP Header. - - Attributes: - name (str): - Header name. - value (str): - Header value. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - - headers: MutableSequence[Header] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Header, - ) - missing_headers: MutableSequence[Header] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Header, - ) - - -class Xss(proto.Message): - r"""Information reported for an XSS. - - Attributes: - stack_traces (MutableSequence[str]): - Stack traces leading to the point where the - XSS occurred. - error_message (str): - An error message generated by a javascript - breakage. - attack_vector (google.cloud.websecurityscanner_v1.types.Xss.AttackVector): - The attack vector of the payload triggering - this XSS. - stored_xss_seeding_url (str): - The reproduction url for the seeding POST - request of a Stored XSS. - """ - class AttackVector(proto.Enum): - r"""Types of XSS attack vector. - - Values: - ATTACK_VECTOR_UNSPECIFIED (0): - Unknown attack vector. - LOCAL_STORAGE (1): - The attack comes from fuzzing the browser's - localStorage. - SESSION_STORAGE (2): - The attack comes from fuzzing the browser's - sessionStorage. - WINDOW_NAME (3): - The attack comes from fuzzing the window's - name property. - REFERRER (4): - The attack comes from fuzzing the referrer - property. - FORM_INPUT (5): - The attack comes from fuzzing an input - element. - COOKIE (6): - The attack comes from fuzzing the browser's - cookies. - POST_MESSAGE (7): - The attack comes from hijacking the post - messaging mechanism. - GET_PARAMETERS (8): - The attack comes from fuzzing parameters in - the url. - URL_FRAGMENT (9): - The attack comes from fuzzing the fragment in - the url. - HTML_COMMENT (10): - The attack comes from fuzzing the HTML - comments. - POST_PARAMETERS (11): - The attack comes from fuzzing the POST - parameters. - PROTOCOL (12): - The attack comes from fuzzing the protocol. - STORED_XSS (13): - The attack comes from the server side and is - stored. - SAME_ORIGIN (14): - The attack is a Same-Origin Method Execution - attack via a GET parameter. - USER_CONTROLLABLE_URL (15): - The attack payload is received from a - third-party host via a URL that is - user-controllable - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - LOCAL_STORAGE = 1 - SESSION_STORAGE = 2 - WINDOW_NAME = 3 - REFERRER = 4 - FORM_INPUT = 5 - COOKIE = 6 - POST_MESSAGE = 7 - GET_PARAMETERS = 8 - URL_FRAGMENT = 9 - HTML_COMMENT = 10 - POST_PARAMETERS = 11 - PROTOCOL = 12 - STORED_XSS = 13 - SAME_ORIGIN = 14 - USER_CONTROLLABLE_URL = 15 - - stack_traces: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - error_message: str = proto.Field( - proto.STRING, - number=2, - ) - attack_vector: AttackVector = proto.Field( - proto.ENUM, - number=3, - enum=AttackVector, - ) - stored_xss_seeding_url: str = proto.Field( - proto.STRING, - number=4, - ) - - -class Xxe(proto.Message): - r"""Information reported for an XXE. - - Attributes: - payload_value (str): - The XML string that triggered the XXE - vulnerability. Non-payload values might be - redacted. - payload_location (google.cloud.websecurityscanner_v1.types.Xxe.Location): - Location within the request where the payload - was placed. - """ - class Location(proto.Enum): - r"""Locations within a request where XML was substituted. - - Values: - LOCATION_UNSPECIFIED (0): - Unknown Location. - COMPLETE_REQUEST_BODY (1): - The XML payload replaced the complete request - body. - """ - LOCATION_UNSPECIFIED = 0 - COMPLETE_REQUEST_BODY = 1 - - payload_value: str = proto.Field( - proto.STRING, - number=1, - ) - payload_location: Location = proto.Field( - proto.ENUM, - number=2, - enum=Location, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py deleted file mode 100644 index f78910e4e18b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'FindingTypeStats', - }, -) - - -class FindingTypeStats(proto.Message): - r"""A FindingTypeStats resource represents stats regarding a - specific FindingType of Findings under a given ScanRun. - - Attributes: - finding_type (str): - Output only. The finding type associated with - the stats. - finding_count (int): - Output only. The count of findings belonging - to this finding type. - """ - - finding_type: str = proto.Field( - proto.STRING, - number=1, - ) - finding_count: int = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config.py deleted file mode 100644 index fe4b7c4479dc..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config.py +++ /dev/null @@ -1,361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner.v1', - manifest={ - 'ScanConfig', - }, -) - - -class ScanConfig(proto.Message): - r"""A ScanConfig resource contains the configurations to launch a - scan. - - Attributes: - name (str): - The resource name of the ScanConfig. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - The ScanConfig IDs are generated by the system. - display_name (str): - Required. The user provided display name of - the ScanConfig. - max_qps (int): - The maximum QPS during scanning. A valid value ranges from 5 - to 20 inclusively. If the field is unspecified or its value - is set 0, server will default to 15. Other values outside of - [5, 20] range will be rejected with INVALID_ARGUMENT error. - starting_urls (MutableSequence[str]): - Required. The starting URLs from which the - scanner finds site pages. - authentication (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication): - The authentication configuration. If - specified, service will use the authentication - configuration during scanning. - user_agent (google.cloud.websecurityscanner_v1.types.ScanConfig.UserAgent): - The user agent used during scanning. - blacklist_patterns (MutableSequence[str]): - The excluded URL patterns as described in - https://cloud.google.com/security-command-center/docs/how-to-use-web-security-scanner#excluding_urls - schedule (google.cloud.websecurityscanner_v1.types.ScanConfig.Schedule): - The schedule of the ScanConfig. - export_to_security_command_center (google.cloud.websecurityscanner_v1.types.ScanConfig.ExportToSecurityCommandCenter): - Controls export of scan configurations and - results to Security Command Center. - risk_level (google.cloud.websecurityscanner_v1.types.ScanConfig.RiskLevel): - The risk level selected for the scan - managed_scan (bool): - Whether the scan config is managed by Web - Security Scanner, output only. - static_ip_scan (bool): - Whether the scan configuration has enabled - static IP address scan feature. If enabled, the - scanner will access applications from static IP - addresses. - ignore_http_status_errors (bool): - Whether to keep scanning even if most - requests return HTTP error codes. - """ - class UserAgent(proto.Enum): - r"""Type of user agents used for scanning. - - Values: - USER_AGENT_UNSPECIFIED (0): - The user agent is unknown. Service will default to - CHROME_LINUX. - CHROME_LINUX (1): - Chrome on Linux. This is the service default - if unspecified. - CHROME_ANDROID (2): - Chrome on Android. - SAFARI_IPHONE (3): - Safari on IPhone. - """ - USER_AGENT_UNSPECIFIED = 0 - CHROME_LINUX = 1 - CHROME_ANDROID = 2 - SAFARI_IPHONE = 3 - - class RiskLevel(proto.Enum): - r"""Scan risk levels supported by Web Security Scanner. LOW - impact scanning will minimize requests with the potential to - modify data. To achieve the maximum scan coverage, NORMAL risk - level is recommended. - - Values: - RISK_LEVEL_UNSPECIFIED (0): - Use default, which is NORMAL. - NORMAL (1): - Normal scanning (Recommended) - LOW (2): - Lower impact scanning - """ - RISK_LEVEL_UNSPECIFIED = 0 - NORMAL = 1 - LOW = 2 - - class ExportToSecurityCommandCenter(proto.Enum): - r"""Controls export of scan configurations and results to - Security Command Center. - - Values: - EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED (0): - Use default, which is ENABLED. - ENABLED (1): - Export results of this scan to Security - Command Center. - DISABLED (2): - Do not export results of this scan to - Security Command Center. - """ - EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - - class Authentication(proto.Message): - r"""Scan authentication configuration. - - 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_account (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.GoogleAccount): - Authentication using a Google account. - - This field is a member of `oneof`_ ``authentication``. - custom_account (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.CustomAccount): - Authentication using a custom account. - - This field is a member of `oneof`_ ``authentication``. - iap_credential (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.IapCredential): - Authentication using Identity-Aware-Proxy - (IAP). - - This field is a member of `oneof`_ ``authentication``. - """ - - class GoogleAccount(proto.Message): - r"""Describes authentication configuration that uses a Google - account. - - Attributes: - username (str): - Required. The user name of the Google - account. - password (str): - Required. Input only. The password of the - Google account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - password: str = proto.Field( - proto.STRING, - number=2, - ) - - class CustomAccount(proto.Message): - r"""Describes authentication configuration that uses a custom - account. - - Attributes: - username (str): - Required. The user name of the custom - account. - password (str): - Required. Input only. The password of the - custom account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - login_url (str): - Required. The login form URL of the website. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - password: str = proto.Field( - proto.STRING, - number=2, - ) - login_url: str = proto.Field( - proto.STRING, - number=3, - ) - - class IapCredential(proto.Message): - r"""Describes authentication configuration for - Identity-Aware-Proxy (IAP). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - iap_test_service_account_info (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo): - Authentication configuration when - Web-Security-Scanner service account is added in - Identity-Aware-Proxy (IAP) access policies. - - This field is a member of `oneof`_ ``iap_credentials``. - """ - - class IapTestServiceAccountInfo(proto.Message): - r"""Describes authentication configuration when - Web-Security-Scanner service account is added in - Identity-Aware-Proxy (IAP) access policies. - - Attributes: - target_audience_client_id (str): - Required. Describes OAuth2 client id of - resources protected by Identity-Aware-Proxy - (IAP). - """ - - target_audience_client_id: str = proto.Field( - proto.STRING, - number=1, - ) - - iap_test_service_account_info: 'ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo' = proto.Field( - proto.MESSAGE, - number=1, - oneof='iap_credentials', - message='ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo', - ) - - google_account: 'ScanConfig.Authentication.GoogleAccount' = proto.Field( - proto.MESSAGE, - number=1, - oneof='authentication', - message='ScanConfig.Authentication.GoogleAccount', - ) - custom_account: 'ScanConfig.Authentication.CustomAccount' = proto.Field( - proto.MESSAGE, - number=2, - oneof='authentication', - message='ScanConfig.Authentication.CustomAccount', - ) - iap_credential: 'ScanConfig.Authentication.IapCredential' = proto.Field( - proto.MESSAGE, - number=4, - oneof='authentication', - message='ScanConfig.Authentication.IapCredential', - ) - - class Schedule(proto.Message): - r"""Scan schedule configuration. - - Attributes: - schedule_time (google.protobuf.timestamp_pb2.Timestamp): - A timestamp indicates when the next run will - be scheduled. The value is refreshed by the - server after each run. If unspecified, it will - default to current server time, which means the - scan will be scheduled to start immediately. - interval_duration_days (int): - Required. The duration of time between - executions in days. - """ - - schedule_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - interval_duration_days: int = proto.Field( - proto.INT32, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - max_qps: int = proto.Field( - proto.INT32, - number=3, - ) - starting_urls: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - authentication: Authentication = proto.Field( - proto.MESSAGE, - number=5, - message=Authentication, - ) - user_agent: UserAgent = proto.Field( - proto.ENUM, - number=6, - enum=UserAgent, - ) - blacklist_patterns: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - schedule: Schedule = proto.Field( - proto.MESSAGE, - number=8, - message=Schedule, - ) - export_to_security_command_center: ExportToSecurityCommandCenter = proto.Field( - proto.ENUM, - number=10, - enum=ExportToSecurityCommandCenter, - ) - risk_level: RiskLevel = proto.Field( - proto.ENUM, - number=12, - enum=RiskLevel, - ) - managed_scan: bool = proto.Field( - proto.BOOL, - number=13, - ) - static_ip_scan: bool = proto.Field( - proto.BOOL, - number=14, - ) - ignore_http_status_errors: bool = proto.Field( - proto.BOOL, - number=15, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py deleted file mode 100644 index 3667d0f1c616..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner.v1', - manifest={ - 'ScanConfigError', - }, -) - - -class ScanConfigError(proto.Message): - r"""Defines a custom error message used by CreateScanConfig and - UpdateScanConfig APIs when scan configuration validation fails. - It is also reported as part of a ScanRunErrorTrace message if - scan validation fails due to a scan configuration error. - - Attributes: - code (google.cloud.websecurityscanner_v1.types.ScanConfigError.Code): - Output only. Indicates the reason code for a - configuration failure. - field_name (str): - Output only. Indicates the full name of the ScanConfig field - that triggers this error, for example "scan_config.max_qps". - This field is provided for troubleshooting purposes only and - its actual value can change in the future. - """ - class Code(proto.Enum): - r"""Output only. - Defines an error reason code. - Next id: 44 - - Values: - CODE_UNSPECIFIED (0): - There is no error. - OK (0): - There is no error. - INTERNAL_ERROR (1): - Indicates an internal server error. - Please DO NOT USE THIS ERROR CODE unless the - root cause is truly unknown. - APPENGINE_API_BACKEND_ERROR (2): - One of the seed URLs is an App Engine URL but - we cannot validate the scan settings due to an - App Engine API backend error. - APPENGINE_API_NOT_ACCESSIBLE (3): - One of the seed URLs is an App Engine URL but - we cannot access the App Engine API to validate - scan settings. - APPENGINE_DEFAULT_HOST_MISSING (4): - One of the seed URLs is an App Engine URL but - the Default Host of the App Engine is not set. - CANNOT_USE_GOOGLE_COM_ACCOUNT (6): - Google corporate accounts can not be used for - scanning. - CANNOT_USE_OWNER_ACCOUNT (7): - The account of the scan creator can not be - used for scanning. - COMPUTE_API_BACKEND_ERROR (8): - This scan targets Compute Engine, but we - cannot validate scan settings due to a Compute - Engine API backend error. - COMPUTE_API_NOT_ACCESSIBLE (9): - This scan targets Compute Engine, but we - cannot access the Compute Engine API to validate - the scan settings. - CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT (10): - The Custom Login URL does not belong to the - current project. - CUSTOM_LOGIN_URL_MALFORMED (11): - The Custom Login URL is malformed (can not be - parsed). - CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS (12): - The Custom Login URL is mapped to a - non-routable IP address in DNS. - CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS (13): - The Custom Login URL is mapped to an IP - address which is not reserved for the current - project. - CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS (14): - The Custom Login URL has a non-routable IP - address. - CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS (15): - The Custom Login URL has an IP address which - is not reserved for the current project. - DUPLICATE_SCAN_NAME (16): - Another scan with the same name - (case-sensitive) already exists. - INVALID_FIELD_VALUE (18): - A field is set to an invalid value. - FAILED_TO_AUTHENTICATE_TO_TARGET (19): - There was an error trying to authenticate to - the scan target. - FINDING_TYPE_UNSPECIFIED (20): - Finding type value is not specified in the - list findings request. - FORBIDDEN_TO_SCAN_COMPUTE (21): - Scan targets Compute Engine, yet current - project was not whitelisted for Google Compute - Engine Scanning Alpha access. - FORBIDDEN_UPDATE_TO_MANAGED_SCAN (43): - User tries to update managed scan - MALFORMED_FILTER (22): - The supplied filter is malformed. For - example, it can not be parsed, does not have a - filter type in expression, or the same filter - type appears more than once. - MALFORMED_RESOURCE_NAME (23): - The supplied resource name is malformed (can - not be parsed). - PROJECT_INACTIVE (24): - The current project is not in an active - state. - REQUIRED_FIELD (25): - A required field is not set. - RESOURCE_NAME_INCONSISTENT (26): - Project id, scanconfig id, scanrun id, or - finding id are not consistent with each other in - resource name. - SCAN_ALREADY_RUNNING (27): - The scan being requested to start is already - running. - SCAN_NOT_RUNNING (28): - The scan that was requested to be stopped is - not running. - SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT (29): - One of the seed URLs does not belong to the - current project. - SEED_URL_MALFORMED (30): - One of the seed URLs is malformed (can not be - parsed). - SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS (31): - One of the seed URLs is mapped to a - non-routable IP address in DNS. - SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS (32): - One of the seed URLs is mapped to an IP - address which is not reserved for the current - project. - SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS (33): - One of the seed URLs has on-routable IP - address. - SEED_URL_HAS_UNRESERVED_IP_ADDRESS (35): - One of the seed URLs has an IP address that - is not reserved for the current project. - SERVICE_ACCOUNT_NOT_CONFIGURED (36): - The Web Security Scanner service account is - not configured under the project. - TOO_MANY_SCANS (37): - A project has reached the maximum number of - scans. - UNABLE_TO_RESOLVE_PROJECT_INFO (38): - Resolving the details of the current project - fails. - UNSUPPORTED_BLACKLIST_PATTERN_FORMAT (39): - One or more blacklist patterns were in the - wrong format. - UNSUPPORTED_FILTER (40): - The supplied filter is not supported. - UNSUPPORTED_FINDING_TYPE (41): - The supplied finding type is not supported. - For example, we do not provide findings of the - given finding type. - UNSUPPORTED_URL_SCHEME (42): - The URL scheme of one or more of the supplied - URLs is not supported. - """ - _pb_options = {'allow_alias': True} - CODE_UNSPECIFIED = 0 - OK = 0 - INTERNAL_ERROR = 1 - APPENGINE_API_BACKEND_ERROR = 2 - APPENGINE_API_NOT_ACCESSIBLE = 3 - APPENGINE_DEFAULT_HOST_MISSING = 4 - CANNOT_USE_GOOGLE_COM_ACCOUNT = 6 - CANNOT_USE_OWNER_ACCOUNT = 7 - COMPUTE_API_BACKEND_ERROR = 8 - COMPUTE_API_NOT_ACCESSIBLE = 9 - CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 10 - CUSTOM_LOGIN_URL_MALFORMED = 11 - CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 12 - CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS = 13 - CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 14 - CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS = 15 - DUPLICATE_SCAN_NAME = 16 - INVALID_FIELD_VALUE = 18 - FAILED_TO_AUTHENTICATE_TO_TARGET = 19 - FINDING_TYPE_UNSPECIFIED = 20 - FORBIDDEN_TO_SCAN_COMPUTE = 21 - FORBIDDEN_UPDATE_TO_MANAGED_SCAN = 43 - MALFORMED_FILTER = 22 - MALFORMED_RESOURCE_NAME = 23 - PROJECT_INACTIVE = 24 - REQUIRED_FIELD = 25 - RESOURCE_NAME_INCONSISTENT = 26 - SCAN_ALREADY_RUNNING = 27 - SCAN_NOT_RUNNING = 28 - SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 29 - SEED_URL_MALFORMED = 30 - SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 31 - SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS = 32 - SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 33 - SEED_URL_HAS_UNRESERVED_IP_ADDRESS = 35 - SERVICE_ACCOUNT_NOT_CONFIGURED = 36 - TOO_MANY_SCANS = 37 - UNABLE_TO_RESOLVE_PROJECT_INFO = 38 - UNSUPPORTED_BLACKLIST_PATTERN_FORMAT = 39 - UNSUPPORTED_FILTER = 40 - UNSUPPORTED_FINDING_TYPE = 41 - UNSUPPORTED_URL_SCHEME = 42 - - code: Code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - field_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run.py deleted file mode 100644 index 9b0aff3df801..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run.py +++ /dev/null @@ -1,181 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner_v1.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'ScanRun', - }, -) - - -class ScanRun(proto.Message): - r"""A ScanRun is a output-only resource representing an actual - run of the scan. Next id: 12 - - Attributes: - name (str): - Output only. The resource name of the - ScanRun. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - The ScanRun IDs are generated by the system. - execution_state (google.cloud.websecurityscanner_v1.types.ScanRun.ExecutionState): - Output only. The execution state of the - ScanRun. - result_state (google.cloud.websecurityscanner_v1.types.ScanRun.ResultState): - Output only. The result state of the ScanRun. - This field is only available after the execution - state reaches "FINISHED". - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the ScanRun - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the ScanRun - reached termination state - that the ScanRun is - either finished or stopped by user. - urls_crawled_count (int): - Output only. The number of URLs crawled - during this ScanRun. If the scan is in progress, - the value represents the number of URLs crawled - up to now. - urls_tested_count (int): - Output only. The number of URLs tested during - this ScanRun. If the scan is in progress, the - value represents the number of URLs tested up to - now. The number of URLs tested is usually larger - than the number URLS crawled because typically a - crawled URL is tested with multiple test - payloads. - has_vulnerabilities (bool): - Output only. Whether the scan run has found - any vulnerabilities. - progress_percent (int): - Output only. The percentage of total - completion ranging from 0 to 100. If the scan is - in queue, the value is 0. If the scan is - running, the value ranges from 0 to 100. If the - scan is finished, the value is 100. - error_trace (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace): - Output only. If result_state is an ERROR, this field - provides the primary reason for scan's termination and more - details, if such are available. - warning_traces (MutableSequence[google.cloud.websecurityscanner_v1.types.ScanRunWarningTrace]): - Output only. A list of warnings, if such are - encountered during this scan run. - """ - class ExecutionState(proto.Enum): - r"""Types of ScanRun execution state. - - Values: - EXECUTION_STATE_UNSPECIFIED (0): - Represents an invalid state caused by - internal server error. This value should never - be returned. - QUEUED (1): - The scan is waiting in the queue. - SCANNING (2): - The scan is in progress. - FINISHED (3): - The scan is either finished or stopped by - user. - """ - EXECUTION_STATE_UNSPECIFIED = 0 - QUEUED = 1 - SCANNING = 2 - FINISHED = 3 - - class ResultState(proto.Enum): - r"""Types of ScanRun result state. - - Values: - RESULT_STATE_UNSPECIFIED (0): - Default value. This value is returned when - the ScanRun is not yet finished. - SUCCESS (1): - The scan finished without errors. - ERROR (2): - The scan finished with errors. - KILLED (3): - The scan was terminated by user. - """ - RESULT_STATE_UNSPECIFIED = 0 - SUCCESS = 1 - ERROR = 2 - KILLED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - execution_state: ExecutionState = proto.Field( - proto.ENUM, - number=2, - enum=ExecutionState, - ) - result_state: ResultState = proto.Field( - proto.ENUM, - number=3, - enum=ResultState, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - urls_crawled_count: int = proto.Field( - proto.INT64, - number=6, - ) - urls_tested_count: int = proto.Field( - proto.INT64, - number=7, - ) - has_vulnerabilities: bool = proto.Field( - proto.BOOL, - number=8, - ) - progress_percent: int = proto.Field( - proto.INT32, - number=9, - ) - error_trace: scan_run_error_trace.ScanRunErrorTrace = proto.Field( - proto.MESSAGE, - number=10, - message=scan_run_error_trace.ScanRunErrorTrace, - ) - warning_traces: MutableSequence[scan_run_warning_trace.ScanRunWarningTrace] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=scan_run_warning_trace.ScanRunWarningTrace, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py deleted file mode 100644 index 4b95f35270df..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner_v1.types import scan_config_error as gcw_scan_config_error - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'ScanRunErrorTrace', - }, -) - - -class ScanRunErrorTrace(proto.Message): - r"""Output only. - Defines an error trace message for a ScanRun. - - Attributes: - code (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace.Code): - Output only. Indicates the error reason code. - scan_config_error (google.cloud.websecurityscanner_v1.types.ScanConfigError): - Output only. If the scan encounters SCAN_CONFIG_ISSUE error, - this field has the error message encountered during scan - configuration validation that is performed before each scan - run. - most_common_http_error_code (int): - Output only. If the scan encounters TOO_MANY_HTTP_ERRORS, - this field indicates the most common HTTP error code, if - such is available. For example, if this code is 404, the - scan has encountered too many NOT_FOUND responses. - """ - class Code(proto.Enum): - r"""Output only. - Defines an error reason code. - Next id: 8 - - Values: - CODE_UNSPECIFIED (0): - Default value is never used. - INTERNAL_ERROR (1): - Indicates that the scan run failed due to an - internal server error. - SCAN_CONFIG_ISSUE (2): - Indicates a scan configuration error, usually due to - outdated ScanConfig settings, such as starting_urls or the - DNS configuration. - AUTHENTICATION_CONFIG_ISSUE (3): - Indicates an authentication error, usually - due to outdated ScanConfig authentication - settings. - TIMED_OUT_WHILE_SCANNING (4): - Indicates a scan operation timeout, usually - caused by a very large site. - TOO_MANY_REDIRECTS (5): - Indicates that a scan encountered excessive - redirects, either to authentication or some - other page outside of the scan scope. - TOO_MANY_HTTP_ERRORS (6): - Indicates that a scan encountered numerous errors from the - web site pages. When available, most_common_http_error_code - field indicates the most common HTTP error code encountered - during the scan. - """ - CODE_UNSPECIFIED = 0 - INTERNAL_ERROR = 1 - SCAN_CONFIG_ISSUE = 2 - AUTHENTICATION_CONFIG_ISSUE = 3 - TIMED_OUT_WHILE_SCANNING = 4 - TOO_MANY_REDIRECTS = 5 - TOO_MANY_HTTP_ERRORS = 6 - - code: Code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - scan_config_error: gcw_scan_config_error.ScanConfigError = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config_error.ScanConfigError, - ) - most_common_http_error_code: int = proto.Field( - proto.INT32, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_log.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_log.py deleted file mode 100644 index d7a72ad4a6f9..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_log.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.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import scan_run_error_trace - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'ScanRunLog', - }, -) - - -class ScanRunLog(proto.Message): - r"""A ScanRunLog is an output-only proto used for Stackdriver - customer logging. It is used for logs covering the start and end - of scan pipelines. Other than an added summary, this is a subset - of the ScanRun. Representation in logs is either a proto Struct, - or converted to JSON. Next id: 9 - - Attributes: - summary (str): - Human friendly message about the event. - name (str): - The resource name of the ScanRun being - logged. - execution_state (google.cloud.websecurityscanner_v1.types.ScanRun.ExecutionState): - The execution state of the ScanRun. - result_state (google.cloud.websecurityscanner_v1.types.ScanRun.ResultState): - The result state of the ScanRun. - urls_crawled_count (int): - - urls_tested_count (int): - - has_findings (bool): - - error_trace (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace): - - """ - - summary: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - execution_state: scan_run.ScanRun.ExecutionState = proto.Field( - proto.ENUM, - number=3, - enum=scan_run.ScanRun.ExecutionState, - ) - result_state: scan_run.ScanRun.ResultState = proto.Field( - proto.ENUM, - number=4, - enum=scan_run.ScanRun.ResultState, - ) - urls_crawled_count: int = proto.Field( - proto.INT64, - number=5, - ) - urls_tested_count: int = proto.Field( - proto.INT64, - number=6, - ) - has_findings: bool = proto.Field( - proto.BOOL, - number=7, - ) - error_trace: scan_run_error_trace.ScanRunErrorTrace = proto.Field( - proto.MESSAGE, - number=8, - message=scan_run_error_trace.ScanRunErrorTrace, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py deleted file mode 100644 index 18de95d60dd3..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'ScanRunWarningTrace', - }, -) - - -class ScanRunWarningTrace(proto.Message): - r"""Output only. - Defines a warning trace message for ScanRun. Warning traces - provide customers with useful information that helps make the - scanning process more effective. - - Attributes: - code (google.cloud.websecurityscanner_v1.types.ScanRunWarningTrace.Code): - Output only. Indicates the warning code. - """ - class Code(proto.Enum): - r"""Output only. - Defines a warning message code. - Next id: 6 - - Values: - CODE_UNSPECIFIED (0): - Default value is never used. - INSUFFICIENT_CRAWL_RESULTS (1): - Indicates that a scan discovered an - unexpectedly low number of URLs. This is - sometimes caused by complex navigation features - or by using a single URL for numerous pages. - TOO_MANY_CRAWL_RESULTS (2): - Indicates that a scan discovered too many - URLs to test, or excessive redundant URLs. - TOO_MANY_FUZZ_TASKS (3): - Indicates that too many tests have been - generated for the scan. Customer should try - reducing the number of starting URLs, increasing - the QPS rate, or narrowing down the scope of the - scan using the excluded patterns. - BLOCKED_BY_IAP (4): - Indicates that a scan is blocked by IAP. - NO_STARTING_URL_FOUND_FOR_MANAGED_SCAN (5): - Indicates that no seeds is found for a scan - """ - CODE_UNSPECIFIED = 0 - INSUFFICIENT_CRAWL_RESULTS = 1 - TOO_MANY_CRAWL_RESULTS = 2 - TOO_MANY_FUZZ_TASKS = 3 - BLOCKED_BY_IAP = 4 - NO_STARTING_URL_FOUND_FOR_MANAGED_SCAN = 5 - - code: Code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py deleted file mode 100644 index ebe221ec6b5f..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.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.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import finding_type_stats as gcw_finding_type_stats -from google.cloud.websecurityscanner_v1.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetScanConfigRequest', - 'ListScanConfigsRequest', - 'UpdateScanConfigRequest', - 'ListScanConfigsResponse', - 'StartScanRunRequest', - 'GetScanRunRequest', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StopScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'GetFindingRequest', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - }, -) - - -class CreateScanConfigRequest(proto.Message): - r"""Request for the ``CreateScanConfig`` method. - - Attributes: - parent (str): - Required. The parent resource name where the - scan is created, which should be a project - resource name in the format - 'projects/{projectId}'. - scan_config (google.cloud.websecurityscanner_v1.types.ScanConfig): - Required. The ScanConfig to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - scan_config: gcw_scan_config.ScanConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - - -class DeleteScanConfigRequest(proto.Message): - r"""Request for the ``DeleteScanConfig`` method. - - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be deleted. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanConfigRequest(proto.Message): - r"""Request for the ``GetScanConfig`` method. - - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanConfigsRequest(proto.Message): - r"""Request for the ``ListScanConfigs`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a project resource name in the format - 'projects/{projectId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanConfigs to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class UpdateScanConfigRequest(proto.Message): - r"""Request for the ``UpdateScanConfigRequest`` method. - - Attributes: - scan_config (google.cloud.websecurityscanner_v1.types.ScanConfig): - Required. The ScanConfig to be updated. The - name field must be set to identify the resource - to be updated. The values of fields not covered - by the mask will be ignored. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For the - ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - """ - - scan_config: gcw_scan_config.ScanConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ListScanConfigsResponse(proto.Message): - r"""Response for the ``ListScanConfigs`` method. - - Attributes: - scan_configs (MutableSequence[google.cloud.websecurityscanner_v1.types.ScanConfig]): - The list of ScanConfigs returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_configs: MutableSequence[gcw_scan_config.ScanConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_scan_config.ScanConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class StartScanRunRequest(proto.Message): - r"""Request for the ``StartScanRun`` method. - - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be used. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanRunRequest(proto.Message): - r"""Request for the ``GetScanRun`` method. - - Attributes: - name (str): - Required. The resource name of the ScanRun to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanRunsRequest(proto.Message): - r"""Request for the ``ListScanRuns`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanRuns to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListScanRunsResponse(proto.Message): - r"""Response for the ``ListScanRuns`` method. - - Attributes: - scan_runs (MutableSequence[google.cloud.websecurityscanner_v1.types.ScanRun]): - The list of ScanRuns returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_runs: MutableSequence[scan_run.ScanRun] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=scan_run.ScanRun, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class StopScanRunRequest(proto.Message): - r"""Request for the ``StopScanRun`` method. - - Attributes: - name (str): - Required. The resource name of the ScanRun to - be stopped. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListCrawledUrlsRequest(proto.Message): - r"""Request for the ``ListCrawledUrls`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of CrawledUrls to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCrawledUrlsResponse(proto.Message): - r"""Response for the ``ListCrawledUrls`` method. - - Attributes: - crawled_urls (MutableSequence[google.cloud.websecurityscanner_v1.types.CrawledUrl]): - The list of CrawledUrls returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - crawled_urls: MutableSequence[crawled_url.CrawledUrl] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=crawled_url.CrawledUrl, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFindingRequest(proto.Message): - r"""Request for the ``GetFinding`` method. - - Attributes: - name (str): - Required. The resource name of the Finding to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request for the ``ListFindings`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - filter (str): - The filter expression. The expression must be in the format: - . Supported field: 'finding_type'. Supported operator: '='. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of Findings to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response for the ``ListFindings`` method. - - Attributes: - findings (MutableSequence[google.cloud.websecurityscanner_v1.types.Finding]): - The list of Findings returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - findings: MutableSequence[finding.Finding] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=finding.Finding, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListFindingTypeStatsRequest(proto.Message): - r"""Request for the ``ListFindingTypeStats`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingTypeStatsResponse(proto.Message): - r"""Response for the ``ListFindingTypeStats`` method. - - Attributes: - finding_type_stats (MutableSequence[google.cloud.websecurityscanner_v1.types.FindingTypeStats]): - The list of FindingTypeStats returned. - """ - - finding_type_stats: MutableSequence[gcw_finding_type_stats.FindingTypeStats] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_finding_type_stats.FindingTypeStats, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/mypy.ini b/owl-bot-staging/google-cloud-websecurityscanner/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/noxfile.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/noxfile.py deleted file mode 100644 index a68dcccfef3f..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner' - -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/cloud/websecurityscanner_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/cloud/websecurityscanner_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-cloud-websecurityscanner/v1/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json deleted file mode 100644 index 030ea8082797..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json +++ /dev/null @@ -1,1998 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.websecurityscanner.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-websecurityscanner", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.create_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.CreateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "CreateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", - "shortName": "create_scan_config" - }, - "description": "Sample for CreateScanConfig", - "file": "websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.create_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.CreateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "CreateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", - "shortName": "create_scan_config" - }, - "description": "Sample for CreateScanConfig", - "file": "websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.delete_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.DeleteScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "DeleteScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_scan_config" - }, - "description": "Sample for DeleteScanConfig", - "file": "websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_async", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.delete_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.DeleteScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "DeleteScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_scan_config" - }, - "description": "Sample for DeleteScanConfig", - "file": "websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_sync", - "segments": [ - { - "end": 48, - "start": 27, - "type": "FULL" - }, - { - "end": 48, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.get_finding", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetFinding", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.GetFindingRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.Finding", - "shortName": "get_finding" - }, - "description": "Sample for GetFinding", - "file": "websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.get_finding", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetFinding", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.GetFindingRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.Finding", - "shortName": "get_finding" - }, - "description": "Sample for GetFinding", - "file": "websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.get_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.GetScanConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", - "shortName": "get_scan_config" - }, - "description": "Sample for GetScanConfig", - "file": "websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.get_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.GetScanConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", - "shortName": "get_scan_config" - }, - "description": "Sample for GetScanConfig", - "file": "websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.get_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.GetScanRunRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", - "shortName": "get_scan_run" - }, - "description": "Sample for GetScanRun", - "file": "websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.get_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.GetScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.GetScanRunRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", - "shortName": "get_scan_run" - }, - "description": "Sample for GetScanRun", - "file": "websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_crawled_urls", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListCrawledUrls", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListCrawledUrls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager", - "shortName": "list_crawled_urls" - }, - "description": "Sample for ListCrawledUrls", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_crawled_urls", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListCrawledUrls", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListCrawledUrls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsPager", - "shortName": "list_crawled_urls" - }, - "description": "Sample for ListCrawledUrls", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_finding_type_stats", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListFindingTypeStats", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindingTypeStats" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse", - "shortName": "list_finding_type_stats" - }, - "description": "Sample for ListFindingTypeStats", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_finding_type_stats", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListFindingTypeStats", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindingTypeStats" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse", - "shortName": "list_finding_type_stats" - }, - "description": "Sample for ListFindingTypeStats", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListFindings", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListFindingsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_findings", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListFindings", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListFindingsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_scan_configs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListScanConfigs", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsAsyncPager", - "shortName": "list_scan_configs" - }, - "description": "Sample for ListScanConfigs", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_scan_configs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListScanConfigs", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsPager", - "shortName": "list_scan_configs" - }, - "description": "Sample for ListScanConfigs", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.list_scan_runs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListScanRuns", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanRuns" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListScanRunsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsAsyncPager", - "shortName": "list_scan_runs" - }, - "description": "Sample for ListScanRuns", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.list_scan_runs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.ListScanRuns", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanRuns" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.ListScanRunsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsPager", - "shortName": "list_scan_runs" - }, - "description": "Sample for ListScanRuns", - "file": "websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.start_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.StartScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StartScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.StartScanRunRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", - "shortName": "start_scan_run" - }, - "description": "Sample for StartScanRun", - "file": "websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.start_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.StartScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StartScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.StartScanRunRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", - "shortName": "start_scan_run" - }, - "description": "Sample for StartScanRun", - "file": "websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.stop_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.StopScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StopScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.StopScanRunRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", - "shortName": "stop_scan_run" - }, - "description": "Sample for StopScanRun", - "file": "websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.stop_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.StopScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StopScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.StopScanRunRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanRun", - "shortName": "stop_scan_run" - }, - "description": "Sample for StopScanRun", - "file": "websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerAsyncClient.update_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.UpdateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "UpdateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", - "shortName": "update_scan_config" - }, - "description": "Sample for UpdateScanConfig", - "file": "websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1.WebSecurityScannerClient.update_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner.UpdateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "UpdateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1.types.ScanConfig", - "shortName": "update_scan_config" - }, - "description": "Sample for UpdateScanConfig", - "file": "websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_async.py deleted file mode 100644 index 92e4d2fef54c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_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 CreateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.CreateScanConfigRequest( - ) - - # Make the request - response = await client.create_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_sync.py deleted file mode 100644 index b11d384eb0ce..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_create_scan_config_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 CreateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.CreateScanConfigRequest( - ) - - # Make the request - response = client.create_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_CreateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.py deleted file mode 100644 index 628a5f9ff1ba..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.DeleteScanConfigRequest( - ) - - # Make the request - await client.delete_scan_config(request=request) - - -# [END websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.py deleted file mode 100644 index a234124ec93b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_delete_scan_config_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.DeleteScanConfigRequest( - ) - - # Make the request - client.delete_scan_config(request=request) - - -# [END websecurityscanner_v1_generated_WebSecurityScanner_DeleteScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_async.py deleted file mode 100644 index 94a5ab16ed40..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_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 GetFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_get_finding(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetFindingRequest( - ) - - # Make the request - response = await client.get_finding(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_sync.py deleted file mode 100644 index a48e371ca205..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_finding_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 GetFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_get_finding(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetFindingRequest( - ) - - # Make the request - response = client.get_finding(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_GetFinding_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_async.py deleted file mode 100644 index 83ed87c87183..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_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 GetScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetScanConfigRequest( - ) - - # Make the request - response = await client.get_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_sync.py deleted file mode 100644 index c632fb367432..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_config_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 GetScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetScanConfigRequest( - ) - - # Make the request - response = client.get_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_GetScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_async.py deleted file mode 100644 index a9c9137dd3ea..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_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 GetScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetScanRunRequest( - ) - - # Make the request - response = await client.get_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_sync.py deleted file mode 100644 index 53c1024650f6..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_get_scan_run_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 GetScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.GetScanRunRequest( - ) - - # Make the request - response = client.get_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_GetScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_async.py deleted file mode 100644 index 55e2566d061d..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListCrawledUrlsRequest( - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_sync.py deleted file mode 100644 index 859e162a3114..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListCrawledUrlsRequest( - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListCrawledUrls_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_async.py deleted file mode 100644 index 05b6814cd287..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListFindingTypeStatsRequest( - ) - - # Make the request - response = await client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_sync.py deleted file mode 100644 index f9f18e708cfa..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListFindingTypeStatsRequest( - ) - - # Make the request - response = client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListFindingTypeStats_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_async.py deleted file mode 100644 index b8265b419552..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_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 ListFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_list_findings(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListFindingsRequest( - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_sync.py deleted file mode 100644 index b8cc02d833da..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_findings_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 ListFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_list_findings(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListFindingsRequest( - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_async.py deleted file mode 100644 index 101dfc951439..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListScanConfigsRequest( - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_sync.py deleted file mode 100644 index 5e0fda7c9a2a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListScanConfigsRequest( - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListScanConfigs_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_async.py deleted file mode 100644 index 956ff8dd2184..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_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 ListScanRuns -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListScanRunsRequest( - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_sync.py deleted file mode 100644 index e8bb370fde0a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_list_scan_runs_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 ListScanRuns -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.ListScanRunsRequest( - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_ListScanRuns_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_async.py deleted file mode 100644 index adb10291e355..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_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 StartScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.StartScanRunRequest( - ) - - # Make the request - response = await client.start_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_sync.py deleted file mode 100644 index cd9c213b7662..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_start_scan_run_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 StartScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.StartScanRunRequest( - ) - - # Make the request - response = client.start_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_StartScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_async.py deleted file mode 100644 index eff91cdab7c5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_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 StopScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.StopScanRunRequest( - ) - - # Make the request - response = await client.stop_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_sync.py deleted file mode 100644 index 1fa670433efe..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_stop_scan_run_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 StopScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.StopScanRunRequest( - ) - - # Make the request - response = client.stop_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_StopScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_async.py deleted file mode 100644 index 54ec11cdc2c2..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -async def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.UpdateScanConfigRequest( - ) - - # Make the request - response = await client.update_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_sync.py deleted file mode 100644 index ad647d84e05a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/samples/generated_samples/websecurityscanner_v1_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1 - - -def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1.UpdateScanConfigRequest( - ) - - # Make the request - response = client.update_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1_generated_WebSecurityScanner_UpdateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/scripts/fixup_websecurityscanner_v1_keywords.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/scripts/fixup_websecurityscanner_v1_keywords.py deleted file mode 100644 index cbe5261ddc2a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/scripts/fixup_websecurityscanner_v1_keywords.py +++ /dev/null @@ -1,188 +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 websecurityscannerCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_scan_config': ('parent', 'scan_config', ), - 'delete_scan_config': ('name', ), - 'get_finding': ('name', ), - 'get_scan_config': ('name', ), - 'get_scan_run': ('name', ), - 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_finding_type_stats': ('parent', ), - 'list_scan_configs': ('parent', 'page_token', 'page_size', ), - 'list_scan_runs': ('parent', 'page_token', 'page_size', ), - 'start_scan_run': ('name', ), - 'stop_scan_run': ('name', ), - 'update_scan_config': ('scan_config', '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=websecurityscannerCallTransformer(), -): - """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 websecurityscanner 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-cloud-websecurityscanner/v1/setup.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/setup.py deleted file mode 100644 index b89eea40fd8f..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner' - - -description = "Google Cloud Websecurityscanner API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/websecurityscanner/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-cloud-websecurityscanner" - -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-cloud-websecurityscanner/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/tests/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_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-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py deleted file mode 100644 index 7c61a0f842c2..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py +++ /dev/null @@ -1,8720 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1.services.web_security_scanner import WebSecurityScannerAsyncClient -from google.cloud.websecurityscanner_v1.services.web_security_scanner import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1.services.web_security_scanner import transports -from google.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import finding_addon -from google.cloud.websecurityscanner_v1.types import finding_type_stats -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_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 WebSecurityScannerClient._get_default_mtls_endpoint(None) is None - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert WebSecurityScannerClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - WebSecurityScannerClient._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 WebSecurityScannerClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert WebSecurityScannerClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - WebSecurityScannerClient._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 WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, False) is None - assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, True) is mock_default_cert_source - assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE - default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert WebSecurityScannerClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - assert WebSecurityScannerClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - WebSecurityScannerClient._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 WebSecurityScannerClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert WebSecurityScannerClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert WebSecurityScannerClient._get_universe_domain(None, None) == WebSecurityScannerClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - WebSecurityScannerClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (WebSecurityScannerClient, "grpc"), - (WebSecurityScannerAsyncClient, "grpc_asyncio"), - (WebSecurityScannerClient, "rest"), -]) -def test_web_security_scanner_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 == ( - 'websecurityscanner.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://websecurityscanner.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WebSecurityScannerGrpcTransport, "grpc"), - (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.WebSecurityScannerRestTransport, "rest"), -]) -def test_web_security_scanner_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", [ - (WebSecurityScannerClient, "grpc"), - (WebSecurityScannerAsyncClient, "grpc_asyncio"), - (WebSecurityScannerClient, "rest"), -]) -def test_web_security_scanner_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 == ( - 'websecurityscanner.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://websecurityscanner.googleapis.com' - ) - - -def test_web_security_scanner_client_get_transport_class(): - transport = WebSecurityScannerClient.get_transport_class() - available_transports = [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerRestTransport, - ] - assert transport in available_transports - - transport = WebSecurityScannerClient.get_transport_class("grpc") - assert transport == transports.WebSecurityScannerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), -]) -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_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(WebSecurityScannerClient, '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(WebSecurityScannerClient, '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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "true"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "false"), -]) -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_web_security_scanner_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", [ - WebSecurityScannerClient, WebSecurityScannerAsyncClient -]) -@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_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", [ - WebSecurityScannerClient, WebSecurityScannerAsyncClient -]) -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE - default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WebSecurityScannerClient._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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), -]) -def test_web_security_scanner_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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", None), -]) -def test_web_security_scanner_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_web_security_scanner_client_client_options_from_dict(): - with mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WebSecurityScannerClient( - 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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_web_security_scanner_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( - "websecurityscanner.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="websecurityscanner.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.CreateScanConfigRequest, - dict, -]) -def test_create_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=True, - ) - response = client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.CreateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - assert response.ignore_http_status_errors is True - - -def test_create_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.CreateScanConfigRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.CreateScanConfigRequest( - parent='parent_value', - ) - -def test_create_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - request = {} - client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=True, - )) - response = await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.CreateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - assert response.ignore_http_status_errors is True - - -@pytest.mark.asyncio -async def test_create_scan_config_async_from_dict(): - await test_create_scan_config_async(request_type=dict) - -def test_create_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - web_security_scanner.DeleteScanConfigRequest, - dict, -]) -def test_delete_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.DeleteScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.DeleteScanConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.DeleteScanConfigRequest( - name='name_value', - ) - -def test_delete_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - request = {} - client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.DeleteScanConfigRequest() - 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_scan_config_async_from_dict(): - await test_delete_scan_config_async(request_type=dict) - -def test_delete_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = None - client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - web_security_scanner.GetScanConfigRequest, - dict, -]) -def test_get_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=True, - ) - response = client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - assert response.ignore_http_status_errors is True - - -def test_get_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.GetScanConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanConfigRequest( - name='name_value', - ) - -def test_get_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc - request = {} - client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=True, - )) - response = await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - assert response.ignore_http_status_errors is True - - -@pytest.mark.asyncio -async def test_get_scan_config_async_from_dict(): - await test_get_scan_config_async(request_type=dict) - -def test_get_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - web_security_scanner.ListScanConfigsRequest, - dict, -]) -def test_list_scan_configs(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_configs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListScanConfigsRequest( - 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_scan_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_scan_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_scan_configs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_configs] = mock_rpc - request = {} - client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_configs(request) - - # Establish that a new wrapper 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_scan_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_configs in client._client._transport._wrapped_methods - - # 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_scan_configs] = mock_rpc - - request = {} - await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_scan_configs(request) - - # Establish that a new wrapper 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_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_configs_async_from_dict(): - await test_list_scan_configs_async(request_type=dict) - -def test_list_scan_configs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanConfigsResponse() - client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_configs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_configs_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_configs(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, scan_config.ScanConfig) - for i in results) -def test_list_scan_configs_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_configs(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_scan_configs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_configs(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, scan_config.ScanConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_scan_configs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - 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_scan_configs(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", [ - web_security_scanner.UpdateScanConfigRequest, - dict, -]) -def test_update_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=True, - ) - response = client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.UpdateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - assert response.ignore_http_status_errors is True - - -def test_update_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.UpdateScanConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.UpdateScanConfigRequest( - ) - -def test_update_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - request = {} - client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=True, - )) - response = await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.UpdateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - assert response.ignore_http_status_errors is True - - -@pytest.mark.asyncio -async def test_update_scan_config_async_from_dict(): - await test_update_scan_config_async(request_type=dict) - -def test_update_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'scan_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'scan_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.StartScanRunRequest, - dict, -]) -def test_start_scan_run(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StartScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_start_scan_run_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.StartScanRunRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.start_scan_run(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest( - name='name_value', - ) - -def test_start_scan_run_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc - request = {} - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.start_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.start_scan_run in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.start_scan_run] = mock_rpc - - request = {} - await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.start_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StartScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_start_scan_run_async_from_dict(): - await test_start_scan_run_async(request_type=dict) - -def test_start_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - web_security_scanner.GetScanRunRequest, - dict, -]) -def test_get_scan_run(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_get_scan_run_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.GetScanRunRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_scan_run(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest( - name='name_value', - ) - -def test_get_scan_run_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc - request = {} - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_run(request) - - # Establish that a new wrapper 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_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_run in client._client._transport._wrapped_methods - - # 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_scan_run] = mock_rpc - - request = {} - await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_scan_run(request) - - # Establish that a new wrapper 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_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_get_scan_run_async_from_dict(): - await test_get_scan_run_async(request_type=dict) - -def test_get_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - web_security_scanner.ListScanRunsRequest, - dict, -]) -def test_list_scan_runs(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanRunsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_runs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListScanRunsRequest( - 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_scan_runs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_scan_runs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_scan_runs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_runs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_runs] = mock_rpc - request = {} - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_runs(request) - - # Establish that a new wrapper 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_scan_runs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_runs in client._client._transport._wrapped_methods - - # 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_scan_runs] = mock_rpc - - request = {} - await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_scan_runs(request) - - # Establish that a new wrapper 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_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanRunsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_runs_async_from_dict(): - await test_list_scan_runs_async(request_type=dict) - -def test_list_scan_runs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanRunsResponse() - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_runs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_runs_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_runs(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, scan_run.ScanRun) - for i in results) -def test_list_scan_runs_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_runs(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_scan_runs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_runs(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, scan_run.ScanRun) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_scan_runs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - 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_scan_runs(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", [ - web_security_scanner.StopScanRunRequest, - dict, -]) -def test_stop_scan_run(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StopScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_stop_scan_run_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.StopScanRunRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.stop_scan_run(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest( - name='name_value', - ) - -def test_stop_scan_run_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc - request = {} - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.stop_scan_run in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.stop_scan_run] = mock_rpc - - request = {} - await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.stop_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StopScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_stop_scan_run_async_from_dict(): - await test_stop_scan_run_async(request_type=dict) - -def test_stop_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - web_security_scanner.ListCrawledUrlsRequest, - dict, -]) -def test_list_crawled_urls(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListCrawledUrlsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_crawled_urls_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListCrawledUrlsRequest( - 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_crawled_urls), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_crawled_urls(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_crawled_urls_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_crawled_urls in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_crawled_urls] = mock_rpc - request = {} - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crawled_urls(request) - - # Establish that a new wrapper 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_crawled_urls_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_crawled_urls in client._client._transport._wrapped_methods - - # 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_crawled_urls] = mock_rpc - - request = {} - await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_crawled_urls(request) - - # Establish that a new wrapper 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_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListCrawledUrlsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_from_dict(): - await test_list_crawled_urls_async(request_type=dict) - -def test_list_crawled_urls_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crawled_urls_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crawled_urls_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crawled_urls(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, crawled_url.CrawledUrl) - for i in results) -def test_list_crawled_urls_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - 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_crawled_urls(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", [ - web_security_scanner.GetFindingRequest, - dict, -]) -def test_get_finding(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - finding_type='finding_type_value', - severity=finding.Finding.Severity.CRITICAL, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - ) - response = client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -def test_get_finding_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.GetFindingRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetFindingRequest( - name='name_value', - ) - -def test_get_finding_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_finding in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc - request = {} - client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_finding(request) - - # Establish that a new wrapper 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_finding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # 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_finding] = mock_rpc - - request = {} - await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_finding(request) - - # Establish that a new wrapper 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_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - finding_type='finding_type_value', - severity=finding.Finding.Severity.CRITICAL, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - )) - response = await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -@pytest.mark.asyncio -async def test_get_finding_async_from_dict(): - await test_get_finding_async(request_type=dict) - -def test_get_finding_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = finding.Finding() - client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - web_security_scanner.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_findings_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListFindingsRequest( - 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_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_findings_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_findings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_findings] = mock_rpc - request = {} - client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_findings(request) - - # Establish that a new wrapper 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_findings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_findings in client._client._transport._wrapped_methods - - # 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_findings] = mock_rpc - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_findings(request) - - # Establish that a new wrapper 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_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_findings_async_from_dict(): - await test_list_findings_async(request_type=dict) - -def test_list_findings_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingsResponse() - client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_findings_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_findings_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_findings(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, finding.Finding) - for i in results) -def test_list_findings_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - pages = list(client.list_findings(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_findings_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_findings(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, finding.Finding) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - 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_findings(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", [ - web_security_scanner.ListFindingTypeStatsRequest, - dict, -]) -def test_list_finding_type_stats(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse( - ) - response = client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingTypeStatsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -def test_list_finding_type_stats_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListFindingTypeStatsRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_finding_type_stats(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest( - parent='parent_value', - ) - -def test_list_finding_type_stats_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_finding_type_stats in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_finding_type_stats] = mock_rpc - request = {} - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_finding_type_stats(request) - - # Establish that a new wrapper 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_finding_type_stats_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_finding_type_stats in client._client._transport._wrapped_methods - - # 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_finding_type_stats] = mock_rpc - - request = {} - await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_finding_type_stats(request) - - # Establish that a new wrapper 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_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( - )) - response = await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingTypeStatsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_async_from_dict(): - await test_list_finding_type_stats_async(request_type=dict) - -def test_list_finding_type_stats_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_type_stats_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - - request = {} - client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_scan_config(request) - - # Establish 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_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - - request = {} - client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_scan_config(request) - - # Establish 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_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc - - request = {} - client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_config(request) - - # Establish 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_scan_configs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_configs] = mock_rpc - - request = {} - client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_configs(request) - - # Establish 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_scan_configs_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListScanConfigsResponse.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_scan_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, scan_config.ScanConfig) - for i in results) - - pages = list(client.list_scan_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - - request = {} - client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_scan_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_start_scan_run_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc - - request = {} - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.start_scan_run(request) - - # Establish 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_scan_run_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc - - request = {} - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_run(request) - - # Establish 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_scan_runs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_runs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_runs] = mock_rpc - - request = {} - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_runs(request) - - # Establish 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_scan_runs_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListScanRunsResponse.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/scanConfigs/sample2'} - - pager = client.list_scan_runs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, scan_run.ScanRun) - for i in results) - - pages = list(client.list_scan_runs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_stop_scan_run_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc - - request = {} - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_scan_run(request) - - # Establish 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_crawled_urls_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_crawled_urls in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_crawled_urls] = mock_rpc - - request = {} - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crawled_urls(request) - - # Establish 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_crawled_urls_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListCrawledUrlsResponse.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/scanConfigs/sample2/scanRuns/sample3'} - - pager = client.list_crawled_urls(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, crawled_url.CrawledUrl) - for i in results) - - pages = list(client.list_crawled_urls(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_finding_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_finding in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc - - request = {} - client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_finding(request) - - # Establish 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_findings_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_findings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_findings] = mock_rpc - - request = {} - client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_findings(request) - - # Establish 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_findings_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListFindingsResponse.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/scanConfigs/sample2/scanRuns/sample3'} - - pager = client.list_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, finding.Finding) - for i in results) - - pages = list(client.list_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_finding_type_stats_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_finding_type_stats in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_finding_type_stats] = mock_rpc - - request = {} - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_finding_type_stats(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - 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 = WebSecurityScannerClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WebSecurityScannerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - transports.WebSecurityScannerRestTransport, -]) -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 = WebSecurityScannerClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = WebSecurityScannerClient( - 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.create_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.CreateScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = None - client.delete_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.DeleteScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.get_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_configs_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanConfigsResponse() - client.list_scan_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanConfigsRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.update_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.UpdateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_scan_run_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.start_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StartScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_run_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.get_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_runs_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanRunsResponse() - client.list_scan_runs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanRunsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_scan_run_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.stop_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StopScanRunRequest() - - assert args[0] == request_msg - - -# This 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_crawled_urls_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - client.list_crawled_urls(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListCrawledUrlsRequest() - - assert args[0] == request_msg - - -# This 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_finding_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = finding.Finding() - client.get_finding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetFindingRequest() - - assert args[0] == request_msg - - -# This 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_findings_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingsResponse() - client.list_findings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingsRequest() - - assert args[0] == request_msg - - -# This 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_finding_type_stats_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - client.list_finding_type_stats(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingTypeStatsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = WebSecurityScannerAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=True, - )) - await client.create_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.CreateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.DeleteScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=True, - )) - await client.get_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_configs_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - )) - await client.list_scan_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=True, - )) - await client.update_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.UpdateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_start_scan_run_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - await client.start_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StartScanRunRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_run_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - await client.get_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanRunRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_runs_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - )) - await client.list_scan_runs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanRunsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_stop_scan_run_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - await client.stop_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StopScanRunRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_crawled_urls_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - )) - await client.list_crawled_urls(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListCrawledUrlsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_finding_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - finding_type='finding_type_value', - severity=finding.Finding.Severity.CRITICAL, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - )) - await client.get_finding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetFindingRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_findings_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - )) - await client.list_findings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_finding_type_stats_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( - )) - await client.list_finding_type_stats(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingTypeStatsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = WebSecurityScannerClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_scan_config_rest_bad_request(request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerClient( - 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 - client.create_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.CreateScanConfigRequest, - dict, -]) -def test_create_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["scan_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}, 'iap_credential': {'iap_test_service_account_info': {'target_audience_client_id': 'target_audience_client_id_value'}}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'export_to_security_command_center': 1, 'risk_level': 1, 'managed_scan': True, 'static_ip_scan': True, 'ignore_http_status_errors': 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 = web_security_scanner.CreateScanConfigRequest.meta.fields["scan_config"] - - 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["scan_config"].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["scan_config"][field])): - del request_init["scan_config"][field][i][subfield] - else: - del request_init["scan_config"][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 = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=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 = scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_scan_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - assert response.ignore_http_status_errors is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_create_scan_config") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_create_scan_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.CreateScanConfigRequest.pb(web_security_scanner.CreateScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) - req.return_value.content = return_value - - request = web_security_scanner.CreateScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_config.ScanConfig() - - client.create_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_scan_config_rest_bad_request(request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - client.delete_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.DeleteScanConfigRequest, - dict, -]) -def test_delete_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - response = client.delete_scan_config(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_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_delete_scan_config") as pre: - pre.assert_not_called() - pb_message = web_security_scanner.DeleteScanConfigRequest.pb(web_security_scanner.DeleteScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - - request = web_security_scanner.DeleteScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_get_scan_config_rest_bad_request(request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - client.get_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanConfigRequest, - dict, -]) -def test_get_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=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 = scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_scan_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - assert response.ignore_http_status_errors is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_config") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.GetScanConfigRequest.pb(web_security_scanner.GetScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) - req.return_value.content = return_value - - request = web_security_scanner.GetScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_config.ScanConfig() - - client.get_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_scan_configs_rest_bad_request(request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerClient( - 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 - client.list_scan_configs(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanConfigsRequest, - dict, -]) -def test_list_scan_configs_rest_call_success(request_type): - client = WebSecurityScannerClient( - 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 = web_security_scanner.ListScanConfigsResponse( - 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_scan_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_scan_configs_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_configs") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListScanConfigsRequest.pb(web_security_scanner.ListScanConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListScanConfigsResponse.to_json(web_security_scanner.ListScanConfigsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListScanConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListScanConfigsResponse() - - client.list_scan_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_scan_config_rest_bad_request(request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/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 - client.update_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.UpdateScanConfigRequest, - dict, -]) -def test_update_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} - request_init["scan_config"] = {'name': 'projects/sample1/scanConfigs/sample2', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}, 'iap_credential': {'iap_test_service_account_info': {'target_audience_client_id': 'target_audience_client_id_value'}}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'export_to_security_command_center': 1, 'risk_level': 1, 'managed_scan': True, 'static_ip_scan': True, 'ignore_http_status_errors': 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 = web_security_scanner.UpdateScanConfigRequest.meta.fields["scan_config"] - - 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["scan_config"].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["scan_config"][field])): - del request_init["scan_config"][field][i][subfield] - else: - del request_init["scan_config"][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 = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ignore_http_status_errors=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 = scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_scan_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - assert response.ignore_http_status_errors is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_update_scan_config") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_update_scan_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.UpdateScanConfigRequest.pb(web_security_scanner.UpdateScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) - req.return_value.content = return_value - - request = web_security_scanner.UpdateScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_config.ScanConfig() - - client.update_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_start_scan_run_rest_bad_request(request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - client.start_scan_run(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.StartScanRunRequest, - dict, -]) -def test_start_scan_run_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.start_scan_run(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_start_scan_run_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_start_scan_run") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_start_scan_run") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.StartScanRunRequest.pb(web_security_scanner.StartScanRunRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) - req.return_value.content = return_value - - request = web_security_scanner.StartScanRunRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_run.ScanRun() - - client.start_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_scan_run_rest_bad_request(request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.get_scan_run(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanRunRequest, - dict, -]) -def test_get_scan_run_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_scan_run(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_scan_run_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_run") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_run") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.GetScanRunRequest.pb(web_security_scanner.GetScanRunRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) - req.return_value.content = return_value - - request = web_security_scanner.GetScanRunRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_run.ScanRun() - - client.get_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_scan_runs_rest_bad_request(request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/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 - client.list_scan_runs(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanRunsRequest, - dict, -]) -def test_list_scan_runs_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse( - 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_scan_runs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_scan_runs_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_runs") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_runs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListScanRunsRequest.pb(web_security_scanner.ListScanRunsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListScanRunsResponse.to_json(web_security_scanner.ListScanRunsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListScanRunsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListScanRunsResponse() - - client.list_scan_runs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_stop_scan_run_rest_bad_request(request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.stop_scan_run(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.StopScanRunRequest, - dict, -]) -def test_stop_scan_run_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.stop_scan_run(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_stop_scan_run_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_stop_scan_run") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_stop_scan_run") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.StopScanRunRequest.pb(web_security_scanner.StopScanRunRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) - req.return_value.content = return_value - - request = web_security_scanner.StopScanRunRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_run.ScanRun() - - client.stop_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_crawled_urls_rest_bad_request(request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.list_crawled_urls(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListCrawledUrlsRequest, - dict, -]) -def test_list_crawled_urls_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListCrawledUrlsResponse( - 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_crawled_urls(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_crawled_urls_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_crawled_urls") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_crawled_urls") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListCrawledUrlsRequest.pb(web_security_scanner.ListCrawledUrlsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListCrawledUrlsResponse.to_json(web_security_scanner.ListCrawledUrlsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListCrawledUrlsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListCrawledUrlsResponse() - - client.list_crawled_urls(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_finding_rest_bad_request(request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_finding(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetFindingRequest, - dict, -]) -def test_get_finding_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = finding.Finding( - name='name_value', - finding_type='finding_type_value', - severity=finding.Finding.Severity.CRITICAL, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = finding.Finding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_finding_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_finding") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.GetFindingRequest.pb(web_security_scanner.GetFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = finding.Finding.to_json(finding.Finding()) - req.return_value.content = return_value - - request = web_security_scanner.GetFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.get_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.list_findings(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListFindingsRequest, - dict, -]) -def test_list_findings_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingsResponse( - 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 = web_security_scanner.ListFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListFindingsRequest.pb(web_security_scanner.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListFindingsResponse.to_json(web_security_scanner.ListFindingsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_finding_type_stats_rest_bad_request(request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.list_finding_type_stats(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListFindingTypeStatsRequest, - dict, -]) -def test_list_finding_type_stats_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingTypeStatsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_finding_type_stats(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_finding_type_stats_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_finding_type_stats") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_finding_type_stats") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListFindingTypeStatsRequest.pb(web_security_scanner.ListFindingTypeStatsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListFindingTypeStatsResponse.to_json(web_security_scanner.ListFindingTypeStatsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListFindingTypeStatsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListFindingTypeStatsResponse() - - client.list_finding_type_stats(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = WebSecurityScannerClient( - 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - client.create_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.CreateScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - client.delete_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.DeleteScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - client.get_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_configs_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - client.list_scan_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanConfigsRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - client.update_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.UpdateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_scan_run_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - client.start_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StartScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_run_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - client.get_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_runs_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - client.list_scan_runs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanRunsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_scan_run_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - client.stop_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StopScanRunRequest() - - assert args[0] == request_msg - - -# This 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_crawled_urls_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - client.list_crawled_urls(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListCrawledUrlsRequest() - - assert args[0] == request_msg - - -# This 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_finding_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - client.get_finding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetFindingRequest() - - assert args[0] == request_msg - - -# This 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_findings_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - client.list_findings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingsRequest() - - assert args[0] == request_msg - - -# This 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_finding_type_stats_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - client.list_finding_type_stats(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingTypeStatsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WebSecurityScannerGrpcTransport, - ) - -def test_web_security_scanner_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_web_security_scanner_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_scan_config', - 'delete_scan_config', - 'get_scan_config', - 'list_scan_configs', - 'update_scan_config', - 'start_scan_run', - 'get_scan_run', - 'list_scan_runs', - 'stop_scan_run', - 'list_crawled_urls', - 'get_finding', - 'list_findings', - 'list_finding_type_stats', - ) - 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_web_security_scanner_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - 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_web_security_scanner_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport() - adc.assert_called_once() - - -def test_web_security_scanner_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) - WebSecurityScannerClient() - 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.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - transports.WebSecurityScannerRestTransport, - ], -) -def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, grpc_helpers), - (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_web_security_scanner_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( - "websecurityscanner.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="websecurityscanner.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_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_web_security_scanner_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.WebSecurityScannerRestTransport ( - 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_web_security_scanner_host_no_port(transport_name): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'websecurityscanner.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://websecurityscanner.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_web_security_scanner_host_with_port(transport_name): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'websecurityscanner.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://websecurityscanner.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_web_security_scanner_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = WebSecurityScannerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = WebSecurityScannerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_scan_config._session - session2 = client2.transport.create_scan_config._session - assert session1 != session2 - session1 = client1.transport.delete_scan_config._session - session2 = client2.transport.delete_scan_config._session - assert session1 != session2 - session1 = client1.transport.get_scan_config._session - session2 = client2.transport.get_scan_config._session - assert session1 != session2 - session1 = client1.transport.list_scan_configs._session - session2 = client2.transport.list_scan_configs._session - assert session1 != session2 - session1 = client1.transport.update_scan_config._session - session2 = client2.transport.update_scan_config._session - assert session1 != session2 - session1 = client1.transport.start_scan_run._session - session2 = client2.transport.start_scan_run._session - assert session1 != session2 - session1 = client1.transport.get_scan_run._session - session2 = client2.transport.get_scan_run._session - assert session1 != session2 - session1 = client1.transport.list_scan_runs._session - session2 = client2.transport.list_scan_runs._session - assert session1 != session2 - session1 = client1.transport.stop_scan_run._session - session2 = client2.transport.stop_scan_run._session - assert session1 != session2 - session1 = client1.transport.list_crawled_urls._session - session2 = client2.transport.list_crawled_urls._session - assert session1 != session2 - session1 = client1.transport.get_finding._session - session2 = client2.transport.get_finding._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_finding_type_stats._session - session2 = client2.transport.list_finding_type_stats._session - assert session1 != session2 -def test_web_security_scanner_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcTransport( - 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_web_security_scanner_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - 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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_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_finding_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - finding = "octopus" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "project": "oyster", - "scan_config": "nudibranch", - "scan_run": "cuttlefish", - "finding": "mussel", - } - path = WebSecurityScannerClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_finding_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WebSecurityScannerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = WebSecurityScannerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = WebSecurityScannerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = WebSecurityScannerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WebSecurityScannerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = WebSecurityScannerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = WebSecurityScannerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = WebSecurityScannerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.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 = WebSecurityScannerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = WebSecurityScannerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.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.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - transport_class = WebSecurityScannerClient.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 = WebSecurityScannerClient( - 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 = WebSecurityScannerAsyncClient( - 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 = WebSecurityScannerClient( - 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 = WebSecurityScannerClient( - 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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport), -]) -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-cloud-websecurityscanner/v1alpha/.coveragerc b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.coveragerc deleted file mode 100644 index 085a92b30288..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/websecurityscanner/__init__.py - google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1alpha/.flake8 b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/.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-cloud-websecurityscanner/v1alpha/MANIFEST.in b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/MANIFEST.in deleted file mode 100644 index 984c53e3603b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/websecurityscanner *.py -recursive-include google/cloud/websecurityscanner_v1alpha *.py diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/README.rst deleted file mode 100644 index 4de4c103eee6..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Websecurityscanner 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 Cloud Websecurityscanner 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-cloud-websecurityscanner/v1alpha/docs/_static/custom.css b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/conf.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/conf.py deleted file mode 100644 index 40ff11b301ef..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner 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-cloud-websecurityscanner" -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 Cloud 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-cloud-websecurityscanner-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-cloud-websecurityscanner.tex", - u"google-cloud-websecurityscanner 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-cloud-websecurityscanner", - u"Google Cloud Websecurityscanner 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-cloud-websecurityscanner", - u"google-cloud-websecurityscanner Documentation", - author, - "google-cloud-websecurityscanner", - "GAPIC library for Google Cloud Websecurityscanner 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-cloud-websecurityscanner/v1alpha/docs/index.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/index.rst deleted file mode 100644 index f694969992f5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - websecurityscanner_v1alpha/services_ - websecurityscanner_v1alpha/types_ diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/services_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/services_.rst deleted file mode 100644 index a4ad4137e1d9..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Websecurityscanner v1alpha API -======================================================== -.. toctree:: - :maxdepth: 2 - - web_security_scanner diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/types_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/types_.rst deleted file mode 100644 index a465d17792b3..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Websecurityscanner v1alpha API -===================================================== - -.. automodule:: google.cloud.websecurityscanner_v1alpha.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst deleted file mode 100644 index 1bb56883bd40..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst +++ /dev/null @@ -1,10 +0,0 @@ -WebSecurityScanner ------------------------------------- - -.. automodule:: google.cloud.websecurityscanner_v1alpha.services.web_security_scanner - :members: - :inherited-members: - -.. automodule:: google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/__init__.py deleted file mode 100644 index 9782642f052f..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/__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.cloud.websecurityscanner import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.client import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient - -from google.cloud.websecurityscanner_v1alpha.types.crawled_url import CrawledUrl -from google.cloud.websecurityscanner_v1alpha.types.finding import Finding -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import OutdatedLibrary -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import ViolatingResource -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import VulnerableHeaders -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import VulnerableParameters -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import Xss -from google.cloud.websecurityscanner_v1alpha.types.finding_type_stats import FindingTypeStats -from google.cloud.websecurityscanner_v1alpha.types.scan_config import ScanConfig -from google.cloud.websecurityscanner_v1alpha.types.scan_run import ScanRun -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import CreateScanConfigRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import DeleteScanConfigRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetFindingRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetScanConfigRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetScanRunRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListCrawledUrlsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListCrawledUrlsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingTypeStatsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingTypeStatsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanConfigsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanConfigsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanRunsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanRunsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import StartScanRunRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import StopScanRunRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ('WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', - 'CrawledUrl', - 'Finding', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanRun', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/py.typed deleted file mode 100644 index 8cfb5d256398..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py deleted file mode 100644 index 69db5396a6ab..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/__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.cloud.websecurityscanner_v1alpha import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.web_security_scanner import WebSecurityScannerClient -from .services.web_security_scanner import WebSecurityScannerAsyncClient - -from .types.crawled_url import CrawledUrl -from .types.finding import Finding -from .types.finding_addon import OutdatedLibrary -from .types.finding_addon import ViolatingResource -from .types.finding_addon import VulnerableHeaders -from .types.finding_addon import VulnerableParameters -from .types.finding_addon import Xss -from .types.finding_type_stats import FindingTypeStats -from .types.scan_config import ScanConfig -from .types.scan_run import ScanRun -from .types.web_security_scanner import CreateScanConfigRequest -from .types.web_security_scanner import DeleteScanConfigRequest -from .types.web_security_scanner import GetFindingRequest -from .types.web_security_scanner import GetScanConfigRequest -from .types.web_security_scanner import GetScanRunRequest -from .types.web_security_scanner import ListCrawledUrlsRequest -from .types.web_security_scanner import ListCrawledUrlsResponse -from .types.web_security_scanner import ListFindingsRequest -from .types.web_security_scanner import ListFindingsResponse -from .types.web_security_scanner import ListFindingTypeStatsRequest -from .types.web_security_scanner import ListFindingTypeStatsResponse -from .types.web_security_scanner import ListScanConfigsRequest -from .types.web_security_scanner import ListScanConfigsResponse -from .types.web_security_scanner import ListScanRunsRequest -from .types.web_security_scanner import ListScanRunsResponse -from .types.web_security_scanner import StartScanRunRequest -from .types.web_security_scanner import StopScanRunRequest -from .types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ( - 'WebSecurityScannerAsyncClient', -'CrawledUrl', -'CreateScanConfigRequest', -'DeleteScanConfigRequest', -'Finding', -'FindingTypeStats', -'GetFindingRequest', -'GetScanConfigRequest', -'GetScanRunRequest', -'ListCrawledUrlsRequest', -'ListCrawledUrlsResponse', -'ListFindingTypeStatsRequest', -'ListFindingTypeStatsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListScanConfigsRequest', -'ListScanConfigsResponse', -'ListScanRunsRequest', -'ListScanRunsResponse', -'OutdatedLibrary', -'ScanConfig', -'ScanRun', -'StartScanRunRequest', -'StopScanRunRequest', -'UpdateScanConfigRequest', -'ViolatingResource', -'VulnerableHeaders', -'VulnerableParameters', -'WebSecurityScannerClient', -'Xss', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json deleted file mode 100644 index a7c87fd4f50f..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json +++ /dev/null @@ -1,223 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.websecurityscanner_v1alpha", - "protoPackage": "google.cloud.websecurityscanner.v1alpha", - "schema": "1.0", - "services": { - "WebSecurityScanner": { - "clients": { - "grpc": { - "libraryClient": "WebSecurityScannerClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WebSecurityScannerAsyncClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - }, - "rest": { - "libraryClient": "WebSecurityScannerClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed deleted file mode 100644 index 8cfb5d256398..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py deleted file mode 100644 index 3aeec5e07d95..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__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 WebSecurityScannerClient -from .async_client import WebSecurityScannerAsyncClient - -__all__ = ( - 'WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py deleted file mode 100644 index ee50e7769af3..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py +++ /dev/null @@ -1,1698 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.websecurityscanner_v1alpha 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.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import finding_addon -from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .client import WebSecurityScannerClient - - -class WebSecurityScannerAsyncClient: - """Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - """ - - _client: WebSecurityScannerClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = WebSecurityScannerClient._DEFAULT_UNIVERSE - - finding_path = staticmethod(WebSecurityScannerClient.finding_path) - parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) - scan_config_path = staticmethod(WebSecurityScannerClient.scan_config_path) - parse_scan_config_path = staticmethod(WebSecurityScannerClient.parse_scan_config_path) - scan_run_path = staticmethod(WebSecurityScannerClient.scan_run_path) - parse_scan_run_path = staticmethod(WebSecurityScannerClient.parse_scan_run_path) - common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) - parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) - common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) - parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) - common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) - parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) - common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) - parse_common_location_path = staticmethod(WebSecurityScannerClient.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: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, 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: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, 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 WebSecurityScannerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: 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 = WebSecurityScannerClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner 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,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): - 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 WebSecurityScannerTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WebSecurityScannerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_scan_config(self, - request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - scan_config: Optional[gcw_scan_config.ScanConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1alpha.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1alpha.CreateScanConfigRequest( - parent="parent_value", - scan_config=scan_config, - ) - - # Make the request - response = await client.create_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest, dict]]): - The request object. Request for the ``CreateScanConfig`` method. - parent (:class:`str`): - Required. The parent resource name - where the scan is created, which should - be a project resource name in the format - 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - scan_config (:class:`google.cloud.websecurityscanner_v1alpha.types.ScanConfig`): - Required. The ScanConfig to be - created. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_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. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, scan_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, web_security_scanner.CreateScanConfigRequest): - request = web_security_scanner.CreateScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if scan_config is not None: - request.scan_config = scan_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_scan_config] - - # Certain fields should be provided within 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_scan_config(self, - request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.DeleteScanConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_scan_config(request=request) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest, dict]]): - The request object. Request for the ``DeleteScanConfig`` method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be deleted. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.DeleteScanConfigRequest): - request = web_security_scanner.DeleteScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_config] - - # Certain fields should be provided within 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 get_scan_config(self, - request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetScanConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest, dict]]): - The request object. Request for the ``GetScanConfig`` method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be returned. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetScanConfigRequest): - request = web_security_scanner.GetScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_config] - - # Certain fields should be provided within 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_scan_configs(self, - request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsAsyncPager: - r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1alpha - - async def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListScanConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest, dict]]): - The request object. Request for the ``ListScanConfigs`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a project resource name - in the format 'projects/{projectId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: - Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): - request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] - - # Certain fields should be provided within 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.ListScanConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_scan_config(self, - request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, - *, - scan_config: Optional[gcw_scan_config.ScanConfig] = 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, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1alpha.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1alpha.UpdateScanConfigRequest( - scan_config=scan_config, - ) - - # Make the request - response = await client.update_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest, dict]]): - The request object. Request for the ``UpdateScanConfigRequest`` method. - scan_config (:class:`google.cloud.websecurityscanner_v1alpha.types.ScanConfig`): - Required. The ScanConfig to be - updated. The name field must be set to - identify the resource to be updated. The - values of fields not covered by the mask - will be ignored. - - This corresponds to the ``scan_config`` 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 update mask applies to the resource. For - the ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([scan_config, 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, web_security_scanner.UpdateScanConfigRequest): - request = web_security_scanner.UpdateScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scan_config is not None: - request.scan_config = scan_config - 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_scan_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.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 start_scan_run(self, - request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.StartScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.start_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest, dict]]): - The request object. Request for the ``StartScanRun`` method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be used. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.StartScanRunRequest): - request = web_security_scanner.StartScanRunRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.start_scan_run] - - # Certain fields should be provided within 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_scan_run(self, - request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.get_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest, dict]]): - The request object. Request for the ``GetScanRun`` method. - name (:class:`str`): - Required. The resource name of the - ScanRun to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetScanRunRequest): - request = web_security_scanner.GetScanRunRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_run] - - # Certain fields should be provided within 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_scan_runs(self, - request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsAsyncPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListScanRunsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest, dict]]): - The request object. Request for the ``ListScanRuns`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan resource name in - the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsAsyncPager: - Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): - request = web_security_scanner.ListScanRunsRequest(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_scan_runs] - - # Certain fields should be provided within 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.ListScanRunsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def stop_scan_run(self, - request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.StopScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.stop_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest, dict]]): - The request object. Request for the ``StopScanRun`` method. - name (:class:`str`): - Required. The resource name of the - ScanRun to be stopped. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.StopScanRunRequest): - request = web_security_scanner.StopScanRunRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.stop_scan_run] - - # Certain fields should be provided within 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_crawled_urls(self, - request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsAsyncPager: - r"""List CrawledUrls under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListCrawledUrlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest, dict]]): - The request object. Request for the ``ListCrawledUrls`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: - Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] - - # Certain fields should be provided within 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.ListCrawledUrlsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_finding(self, - request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_get_finding(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetFindingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest, dict]]): - The request object. Request for the ``GetFinding`` method. - name (:class:`str`): - Required. The resource name of the - Finding to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetFindingRequest): - request = web_security_scanner.GetFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_finding] - - # Certain fields should be provided within 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_findings(self, - request: Optional[Union[web_security_scanner.ListFindingsRequest, 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, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""List Findings under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_list_findings(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListFindingsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest, dict]]): - The request object. Request for the ``ListFindings`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Required. The filter expression. The expression must be - in the format: . Supported field: 'finding_type'. - Supported operator: '='. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsAsyncPager: - Response for the ListFindings 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, 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, web_security_scanner.ListFindingsRequest): - request = web_security_scanner.ListFindingsRequest(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_findings] - - # Certain fields should be provided within 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.ListFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_finding_type_stats(self, - request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - async def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListFindingTypeStatsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest, dict]]): - The request object. Request for the ``ListFindingTypeStats`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats method. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - 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, web_security_scanner.ListFindingTypeStatsRequest): - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] - - # Certain fields should be provided within 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) -> "WebSecurityScannerAsyncClient": - 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__ = ( - "WebSecurityScannerAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py deleted file mode 100644 index 7edee84eaf0a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py +++ /dev/null @@ -1,2060 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.websecurityscanner_v1alpha 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 - -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import finding_addon -from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WebSecurityScannerGrpcTransport -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .transports.rest import WebSecurityScannerRestTransport - - -class WebSecurityScannerClientMeta(type): - """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] - _transport_registry["grpc"] = WebSecurityScannerGrpcTransport - _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport - _transport_registry["rest"] = WebSecurityScannerRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[WebSecurityScannerTransport]: - """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 WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): - """Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - """ - - @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 = "websecurityscanner.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "websecurityscanner.{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: - WebSecurityScannerClient: 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: - WebSecurityScannerClient: 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) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def scan_config_path(project: str,scan_config: str,) -> str: - """Returns a fully-qualified scan_config string.""" - return "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) - - @staticmethod - def parse_scan_config_path(path: str) -> Dict[str,str]: - """Parses a scan_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def scan_run_path(project: str,scan_config: str,scan_run: str,) -> str: - """Returns a fully-qualified scan_run string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) - - @staticmethod - def parse_scan_run_path(path: str) -> Dict[str,str]: - """Parses a scan_run path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?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 = WebSecurityScannerClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = WebSecurityScannerClient._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 = WebSecurityScannerClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - WebSecurityScannerClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): - 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 WebSecurityScannerTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WebSecurityScannerClient._read_environment_variables() - self._client_cert_source = WebSecurityScannerClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = WebSecurityScannerClient._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 - - 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, WebSecurityScannerTransport) - if transport_provided: - # transport is a WebSecurityScannerTransport 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(WebSecurityScannerTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - WebSecurityScannerClient._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[WebSecurityScannerTransport], Callable[..., WebSecurityScannerTransport]] = ( - WebSecurityScannerClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., WebSecurityScannerTransport], 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, - ) - - def create_scan_config(self, - request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - scan_config: Optional[gcw_scan_config.ScanConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1alpha.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1alpha.CreateScanConfigRequest( - parent="parent_value", - scan_config=scan_config, - ) - - # Make the request - response = client.create_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest, dict]): - The request object. Request for the ``CreateScanConfig`` method. - parent (str): - Required. The parent resource name - where the scan is created, which should - be a project resource name in the format - 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): - Required. The ScanConfig to be - created. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, scan_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, web_security_scanner.CreateScanConfigRequest): - request = web_security_scanner.CreateScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if scan_config is not None: - request.scan_config = scan_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_scan_config] - - # Certain fields should be provided within 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_scan_config(self, - request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.DeleteScanConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_scan_config(request=request) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest, dict]): - The request object. Request for the ``DeleteScanConfig`` method. - name (str): - Required. The resource name of the - ScanConfig to be deleted. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.DeleteScanConfigRequest): - request = web_security_scanner.DeleteScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_config] - - # Certain fields should be provided within 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 get_scan_config(self, - request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetScanConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest, dict]): - The request object. Request for the ``GetScanConfig`` method. - name (str): - Required. The resource name of the - ScanConfig to be returned. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetScanConfigRequest): - request = web_security_scanner.GetScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_config] - - # Certain fields should be provided within 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_scan_configs(self, - request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsPager: - r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1alpha - - def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListScanConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest, dict]): - The request object. Request for the ``ListScanConfigs`` method. - parent (str): - Required. The parent resource name, - which should be a project resource name - in the format 'projects/{projectId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsPager: - Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): - request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] - - # Certain fields should be provided within 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.ListScanConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_scan_config(self, - request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, - *, - scan_config: Optional[gcw_scan_config.ScanConfig] = 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, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1alpha.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1alpha.UpdateScanConfigRequest( - scan_config=scan_config, - ) - - # Make the request - response = client.update_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest, dict]): - The request object. Request for the ``UpdateScanConfigRequest`` method. - scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): - Required. The ScanConfig to be - updated. The name field must be set to - identify the resource to be updated. The - values of fields not covered by the mask - will be ignored. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For - the ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([scan_config, 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, web_security_scanner.UpdateScanConfigRequest): - request = web_security_scanner.UpdateScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scan_config is not None: - request.scan_config = scan_config - 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_scan_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.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 start_scan_run(self, - request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.StartScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.start_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest, dict]): - The request object. Request for the ``StartScanRun`` method. - name (str): - Required. The resource name of the - ScanConfig to be used. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.StartScanRunRequest): - request = web_security_scanner.StartScanRunRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.start_scan_run] - - # Certain fields should be provided within 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_scan_run(self, - request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.get_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest, dict]): - The request object. Request for the ``GetScanRun`` method. - name (str): - Required. The resource name of the - ScanRun to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetScanRunRequest): - request = web_security_scanner.GetScanRunRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_run] - - # Certain fields should be provided within 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_scan_runs(self, - request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListScanRunsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest, dict]): - The request object. Request for the ``ListScanRuns`` method. - parent (str): - Required. The parent resource name, - which should be a scan resource name in - the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsPager: - Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): - request = web_security_scanner.ListScanRunsRequest(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_scan_runs] - - # Certain fields should be provided within 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.ListScanRunsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def stop_scan_run(self, - request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.StopScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.stop_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest, dict]): - The request object. Request for the ``StopScanRun`` method. - name (str): - Required. The resource name of the - ScanRun to be stopped. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.StopScanRunRequest): - request = web_security_scanner.StopScanRunRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.stop_scan_run] - - # Certain fields should be provided within 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_crawled_urls(self, - request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsPager: - r"""List CrawledUrls under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListCrawledUrlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest, dict]): - The request object. Request for the ``ListCrawledUrls`` method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsPager: - Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] - - # Certain fields should be provided within 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.ListCrawledUrlsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_finding(self, - request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_get_finding(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetFindingRequest( - name="name_value", - ) - - # Make the request - response = client.get_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest, dict]): - The request object. Request for the ``GetFinding`` method. - name (str): - Required. The resource name of the - Finding to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetFindingRequest): - request = web_security_scanner.GetFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_finding] - - # Certain fields should be provided within 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_findings(self, - request: Optional[Union[web_security_scanner.ListFindingsRequest, 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, str]] = (), - ) -> pagers.ListFindingsPager: - r"""List Findings under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_list_findings(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListFindingsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest, dict]): - The request object. Request for the ``ListFindings`` method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Required. The filter expression. The expression must be - in the format: . Supported field: 'finding_type'. - Supported operator: '='. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsPager: - Response for the ListFindings 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, 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, web_security_scanner.ListFindingsRequest): - request = web_security_scanner.ListFindingsRequest(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_findings] - - # Certain fields should be provided within 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.ListFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_finding_type_stats(self, - request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1alpha - - def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListFindingTypeStatsRequest( - parent="parent_value", - ) - - # Make the request - response = client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest, dict]): - The request object. Request for the ``ListFindingTypeStats`` method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats method. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - 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, web_security_scanner.ListFindingTypeStatsRequest): - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] - - # Certain fields should be provided within 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) -> "WebSecurityScannerClient": - 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__ = ( - "WebSecurityScannerClient", -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py deleted file mode 100644 index 055868c3ae3a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py +++ /dev/null @@ -1,571 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner - - -class ListScanConfigsPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListScanConfigsResponse], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - for page in self.pages: - yield from page.scan_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanConfigsAsyncPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` - attributes are available on the 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[web_security_scanner.ListScanConfigsResponse]], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListScanRunsResponse], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - for page in self.pages: - yield from page.scan_runs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsAsyncPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` - attributes are available on the 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[web_security_scanner.ListScanRunsResponse]], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_runs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListCrawledUrlsResponse], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - for page in self.pages: - yield from page.crawled_urls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsAsyncPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` - attributes are available on the 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[web_security_scanner.ListCrawledUrlsResponse]], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - async def async_generator(): - async for page in self.pages: - for response in page.crawled_urls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListFindingsResponse], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: - 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[finding.Finding]: - for page in self.pages: - yield from page.findings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` - attributes are available on the 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[web_security_scanner.ListFindingsResponse]], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: - 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[finding.Finding]: - async def async_generator(): - async for page in self.pages: - for response in page.findings: - 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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/README.rst deleted file mode 100644 index 3479ee767648..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`WebSecurityScannerTransport` is the ABC for all transports. -- public child `WebSecurityScannerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `WebSecurityScannerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseWebSecurityScannerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `WebSecurityScannerRestTransport` 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-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py deleted file mode 100644 index e24819a4ee07..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/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 WebSecurityScannerTransport -from .grpc import WebSecurityScannerGrpcTransport -from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .rest import WebSecurityScannerRestTransport -from .rest import WebSecurityScannerRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] -_transport_registry['grpc'] = WebSecurityScannerGrpcTransport -_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport -_transport_registry['rest'] = WebSecurityScannerRestTransport - -__all__ = ( - 'WebSecurityScannerTransport', - 'WebSecurityScannerGrpcTransport', - 'WebSecurityScannerGrpcAsyncIOTransport', - 'WebSecurityScannerRestTransport', - 'WebSecurityScannerRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py deleted file mode 100644 index 8adb5f158796..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1alpha 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.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class WebSecurityScannerTransport(abc.ABC): - """Abstract transport class for WebSecurityScanner.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_scan_config: gapic_v1.method.wrap_method( - self.create_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.delete_scan_config: gapic_v1.method.wrap_method( - self.delete_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_config: gapic_v1.method.wrap_method( - self.get_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_configs: gapic_v1.method.wrap_method( - self.list_scan_configs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_scan_config: gapic_v1.method.wrap_method( - self.update_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.start_scan_run: gapic_v1.method.wrap_method( - self.start_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_run: gapic_v1.method.wrap_method( - self.get_scan_run, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_runs: gapic_v1.method.wrap_method( - self.list_scan_runs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.stop_scan_run: gapic_v1.method.wrap_method( - self.stop_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.list_crawled_urls: gapic_v1.method.wrap_method( - self.list_crawled_urls, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_finding: gapic_v1.method.wrap_method( - self.get_finding, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_finding_type_stats: gapic_v1.method.wrap_method( - self.list_finding_type_stats, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Union[ - gcw_scan_config.ScanConfig, - Awaitable[gcw_scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Union[ - web_security_scanner.ListScanConfigsResponse, - Awaitable[web_security_scanner.ListScanConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Union[ - gcw_scan_config.ScanConfig, - Awaitable[gcw_scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Union[ - web_security_scanner.ListScanRunsResponse, - Awaitable[web_security_scanner.ListScanRunsResponse] - ]]: - raise NotImplementedError() - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Union[ - web_security_scanner.ListCrawledUrlsResponse, - Awaitable[web_security_scanner.ListCrawledUrlsResponse] - ]]: - raise NotImplementedError() - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Union[ - web_security_scanner.ListFindingsResponse, - Awaitable[web_security_scanner.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Union[ - web_security_scanner.ListFindingTypeStatsResponse, - Awaitable[web_security_scanner.ListFindingTypeStatsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'WebSecurityScannerTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py deleted file mode 100644 index de43b70f1f09..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO - - -class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): - """gRPC backend transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'websecurityscanner.googleapis.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_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - gcw_scan_config.ScanConfig]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - ~.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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - web_security_scanner.ListScanConfigsResponse]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - ~.ListScanConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - gcw_scan_config.ScanConfig]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - web_security_scanner.ListScanRunsResponse]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - ~.ListScanRunsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - web_security_scanner.ListCrawledUrlsResponse]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - ~.ListCrawledUrlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - finding.Finding]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - web_security_scanner.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - Returns: - Callable[[~.ListFindingsRequest], - ~.ListFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - web_security_scanner.ListFindingTypeStatsResponse]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - ~.ListFindingTypeStatsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'WebSecurityScannerGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py deleted file mode 100644 index 6381e2b7bbf4..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py +++ /dev/null @@ -1,764 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .grpc import WebSecurityScannerGrpcTransport - - -class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): - """gRPC AsyncIO backend transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'websecurityscanner.googleapis.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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Awaitable[gcw_scan_config.ScanConfig]]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - 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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Awaitable[web_security_scanner.ListScanConfigsResponse]]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - Awaitable[~.ListScanConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Awaitable[gcw_scan_config.ScanConfig]]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Awaitable[web_security_scanner.ListScanRunsResponse]]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - Awaitable[~.ListScanRunsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - Awaitable[~.ListCrawledUrlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Awaitable[web_security_scanner.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - Returns: - Callable[[~.ListFindingsRequest], - Awaitable[~.ListFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - Awaitable[~.ListFindingTypeStatsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - 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_scan_config: self._wrap_method( - self.create_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.delete_scan_config: self._wrap_method( - self.delete_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_config: self._wrap_method( - self.get_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_configs: self._wrap_method( - self.list_scan_configs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_scan_config: self._wrap_method( - self.update_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.start_scan_run: self._wrap_method( - self.start_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_run: self._wrap_method( - self.get_scan_run, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_runs: self._wrap_method( - self.list_scan_runs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.stop_scan_run: self._wrap_method( - self.stop_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.list_crawled_urls: self._wrap_method( - self.list_crawled_urls, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_finding: self._wrap_method( - self.get_finding, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_findings: self._wrap_method( - self.list_findings, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_finding_type_stats: self._wrap_method( - self.list_finding_type_stats, - 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=600.0, - ), - default_timeout=600.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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'WebSecurityScannerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py deleted file mode 100644 index 0e6858594151..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py +++ /dev/null @@ -1,1533 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - - -from .rest_base import _BaseWebSecurityScannerRestTransport -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 - - -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 WebSecurityScannerRestInterceptor: - """Interceptor for WebSecurityScanner. - - 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 WebSecurityScannerRestTransport. - - .. code-block:: python - class MyCustomWebSecurityScannerInterceptor(WebSecurityScannerRestInterceptor): - def pre_create_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_scan_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_scan_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_scan_run(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_scan_run(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_crawled_urls(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_crawled_urls(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_finding_type_stats(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_finding_type_stats(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_scan_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_scan_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_scan_runs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_scan_runs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_start_scan_run(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_start_scan_run(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stop_scan_run(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stop_scan_run(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_scan_config(self, response): - logging.log(f"Received response: {response}") - return response - - transport = WebSecurityScannerRestTransport(interceptor=MyCustomWebSecurityScannerInterceptor()) - client = WebSecurityScannerClient(transport=transport) - - - """ - def pre_create_scan_config(self, request: web_security_scanner.CreateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.CreateScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_create_scan_config(self, response: gcw_scan_config.ScanConfig) -> gcw_scan_config.ScanConfig: - """Post-rpc interceptor for create_scan_config - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_delete_scan_config(self, request: web_security_scanner.DeleteScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.DeleteScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def pre_get_finding(self, request: web_security_scanner.GetFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_get_finding(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for get_finding - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_get_scan_config(self, request: web_security_scanner.GetScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_get_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: - """Post-rpc interceptor for get_scan_config - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_get_scan_run(self, request: web_security_scanner.GetScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanRunRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_scan_run - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_get_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: - """Post-rpc interceptor for get_scan_run - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_crawled_urls(self, request: web_security_scanner.ListCrawledUrlsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListCrawledUrlsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_crawled_urls - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_crawled_urls(self, response: web_security_scanner.ListCrawledUrlsResponse) -> web_security_scanner.ListCrawledUrlsResponse: - """Post-rpc interceptor for list_crawled_urls - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_findings(self, request: web_security_scanner.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_findings(self, response: web_security_scanner.ListFindingsResponse) -> web_security_scanner.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_finding_type_stats(self, request: web_security_scanner.ListFindingTypeStatsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingTypeStatsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_finding_type_stats - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_finding_type_stats(self, response: web_security_scanner.ListFindingTypeStatsResponse) -> web_security_scanner.ListFindingTypeStatsResponse: - """Post-rpc interceptor for list_finding_type_stats - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_scan_configs(self, request: web_security_scanner.ListScanConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_scan_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_scan_configs(self, response: web_security_scanner.ListScanConfigsResponse) -> web_security_scanner.ListScanConfigsResponse: - """Post-rpc interceptor for list_scan_configs - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_scan_runs(self, request: web_security_scanner.ListScanRunsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanRunsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_scan_runs - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_scan_runs(self, response: web_security_scanner.ListScanRunsResponse) -> web_security_scanner.ListScanRunsResponse: - """Post-rpc interceptor for list_scan_runs - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_start_scan_run(self, request: web_security_scanner.StartScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StartScanRunRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for start_scan_run - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_start_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: - """Post-rpc interceptor for start_scan_run - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_stop_scan_run(self, request: web_security_scanner.StopScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StopScanRunRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for stop_scan_run - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_stop_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: - """Post-rpc interceptor for stop_scan_run - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_update_scan_config(self, request: web_security_scanner.UpdateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.UpdateScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_update_scan_config(self, response: gcw_scan_config.ScanConfig) -> gcw_scan_config.ScanConfig: - """Post-rpc interceptor for update_scan_config - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class WebSecurityScannerRestStub: - _session: AuthorizedSession - _host: str - _interceptor: WebSecurityScannerRestInterceptor - - -class WebSecurityScannerRestTransport(_BaseWebSecurityScannerRestTransport): - """REST backend synchronous transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'websecurityscanner.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[WebSecurityScannerRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 WebSecurityScannerRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateScanConfig(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.CreateScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.CreateScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcw_scan_config.ScanConfig: - r"""Call the create scan config method over HTTP. - - Args: - request (~.web_security_scanner.CreateScanConfigRequest): - The request object. Request for the ``CreateScanConfig`` method. - retry (google.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. - - Returns: - ~.gcw_scan_config.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_http_options() - request, metadata = self._interceptor.pre_create_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._CreateScanConfig._get_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 = gcw_scan_config.ScanConfig() - pb_resp = gcw_scan_config.ScanConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_scan_config(resp) - return resp - - class _DeleteScanConfig(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.DeleteScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.DeleteScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete scan config method over HTTP. - - Args: - request (~.web_security_scanner.DeleteScanConfigRequest): - The request object. Request for the ``DeleteScanConfig`` method. - retry (google.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. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_http_options() - request, metadata = self._interceptor.pre_delete_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._DeleteScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 _GetFinding(_BaseWebSecurityScannerRestTransport._BaseGetFinding, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.GetFinding") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.GetFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the get finding method over HTTP. - - Args: - request (~.web_security_scanner.GetFindingRequest): - The request object. Request for the ``GetFinding`` method. - retry (google.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. - - Returns: - ~.finding.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_http_options() - request, metadata = self._interceptor.pre_get_finding(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._GetFinding._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = finding.Finding() - pb_resp = finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_finding(resp) - return resp - - class _GetScanConfig(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.GetScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.GetScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_config.ScanConfig: - r"""Call the get scan config method over HTTP. - - Args: - request (~.web_security_scanner.GetScanConfigRequest): - The request object. Request for the ``GetScanConfig`` method. - retry (google.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. - - Returns: - ~.scan_config.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_http_options() - request, metadata = self._interceptor.pre_get_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._GetScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = scan_config.ScanConfig() - pb_resp = scan_config.ScanConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_scan_config(resp) - return resp - - class _GetScanRun(_BaseWebSecurityScannerRestTransport._BaseGetScanRun, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.GetScanRun") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.GetScanRunRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_run.ScanRun: - r"""Call the get scan run method over HTTP. - - Args: - request (~.web_security_scanner.GetScanRunRequest): - The request object. Request for the ``GetScanRun`` method. - retry (google.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. - - Returns: - ~.scan_run.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_http_options() - request, metadata = self._interceptor.pre_get_scan_run(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._GetScanRun._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = scan_run.ScanRun() - pb_resp = scan_run.ScanRun.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_scan_run(resp) - return resp - - class _ListCrawledUrls(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListCrawledUrls") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListCrawledUrlsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListCrawledUrlsResponse: - r"""Call the list crawled urls method over HTTP. - - Args: - request (~.web_security_scanner.ListCrawledUrlsRequest): - The request object. Request for the ``ListCrawledUrls`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListCrawledUrlsResponse: - Response for the ``ListCrawledUrls`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_http_options() - request, metadata = self._interceptor.pre_list_crawled_urls(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListCrawledUrls._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListCrawledUrlsResponse() - pb_resp = web_security_scanner.ListCrawledUrlsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_crawled_urls(resp) - return resp - - class _ListFindings(_BaseWebSecurityScannerRestTransport._BaseListFindings, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListFindings") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.web_security_scanner.ListFindingsRequest): - The request object. Request for the ``ListFindings`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListFindingsResponse: - Response for the ``ListFindings`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_http_options() - request, metadata = self._interceptor.pre_list_findings(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListFindings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListFindingsResponse() - pb_resp = web_security_scanner.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListFindingTypeStats(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListFindingTypeStats") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListFindingTypeStatsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""Call the list finding type stats method over HTTP. - - Args: - request (~.web_security_scanner.ListFindingTypeStatsRequest): - The request object. Request for the ``ListFindingTypeStats`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListFindingTypeStatsResponse: - Response for the ``ListFindingTypeStats`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_http_options() - request, metadata = self._interceptor.pre_list_finding_type_stats(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListFindingTypeStats._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListFindingTypeStatsResponse() - pb_resp = web_security_scanner.ListFindingTypeStatsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_finding_type_stats(resp) - return resp - - class _ListScanConfigs(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListScanConfigs") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListScanConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListScanConfigsResponse: - r"""Call the list scan configs method over HTTP. - - Args: - request (~.web_security_scanner.ListScanConfigsRequest): - The request object. Request for the ``ListScanConfigs`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListScanConfigsResponse: - Response for the ``ListScanConfigs`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_http_options() - request, metadata = self._interceptor.pre_list_scan_configs(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListScanConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListScanConfigsResponse() - pb_resp = web_security_scanner.ListScanConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_scan_configs(resp) - return resp - - class _ListScanRuns(_BaseWebSecurityScannerRestTransport._BaseListScanRuns, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListScanRuns") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListScanRunsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListScanRunsResponse: - r"""Call the list scan runs method over HTTP. - - Args: - request (~.web_security_scanner.ListScanRunsRequest): - The request object. Request for the ``ListScanRuns`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListScanRunsResponse: - Response for the ``ListScanRuns`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_http_options() - request, metadata = self._interceptor.pre_list_scan_runs(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListScanRuns._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListScanRunsResponse() - pb_resp = web_security_scanner.ListScanRunsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_scan_runs(resp) - return resp - - class _StartScanRun(_BaseWebSecurityScannerRestTransport._BaseStartScanRun, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.StartScanRun") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.StartScanRunRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_run.ScanRun: - r"""Call the start scan run method over HTTP. - - Args: - request (~.web_security_scanner.StartScanRunRequest): - The request object. Request for the ``StartScanRun`` method. - retry (google.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. - - Returns: - ~.scan_run.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_http_options() - request, metadata = self._interceptor.pre_start_scan_run(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._StartScanRun._get_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 = scan_run.ScanRun() - pb_resp = scan_run.ScanRun.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_start_scan_run(resp) - return resp - - class _StopScanRun(_BaseWebSecurityScannerRestTransport._BaseStopScanRun, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.StopScanRun") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.StopScanRunRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_run.ScanRun: - r"""Call the stop scan run method over HTTP. - - Args: - request (~.web_security_scanner.StopScanRunRequest): - The request object. Request for the ``StopScanRun`` method. - retry (google.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. - - Returns: - ~.scan_run.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_http_options() - request, metadata = self._interceptor.pre_stop_scan_run(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._StopScanRun._get_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 = scan_run.ScanRun() - pb_resp = scan_run.ScanRun.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_stop_scan_run(resp) - return resp - - class _UpdateScanConfig(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.UpdateScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.UpdateScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcw_scan_config.ScanConfig: - r"""Call the update scan config method over HTTP. - - Args: - request (~.web_security_scanner.UpdateScanConfigRequest): - The request object. Request for the ``UpdateScanConfigRequest`` method. - retry (google.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. - - Returns: - ~.gcw_scan_config.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_http_options() - request, metadata = self._interceptor.pre_update_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._UpdateScanConfig._get_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 = gcw_scan_config.ScanConfig() - pb_resp = gcw_scan_config.ScanConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_scan_config(resp) - return resp - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - gcw_scan_config.ScanConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - 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._DeleteScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - finding.Finding]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - scan_config.ScanConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - scan_run.ScanRun]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetScanRun(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - web_security_scanner.ListCrawledUrlsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListCrawledUrls(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - web_security_scanner.ListFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - web_security_scanner.ListFindingTypeStatsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListFindingTypeStats(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - web_security_scanner.ListScanConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListScanConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - web_security_scanner.ListScanRunsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListScanRuns(self._session, self._host, self._interceptor) # type: ignore - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - scan_run.ScanRun]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StartScanRun(self._session, self._host, self._interceptor) # type: ignore - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - scan_run.ScanRun]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StopScanRun(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - gcw_scan_config.ScanConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'WebSecurityScannerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest_base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest_base.py deleted file mode 100644 index 43a473271d0c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest_base.py +++ /dev/null @@ -1,617 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 WebSecurityScannerTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - - -class _BaseWebSecurityScannerRestTransport(WebSecurityScannerTransport): - """Base REST backend transport for WebSecurityScanner. - - 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 = 'websecurityscanner.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: 'websecurityscanner.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 _BaseCreateScanConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1alpha/{parent=projects/*}/scanConfigs', - 'body': 'scan_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.CreateScanConfigRequest.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(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteScanConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1alpha/{name=projects/*/scanConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.DeleteScanConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetFinding: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.GetFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetFinding._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetScanConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/scanConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.GetScanConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetScanRun: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.GetScanRunRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListCrawledUrls: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListCrawledUrlsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListFindings: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "filter" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListFindings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListFindingTypeStats: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListFindingTypeStatsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListScanConfigs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*}/scanConfigs', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListScanConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListScanRuns: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/scanConfigs/*}/scanRuns', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListScanRunsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStartScanRun: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1alpha/{name=projects/*/scanConfigs/*}:start', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.StartScanRunRequest.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(_BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStopScanRun: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}:stop', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.StopScanRunRequest.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(_BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateScanConfig: - 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': '/v1alpha/{scan_config.name=projects/*/scanConfigs/*}', - 'body': 'scan_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.UpdateScanConfigRequest.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(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseWebSecurityScannerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py deleted file mode 100644 index e83bf17f079c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py +++ /dev/null @@ -1,88 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .crawled_url import ( - CrawledUrl, -) -from .finding import ( - Finding, -) -from .finding_addon import ( - OutdatedLibrary, - ViolatingResource, - VulnerableHeaders, - VulnerableParameters, - Xss, -) -from .finding_type_stats import ( - FindingTypeStats, -) -from .scan_config import ( - ScanConfig, -) -from .scan_run import ( - ScanRun, -) -from .web_security_scanner import ( - CreateScanConfigRequest, - DeleteScanConfigRequest, - GetFindingRequest, - GetScanConfigRequest, - GetScanRunRequest, - ListCrawledUrlsRequest, - ListCrawledUrlsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListFindingTypeStatsRequest, - ListFindingTypeStatsResponse, - ListScanConfigsRequest, - ListScanConfigsResponse, - ListScanRunsRequest, - ListScanRunsResponse, - StartScanRunRequest, - StopScanRunRequest, - UpdateScanConfigRequest, -) - -__all__ = ( - 'CrawledUrl', - 'Finding', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanRun', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py deleted file mode 100644 index 747e60e69d12..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.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.cloud.websecurityscanner.v1alpha', - manifest={ - 'CrawledUrl', - }, -) - - -class CrawledUrl(proto.Message): - r"""A CrawledUrl resource represents a URL that was crawled - during a ScanRun. Web Security Scanner Service crawls the web - applications, following all links within the scope of sites, to - find the URLs to test against. - - Attributes: - http_method (str): - Output only. The http method of the request - that was used to visit the URL, in uppercase. - url (str): - Output only. The URL that was crawled. - body (str): - Output only. The body of the request that was - used to visit the URL. - """ - - http_method: str = proto.Field( - proto.STRING, - number=1, - ) - url: str = proto.Field( - proto.STRING, - number=2, - ) - body: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py deleted file mode 100644 index dad7099ea2cb..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner_v1alpha.types import finding_addon - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""A Finding resource represents a vulnerability instance - identified during a ScanRun. - - Attributes: - name (str): - The resource name of the Finding. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. - The finding IDs are generated by the system. - finding_type (google.cloud.websecurityscanner_v1alpha.types.Finding.FindingType): - The type of the Finding. - http_method (str): - The http method of the request that triggered - the vulnerability, in uppercase. - fuzzed_url (str): - The URL produced by the server-side fuzzer - and used in the request that triggered the - vulnerability. - body (str): - The body of the request that triggered the - vulnerability. - description (str): - The description of the vulnerability. - reproduction_url (str): - The URL containing human-readable payload - that user can leverage to reproduce the - vulnerability. - frame_url (str): - If the vulnerability was originated from - nested IFrame, the immediate parent IFrame is - reported. - final_url (str): - The URL where the browser lands when the - vulnerability is detected. - tracking_id (str): - The tracking ID uniquely identifies a - vulnerability instance across multiple ScanRuns. - outdated_library (google.cloud.websecurityscanner_v1alpha.types.OutdatedLibrary): - An addon containing information about - outdated libraries. - violating_resource (google.cloud.websecurityscanner_v1alpha.types.ViolatingResource): - An addon containing detailed information - regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, - etc. - vulnerable_headers (google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders): - An addon containing information about - vulnerable or missing HTTP headers. - vulnerable_parameters (google.cloud.websecurityscanner_v1alpha.types.VulnerableParameters): - An addon containing information about request - parameters which were found to be vulnerable. - xss (google.cloud.websecurityscanner_v1alpha.types.Xss): - An addon containing information reported for - an XSS, if any. - """ - class FindingType(proto.Enum): - r"""Types of Findings. - - Values: - FINDING_TYPE_UNSPECIFIED (0): - The invalid finding type. - MIXED_CONTENT (1): - A page that was served over HTTPS also - resources over HTTP. A man-in-the-middle - attacker could tamper with the HTTP resource and - gain full access to the website that loads the - resource or to monitor the actions taken by the - user. - OUTDATED_LIBRARY (2): - The version of an included library is known - to contain a security issue. The scanner checks - the version of library in use against a known - list of vulnerable libraries. False positives - are possible if the version detection fails or - if the library has been manually patched. - ROSETTA_FLASH (5): - This type of vulnerability occurs when the - value of a request parameter is reflected at the - beginning of the response, for example, in - requests using JSONP. Under certain - circumstances, an attacker may be able to supply - an alphanumeric-only Flash file in the - vulnerable parameter causing the browser to - execute the Flash file as if it originated on - the vulnerable server. - XSS_CALLBACK (3): - A cross-site scripting (XSS) bug is found via - JavaScript callback. For detailed explanations - on XSS, see - https://www.google.com/about/appsecurity/learning/xss/. - XSS_ERROR (4): - A potential cross-site scripting (XSS) bug - due to JavaScript breakage. In some - circumstances, the application under test might - modify the test string before it is parsed by - the browser. When the browser attempts to runs - this modified test string, it will likely break - and throw a JavaScript execution error, thus an - injection issue is occurring. However, it may - not be exploitable. Manual verification is - needed to see if the test string modifications - can be evaded and confirm that the issue is in - fact an XSS vulnerability. For detailed - explanations on XSS, see - https://www.google.com/about/appsecurity/learning/xss/. - CLEAR_TEXT_PASSWORD (6): - An application appears to be transmitting a - password field in clear text. An attacker can - eavesdrop network traffic and sniff the password - field. - INVALID_CONTENT_TYPE (7): - An application returns sensitive content with - an invalid content type, or without an - 'X-Content-Type-Options: nosniff' header. - XSS_ANGULAR_CALLBACK (8): - A cross-site scripting (XSS) vulnerability in - AngularJS module that occurs when a - user-provided string is interpolated by Angular. - INVALID_HEADER (9): - A malformed or invalid valued header. - MISSPELLED_SECURITY_HEADER_NAME (10): - Misspelled security header name. - MISMATCHING_SECURITY_HEADER_VALUES (11): - Mismatching values in a duplicate security - header. - """ - FINDING_TYPE_UNSPECIFIED = 0 - MIXED_CONTENT = 1 - OUTDATED_LIBRARY = 2 - ROSETTA_FLASH = 5 - XSS_CALLBACK = 3 - XSS_ERROR = 4 - CLEAR_TEXT_PASSWORD = 6 - INVALID_CONTENT_TYPE = 7 - XSS_ANGULAR_CALLBACK = 8 - INVALID_HEADER = 9 - MISSPELLED_SECURITY_HEADER_NAME = 10 - MISMATCHING_SECURITY_HEADER_VALUES = 11 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - finding_type: FindingType = proto.Field( - proto.ENUM, - number=2, - enum=FindingType, - ) - http_method: str = proto.Field( - proto.STRING, - number=3, - ) - fuzzed_url: str = proto.Field( - proto.STRING, - number=4, - ) - body: str = proto.Field( - proto.STRING, - number=5, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - reproduction_url: str = proto.Field( - proto.STRING, - number=7, - ) - frame_url: str = proto.Field( - proto.STRING, - number=8, - ) - final_url: str = proto.Field( - proto.STRING, - number=9, - ) - tracking_id: str = proto.Field( - proto.STRING, - number=10, - ) - outdated_library: finding_addon.OutdatedLibrary = proto.Field( - proto.MESSAGE, - number=11, - message=finding_addon.OutdatedLibrary, - ) - violating_resource: finding_addon.ViolatingResource = proto.Field( - proto.MESSAGE, - number=12, - message=finding_addon.ViolatingResource, - ) - vulnerable_headers: finding_addon.VulnerableHeaders = proto.Field( - proto.MESSAGE, - number=15, - message=finding_addon.VulnerableHeaders, - ) - vulnerable_parameters: finding_addon.VulnerableParameters = proto.Field( - proto.MESSAGE, - number=13, - message=finding_addon.VulnerableParameters, - ) - xss: finding_addon.Xss = proto.Field( - proto.MESSAGE, - number=14, - message=finding_addon.Xss, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py deleted file mode 100644 index ed500844531b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py +++ /dev/null @@ -1,160 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner.v1alpha', - manifest={ - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableParameters', - 'VulnerableHeaders', - 'Xss', - }, -) - - -class OutdatedLibrary(proto.Message): - r"""Information reported for an outdated library. - - Attributes: - library_name (str): - The name of the outdated library. - version (str): - The version number. - learn_more_urls (MutableSequence[str]): - URLs to learn more information about the - vulnerabilities in the library. - """ - - library_name: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - learn_more_urls: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ViolatingResource(proto.Message): - r"""Information regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, etc. - - Attributes: - content_type (str): - The MIME type of this resource. - resource_url (str): - URL of this violating resource. - """ - - content_type: str = proto.Field( - proto.STRING, - number=1, - ) - resource_url: str = proto.Field( - proto.STRING, - number=2, - ) - - -class VulnerableParameters(proto.Message): - r"""Information about vulnerable request parameters. - - Attributes: - parameter_names (MutableSequence[str]): - The vulnerable parameter names. - """ - - parameter_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class VulnerableHeaders(proto.Message): - r"""Information about vulnerable or missing HTTP Headers. - - Attributes: - headers (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders.Header]): - List of vulnerable headers. - missing_headers (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders.Header]): - List of missing headers. - """ - - class Header(proto.Message): - r"""Describes a HTTP Header. - - Attributes: - name (str): - Header name. - value (str): - Header value. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - - headers: MutableSequence[Header] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Header, - ) - missing_headers: MutableSequence[Header] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Header, - ) - - -class Xss(proto.Message): - r"""Information reported for an XSS. - - Attributes: - stack_traces (MutableSequence[str]): - Stack traces leading to the point where the - XSS occurred. - error_message (str): - An error message generated by a javascript - breakage. - """ - - stack_traces: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - error_message: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py deleted file mode 100644 index 99f4c21be8ba..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.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 - -from google.cloud.websecurityscanner_v1alpha.types import finding - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'FindingTypeStats', - }, -) - - -class FindingTypeStats(proto.Message): - r"""A FindingTypeStats resource represents stats regarding a - specific FindingType of Findings under a given ScanRun. - - Attributes: - finding_type (google.cloud.websecurityscanner_v1alpha.types.Finding.FindingType): - The finding type associated with the stats. - finding_count (int): - The count of findings belonging to this - finding type. - """ - - finding_type: finding.Finding.FindingType = proto.Field( - proto.ENUM, - number=1, - enum=finding.Finding.FindingType, - ) - finding_count: int = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py deleted file mode 100644 index 57b9b8dfc9aa..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py +++ /dev/null @@ -1,268 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner_v1alpha.types import scan_run -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'ScanConfig', - }, -) - - -class ScanConfig(proto.Message): - r"""A ScanConfig resource contains the configurations to launch a - scan. next id: 12 - - Attributes: - name (str): - The resource name of the ScanConfig. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - The ScanConfig IDs are generated by the system. - display_name (str): - Required. The user provided display name of - the ScanConfig. - max_qps (int): - The maximum QPS during scanning. A valid value ranges from 5 - to 20 inclusively. If the field is unspecified or its value - is set 0, server will default to 15. Other values outside of - [5, 20] range will be rejected with INVALID_ARGUMENT error. - starting_urls (MutableSequence[str]): - Required. The starting URLs from which the - scanner finds site pages. - authentication (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication): - The authentication configuration. If - specified, service will use the authentication - configuration during scanning. - user_agent (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.UserAgent): - The user agent used during scanning. - blacklist_patterns (MutableSequence[str]): - The blacklist URL patterns as described in - https://cloud.google.com/security-scanner/docs/excluded-urls - schedule (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Schedule): - The schedule of the ScanConfig. - target_platforms (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.ScanConfig.TargetPlatform]): - Set of Cloud Platforms targeted by the scan. If empty, - APP_ENGINE will be used as a default. - latest_run (google.cloud.websecurityscanner_v1alpha.types.ScanRun): - Latest ScanRun if available. - """ - class UserAgent(proto.Enum): - r"""Type of user agents used for scanning. - - Values: - USER_AGENT_UNSPECIFIED (0): - The user agent is unknown. Service will default to - CHROME_LINUX. - CHROME_LINUX (1): - Chrome on Linux. This is the service default - if unspecified. - CHROME_ANDROID (2): - Chrome on Android. - SAFARI_IPHONE (3): - Safari on IPhone. - """ - USER_AGENT_UNSPECIFIED = 0 - CHROME_LINUX = 1 - CHROME_ANDROID = 2 - SAFARI_IPHONE = 3 - - class TargetPlatform(proto.Enum): - r"""Cloud platforms supported by Cloud Web Security Scanner. - - Values: - TARGET_PLATFORM_UNSPECIFIED (0): - The target platform is unknown. Requests with this enum - value will be rejected with INVALID_ARGUMENT error. - APP_ENGINE (1): - Google App Engine service. - COMPUTE (2): - Google Compute Engine service. - """ - TARGET_PLATFORM_UNSPECIFIED = 0 - APP_ENGINE = 1 - COMPUTE = 2 - - class Authentication(proto.Message): - r"""Scan authentication configuration. - - 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_account (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication.GoogleAccount): - Authentication using a Google account. - - This field is a member of `oneof`_ ``authentication``. - custom_account (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication.CustomAccount): - Authentication using a custom account. - - This field is a member of `oneof`_ ``authentication``. - """ - - class GoogleAccount(proto.Message): - r"""Describes authentication configuration that uses a Google - account. - - Attributes: - username (str): - Required. The user name of the Google - account. - password (str): - Required. Input only. The password of the - Google account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - password: str = proto.Field( - proto.STRING, - number=2, - ) - - class CustomAccount(proto.Message): - r"""Describes authentication configuration that uses a custom - account. - - Attributes: - username (str): - Required. The user name of the custom - account. - password (str): - Required. Input only. The password of the - custom account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - login_url (str): - Required. The login form URL of the website. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - password: str = proto.Field( - proto.STRING, - number=2, - ) - login_url: str = proto.Field( - proto.STRING, - number=3, - ) - - google_account: 'ScanConfig.Authentication.GoogleAccount' = proto.Field( - proto.MESSAGE, - number=1, - oneof='authentication', - message='ScanConfig.Authentication.GoogleAccount', - ) - custom_account: 'ScanConfig.Authentication.CustomAccount' = proto.Field( - proto.MESSAGE, - number=2, - oneof='authentication', - message='ScanConfig.Authentication.CustomAccount', - ) - - class Schedule(proto.Message): - r"""Scan schedule configuration. - - Attributes: - schedule_time (google.protobuf.timestamp_pb2.Timestamp): - A timestamp indicates when the next run will - be scheduled. The value is refreshed by the - server after each run. If unspecified, it will - default to current server time, which means the - scan will be scheduled to start immediately. - interval_duration_days (int): - Required. The duration of time between - executions in days. - """ - - schedule_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - interval_duration_days: int = proto.Field( - proto.INT32, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - max_qps: int = proto.Field( - proto.INT32, - number=3, - ) - starting_urls: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - authentication: Authentication = proto.Field( - proto.MESSAGE, - number=5, - message=Authentication, - ) - user_agent: UserAgent = proto.Field( - proto.ENUM, - number=6, - enum=UserAgent, - ) - blacklist_patterns: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - schedule: Schedule = proto.Field( - proto.MESSAGE, - number=8, - message=Schedule, - ) - target_platforms: MutableSequence[TargetPlatform] = proto.RepeatedField( - proto.ENUM, - number=9, - enum=TargetPlatform, - ) - latest_run: scan_run.ScanRun = proto.Field( - proto.MESSAGE, - number=11, - message=scan_run.ScanRun, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py deleted file mode 100644 index 838665badb35..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py +++ /dev/null @@ -1,159 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner.v1alpha', - manifest={ - 'ScanRun', - }, -) - - -class ScanRun(proto.Message): - r"""A ScanRun is a output-only resource representing an actual - run of the scan. - - Attributes: - name (str): - The resource name of the ScanRun. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - The ScanRun IDs are generated by the system. - execution_state (google.cloud.websecurityscanner_v1alpha.types.ScanRun.ExecutionState): - The execution state of the ScanRun. - result_state (google.cloud.websecurityscanner_v1alpha.types.ScanRun.ResultState): - The result state of the ScanRun. This field - is only available after the execution state - reaches "FINISHED". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the ScanRun started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the ScanRun reached - termination state - that the ScanRun is either - finished or stopped by user. - urls_crawled_count (int): - The number of URLs crawled during this - ScanRun. If the scan is in progress, the value - represents the number of URLs crawled up to now. - urls_tested_count (int): - The number of URLs tested during this - ScanRun. If the scan is in progress, the value - represents the number of URLs tested up to now. - The number of URLs tested is usually larger than - the number URLS crawled because typically a - crawled URL is tested with multiple test - payloads. - has_vulnerabilities (bool): - Whether the scan run has found any - vulnerabilities. - progress_percent (int): - The percentage of total completion ranging - from 0 to 100. If the scan is in queue, the - value is 0. If the scan is running, the value - ranges from 0 to 100. If the scan is finished, - the value is 100. - """ - class ExecutionState(proto.Enum): - r"""Types of ScanRun execution state. - - Values: - EXECUTION_STATE_UNSPECIFIED (0): - Represents an invalid state caused by - internal server error. This value should never - be returned. - QUEUED (1): - The scan is waiting in the queue. - SCANNING (2): - The scan is in progress. - FINISHED (3): - The scan is either finished or stopped by - user. - """ - EXECUTION_STATE_UNSPECIFIED = 0 - QUEUED = 1 - SCANNING = 2 - FINISHED = 3 - - class ResultState(proto.Enum): - r"""Types of ScanRun result state. - - Values: - RESULT_STATE_UNSPECIFIED (0): - Default value. This value is returned when - the ScanRun is not yet finished. - SUCCESS (1): - The scan finished without errors. - ERROR (2): - The scan finished with errors. - KILLED (3): - The scan was terminated by user. - """ - RESULT_STATE_UNSPECIFIED = 0 - SUCCESS = 1 - ERROR = 2 - KILLED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - execution_state: ExecutionState = proto.Field( - proto.ENUM, - number=2, - enum=ExecutionState, - ) - result_state: ResultState = proto.Field( - proto.ENUM, - number=3, - enum=ResultState, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - urls_crawled_count: int = proto.Field( - proto.INT64, - number=6, - ) - urls_tested_count: int = proto.Field( - proto.INT64, - number=7, - ) - has_vulnerabilities: bool = proto.Field( - proto.BOOL, - number=8, - ) - progress_percent: int = proto.Field( - proto.INT32, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py deleted file mode 100644 index 2500ac7896a1..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats as gcw_finding_type_stats -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetScanConfigRequest', - 'ListScanConfigsRequest', - 'UpdateScanConfigRequest', - 'ListScanConfigsResponse', - 'StartScanRunRequest', - 'GetScanRunRequest', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StopScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'GetFindingRequest', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - }, -) - - -class CreateScanConfigRequest(proto.Message): - r"""Request for the ``CreateScanConfig`` method. - - Attributes: - parent (str): - Required. The parent resource name where the - scan is created, which should be a project - resource name in the format - 'projects/{projectId}'. - scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): - Required. The ScanConfig to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - scan_config: gcw_scan_config.ScanConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - - -class DeleteScanConfigRequest(proto.Message): - r"""Request for the ``DeleteScanConfig`` method. - - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be deleted. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanConfigRequest(proto.Message): - r"""Request for the ``GetScanConfig`` method. - - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanConfigsRequest(proto.Message): - r"""Request for the ``ListScanConfigs`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a project resource name in the format - 'projects/{projectId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanConfigs to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class UpdateScanConfigRequest(proto.Message): - r"""Request for the ``UpdateScanConfigRequest`` method. - - Attributes: - scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): - Required. The ScanConfig to be updated. The - name field must be set to identify the resource - to be updated. The values of fields not covered - by the mask will be ignored. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For the - ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - """ - - scan_config: gcw_scan_config.ScanConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ListScanConfigsResponse(proto.Message): - r"""Response for the ``ListScanConfigs`` method. - - Attributes: - scan_configs (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.ScanConfig]): - The list of ScanConfigs returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_configs: MutableSequence[gcw_scan_config.ScanConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_scan_config.ScanConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class StartScanRunRequest(proto.Message): - r"""Request for the ``StartScanRun`` method. - - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be used. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanRunRequest(proto.Message): - r"""Request for the ``GetScanRun`` method. - - Attributes: - name (str): - Required. The resource name of the ScanRun to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanRunsRequest(proto.Message): - r"""Request for the ``ListScanRuns`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanRuns to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListScanRunsResponse(proto.Message): - r"""Response for the ``ListScanRuns`` method. - - Attributes: - scan_runs (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.ScanRun]): - The list of ScanRuns returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_runs: MutableSequence[scan_run.ScanRun] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=scan_run.ScanRun, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class StopScanRunRequest(proto.Message): - r"""Request for the ``StopScanRun`` method. - - Attributes: - name (str): - Required. The resource name of the ScanRun to - be stopped. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListCrawledUrlsRequest(proto.Message): - r"""Request for the ``ListCrawledUrls`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of CrawledUrls to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCrawledUrlsResponse(proto.Message): - r"""Response for the ``ListCrawledUrls`` method. - - Attributes: - crawled_urls (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.CrawledUrl]): - The list of CrawledUrls returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - crawled_urls: MutableSequence[crawled_url.CrawledUrl] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=crawled_url.CrawledUrl, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFindingRequest(proto.Message): - r"""Request for the ``GetFinding`` method. - - Attributes: - name (str): - Required. The resource name of the Finding to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request for the ``ListFindings`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - filter (str): - Required. The filter expression. The expression must be in - the format: . Supported field: 'finding_type'. Supported - operator: '='. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of Findings to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response for the ``ListFindings`` method. - - Attributes: - findings (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.Finding]): - The list of Findings returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - findings: MutableSequence[finding.Finding] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=finding.Finding, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListFindingTypeStatsRequest(proto.Message): - r"""Request for the ``ListFindingTypeStats`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingTypeStatsResponse(proto.Message): - r"""Response for the ``ListFindingTypeStats`` method. - - Attributes: - finding_type_stats (MutableSequence[google.cloud.websecurityscanner_v1alpha.types.FindingTypeStats]): - The list of FindingTypeStats returned. - """ - - finding_type_stats: MutableSequence[gcw_finding_type_stats.FindingTypeStats] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_finding_type_stats.FindingTypeStats, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/mypy.ini b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/noxfile.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/noxfile.py deleted file mode 100644 index 9ddc35ffe522..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner' - -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/cloud/websecurityscanner_v1alpha/', - '--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/cloud/websecurityscanner_v1alpha/', - '--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-cloud-websecurityscanner/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json deleted file mode 100644 index c87e0efb514b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json +++ /dev/null @@ -1,2126 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.websecurityscanner.v1alpha", - "version": "v1alpha" - } - ], - "language": "PYTHON", - "name": "google-cloud-websecurityscanner", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.create_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.CreateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "CreateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "scan_config", - "type": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", - "shortName": "create_scan_config" - }, - "description": "Sample for CreateScanConfig", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.create_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.CreateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "CreateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "scan_config", - "type": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", - "shortName": "create_scan_config" - }, - "description": "Sample for CreateScanConfig", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.delete_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.DeleteScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "DeleteScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_scan_config" - }, - "description": "Sample for DeleteScanConfig", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.delete_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.DeleteScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "DeleteScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_scan_config" - }, - "description": "Sample for DeleteScanConfig", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.get_finding", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetFinding", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.Finding", - "shortName": "get_finding" - }, - "description": "Sample for GetFinding", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.get_finding", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetFinding", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.Finding", - "shortName": "get_finding" - }, - "description": "Sample for GetFinding", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.get_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", - "shortName": "get_scan_config" - }, - "description": "Sample for GetScanConfig", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.get_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", - "shortName": "get_scan_config" - }, - "description": "Sample for GetScanConfig", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.get_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", - "shortName": "get_scan_run" - }, - "description": "Sample for GetScanRun", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.get_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.GetScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", - "shortName": "get_scan_run" - }, - "description": "Sample for GetScanRun", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_crawled_urls", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListCrawledUrls", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListCrawledUrls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager", - "shortName": "list_crawled_urls" - }, - "description": "Sample for ListCrawledUrls", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_crawled_urls", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListCrawledUrls", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListCrawledUrls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsPager", - "shortName": "list_crawled_urls" - }, - "description": "Sample for ListCrawledUrls", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_finding_type_stats", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListFindingTypeStats", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindingTypeStats" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse", - "shortName": "list_finding_type_stats" - }, - "description": "Sample for ListFindingTypeStats", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_finding_type_stats", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListFindingTypeStats", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindingTypeStats" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse", - "shortName": "list_finding_type_stats" - }, - "description": "Sample for ListFindingTypeStats", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListFindings", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest" - }, - { - "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, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_findings", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListFindings", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest" - }, - { - "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, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_scan_configs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListScanConfigs", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsAsyncPager", - "shortName": "list_scan_configs" - }, - "description": "Sample for ListScanConfigs", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_scan_configs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListScanConfigs", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsPager", - "shortName": "list_scan_configs" - }, - "description": "Sample for ListScanConfigs", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.list_scan_runs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListScanRuns", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanRuns" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsAsyncPager", - "shortName": "list_scan_runs" - }, - "description": "Sample for ListScanRuns", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.list_scan_runs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.ListScanRuns", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanRuns" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsPager", - "shortName": "list_scan_runs" - }, - "description": "Sample for ListScanRuns", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.start_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.StartScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StartScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", - "shortName": "start_scan_run" - }, - "description": "Sample for StartScanRun", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.start_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.StartScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StartScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", - "shortName": "start_scan_run" - }, - "description": "Sample for StartScanRun", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.stop_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.StopScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StopScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", - "shortName": "stop_scan_run" - }, - "description": "Sample for StopScanRun", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.stop_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.StopScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StopScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanRun", - "shortName": "stop_scan_run" - }, - "description": "Sample for StopScanRun", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerAsyncClient.update_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.UpdateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "UpdateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest" - }, - { - "name": "scan_config", - "type": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig" - }, - { - "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, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", - "shortName": "update_scan_config" - }, - "description": "Sample for UpdateScanConfig", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1alpha.WebSecurityScannerClient.update_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner.UpdateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "UpdateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest" - }, - { - "name": "scan_config", - "type": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig" - }, - { - "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, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1alpha.types.ScanConfig", - "shortName": "update_scan_config" - }, - "description": "Sample for UpdateScanConfig", - "file": "websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_async.py deleted file mode 100644 index 9e5260326eaf..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_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 CreateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1alpha.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1alpha.CreateScanConfigRequest( - parent="parent_value", - scan_config=scan_config, - ) - - # Make the request - response = await client.create_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_sync.py deleted file mode 100644 index badf5b41523f..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_create_scan_config_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 CreateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1alpha.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1alpha.CreateScanConfigRequest( - parent="parent_value", - scan_config=scan_config, - ) - - # Make the request - response = client.create_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_CreateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_async.py deleted file mode 100644 index 07a1d176387e..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_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 DeleteScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.DeleteScanConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_scan_config(request=request) - - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_sync.py deleted file mode 100644 index e2ddc235ebb3..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_delete_scan_config_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 DeleteScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.DeleteScanConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_scan_config(request=request) - - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_DeleteScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_async.py deleted file mode 100644 index a74c0e27c557..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_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 GetFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_get_finding(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetFindingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_finding(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py deleted file mode 100644 index 04db260be284..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_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 GetFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_get_finding(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetFindingRequest( - name="name_value", - ) - - # Make the request - response = client.get_finding(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetFinding_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_async.py deleted file mode 100644 index 38c2eceaaddf..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_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 GetScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetScanConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_sync.py deleted file mode 100644 index 1fb688bf1790..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_config_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 GetScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetScanConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_async.py deleted file mode 100644 index e9e81d3d3418..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_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 GetScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.get_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_sync.py deleted file mode 100644 index 0cb2bb5b111d..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_scan_run_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 GetScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.GetScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.get_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_GetScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_async.py deleted file mode 100644 index f84eb09bc9d9..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListCrawledUrlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_sync.py deleted file mode 100644 index 98e151f40d16..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListCrawledUrlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListCrawledUrls_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_async.py deleted file mode 100644 index 7ef632849883..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListFindingTypeStatsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_sync.py deleted file mode 100644 index 7f041e22abfa..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListFindingTypeStatsRequest( - parent="parent_value", - ) - - # Make the request - response = client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindingTypeStats_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_async.py deleted file mode 100644 index 9325d57de8b3..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_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 ListFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_list_findings(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListFindingsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_sync.py deleted file mode 100644 index 1723efb8b714..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_findings_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 ListFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_list_findings(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListFindingsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_async.py deleted file mode 100644 index 1c052cece721..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListScanConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_sync.py deleted file mode 100644 index 4388366def42..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListScanConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanConfigs_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_async.py deleted file mode 100644 index 84097f7141f9..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_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 ListScanRuns -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListScanRunsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_sync.py deleted file mode 100644 index 918a3d1cf72a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_list_scan_runs_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 ListScanRuns -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.ListScanRunsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_async.py deleted file mode 100644 index f1201405b659..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_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 StartScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.StartScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.start_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_sync.py deleted file mode 100644 index b5b14ef2b99c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_start_scan_run_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 StartScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.StartScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.start_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_StartScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_async.py deleted file mode 100644 index 1f9f34d62eed..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_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 StopScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.StopScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.stop_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_sync.py deleted file mode 100644 index 55ae40e93966..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_stop_scan_run_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 StopScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1alpha.StopScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.stop_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_StopScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_async.py deleted file mode 100644 index da3f2a27ba86..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -async def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1alpha.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1alpha.UpdateScanConfigRequest( - scan_config=scan_config, - ) - - # Make the request - response = await client.update_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_sync.py deleted file mode 100644 index d8a2a522e64c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1alpha - - -def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1alpha.WebSecurityScannerClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1alpha.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1alpha.UpdateScanConfigRequest( - scan_config=scan_config, - ) - - # Make the request - response = client.update_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1alpha_generated_WebSecurityScanner_UpdateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py deleted file mode 100644 index cbe5261ddc2a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py +++ /dev/null @@ -1,188 +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 websecurityscannerCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_scan_config': ('parent', 'scan_config', ), - 'delete_scan_config': ('name', ), - 'get_finding': ('name', ), - 'get_scan_config': ('name', ), - 'get_scan_run': ('name', ), - 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_finding_type_stats': ('parent', ), - 'list_scan_configs': ('parent', 'page_token', 'page_size', ), - 'list_scan_runs': ('parent', 'page_token', 'page_size', ), - 'start_scan_run': ('name', ), - 'stop_scan_run': ('name', ), - 'update_scan_config': ('scan_config', '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=websecurityscannerCallTransformer(), -): - """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 websecurityscanner 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-cloud-websecurityscanner/v1alpha/setup.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/setup.py deleted file mode 100644 index b89eea40fd8f..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner' - - -description = "Google Cloud Websecurityscanner API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/websecurityscanner/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-cloud-websecurityscanner" - -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-cloud-websecurityscanner/v1alpha/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/tests/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/tests/unit/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/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-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__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-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py deleted file mode 100644 index 4d364f713f88..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py +++ /dev/null @@ -1,11488 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1alpha.services.web_security_scanner import WebSecurityScannerAsyncClient -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import transports -from google.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import finding_addon -from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_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 WebSecurityScannerClient._get_default_mtls_endpoint(None) is None - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert WebSecurityScannerClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - WebSecurityScannerClient._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 WebSecurityScannerClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert WebSecurityScannerClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - WebSecurityScannerClient._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 WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, False) is None - assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, True) is mock_default_cert_source - assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE - default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert WebSecurityScannerClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - assert WebSecurityScannerClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - WebSecurityScannerClient._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 WebSecurityScannerClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert WebSecurityScannerClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert WebSecurityScannerClient._get_universe_domain(None, None) == WebSecurityScannerClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - WebSecurityScannerClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (WebSecurityScannerClient, "grpc"), - (WebSecurityScannerAsyncClient, "grpc_asyncio"), - (WebSecurityScannerClient, "rest"), -]) -def test_web_security_scanner_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 == ( - 'websecurityscanner.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://websecurityscanner.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WebSecurityScannerGrpcTransport, "grpc"), - (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.WebSecurityScannerRestTransport, "rest"), -]) -def test_web_security_scanner_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", [ - (WebSecurityScannerClient, "grpc"), - (WebSecurityScannerAsyncClient, "grpc_asyncio"), - (WebSecurityScannerClient, "rest"), -]) -def test_web_security_scanner_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 == ( - 'websecurityscanner.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://websecurityscanner.googleapis.com' - ) - - -def test_web_security_scanner_client_get_transport_class(): - transport = WebSecurityScannerClient.get_transport_class() - available_transports = [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerRestTransport, - ] - assert transport in available_transports - - transport = WebSecurityScannerClient.get_transport_class("grpc") - assert transport == transports.WebSecurityScannerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), -]) -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_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(WebSecurityScannerClient, '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(WebSecurityScannerClient, '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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "true"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "false"), -]) -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_web_security_scanner_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", [ - WebSecurityScannerClient, WebSecurityScannerAsyncClient -]) -@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_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", [ - WebSecurityScannerClient, WebSecurityScannerAsyncClient -]) -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE - default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WebSecurityScannerClient._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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), -]) -def test_web_security_scanner_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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", None), -]) -def test_web_security_scanner_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_web_security_scanner_client_client_options_from_dict(): - with mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WebSecurityScannerClient( - 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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_web_security_scanner_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( - "websecurityscanner.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="websecurityscanner.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.CreateScanConfigRequest, - dict, -]) -def test_create_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - ) - response = client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.CreateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -def test_create_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.CreateScanConfigRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.CreateScanConfigRequest( - parent='parent_value', - ) - -def test_create_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - request = {} - client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - )) - response = await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.CreateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -@pytest.mark.asyncio -async def test_create_scan_config_async_from_dict(): - await test_create_scan_config_async(request_type=dict) - -def test_create_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_scan_config( - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(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].scan_config - mock_val = gcw_scan_config.ScanConfig(name='name_value') - assert arg == mock_val - - -def test_create_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_scan_config( - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(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].scan_config - mock_val = gcw_scan_config.ScanConfig(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.DeleteScanConfigRequest, - dict, -]) -def test_delete_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.DeleteScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.DeleteScanConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.DeleteScanConfigRequest( - name='name_value', - ) - -def test_delete_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - request = {} - client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.DeleteScanConfigRequest() - 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_scan_config_async_from_dict(): - await test_delete_scan_config_async(request_type=dict) - -def test_delete_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = None - client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__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_scan_config( - 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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__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_scan_config( - 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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanConfigRequest, - dict, -]) -def test_get_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - ) - response = client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -def test_get_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.GetScanConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanConfigRequest( - name='name_value', - ) - -def test_get_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc - request = {} - client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - )) - response = await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -@pytest.mark.asyncio -async def test_get_scan_config_async_from_dict(): - await test_get_scan_config_async(request_type=dict) - -def test_get_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_scan_config( - 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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_scan_config( - 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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanConfigsRequest, - dict, -]) -def test_list_scan_configs(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_configs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListScanConfigsRequest( - 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_scan_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_scan_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_scan_configs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_configs] = mock_rpc - request = {} - client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_configs(request) - - # Establish that a new wrapper 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_scan_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_configs in client._client._transport._wrapped_methods - - # 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_scan_configs] = mock_rpc - - request = {} - await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_scan_configs(request) - - # Establish that a new wrapper 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_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_configs_async_from_dict(): - await test_list_scan_configs_async(request_type=dict) - -def test_list_scan_configs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanConfigsResponse() - client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_configs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_configs_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_scan_configs( - 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_scan_configs_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_scan_configs_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_scan_configs( - 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_scan_configs_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - - -def test_list_scan_configs_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_configs(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, scan_config.ScanConfig) - for i in results) -def test_list_scan_configs_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_configs(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_scan_configs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_configs(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, scan_config.ScanConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_scan_configs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - 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_scan_configs(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", [ - web_security_scanner.UpdateScanConfigRequest, - dict, -]) -def test_update_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - ) - response = client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.UpdateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -def test_update_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.UpdateScanConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.UpdateScanConfigRequest( - ) - -def test_update_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - request = {} - client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - )) - response = await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.UpdateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -@pytest.mark.asyncio -async def test_update_scan_config_async_from_dict(): - await test_update_scan_config_async(request_type=dict) - -def test_update_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'scan_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'scan_config.name=name_value', - ) in kw['metadata'] - - -def test_update_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_scan_config( - scan_config=gcw_scan_config.ScanConfig(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].scan_config - mock_val = gcw_scan_config.ScanConfig(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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_scan_config( - scan_config=gcw_scan_config.ScanConfig(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].scan_config - mock_val = gcw_scan_config.ScanConfig(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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.StartScanRunRequest, - dict, -]) -def test_start_scan_run(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StartScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_start_scan_run_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.StartScanRunRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.start_scan_run(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest( - name='name_value', - ) - -def test_start_scan_run_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc - request = {} - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.start_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.start_scan_run in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.start_scan_run] = mock_rpc - - request = {} - await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.start_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StartScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_start_scan_run_async_from_dict(): - await test_start_scan_run_async(request_type=dict) - -def test_start_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.start_scan_run( - 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_start_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_start_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.start_scan_run( - 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_start_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanRunRequest, - dict, -]) -def test_get_scan_run(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_get_scan_run_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.GetScanRunRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_scan_run(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest( - name='name_value', - ) - -def test_get_scan_run_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc - request = {} - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_run(request) - - # Establish that a new wrapper 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_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_run in client._client._transport._wrapped_methods - - # 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_scan_run] = mock_rpc - - request = {} - await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_scan_run(request) - - # Establish that a new wrapper 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_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_get_scan_run_async_from_dict(): - await test_get_scan_run_async(request_type=dict) - -def test_get_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_scan_run( - 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_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_scan_run( - 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_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanRunsRequest, - dict, -]) -def test_list_scan_runs(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanRunsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_runs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListScanRunsRequest( - 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_scan_runs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_scan_runs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_scan_runs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_runs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_runs] = mock_rpc - request = {} - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_runs(request) - - # Establish that a new wrapper 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_scan_runs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_runs in client._client._transport._wrapped_methods - - # 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_scan_runs] = mock_rpc - - request = {} - await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_scan_runs(request) - - # Establish that a new wrapper 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_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanRunsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_runs_async_from_dict(): - await test_list_scan_runs_async(request_type=dict) - -def test_list_scan_runs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanRunsResponse() - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_runs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_runs_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_scan_runs( - 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_scan_runs_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_scan_runs_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_scan_runs( - 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_scan_runs_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - - -def test_list_scan_runs_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_runs(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, scan_run.ScanRun) - for i in results) -def test_list_scan_runs_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_runs(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_scan_runs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_runs(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, scan_run.ScanRun) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_scan_runs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - 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_scan_runs(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", [ - web_security_scanner.StopScanRunRequest, - dict, -]) -def test_stop_scan_run(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StopScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_stop_scan_run_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.StopScanRunRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.stop_scan_run(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest( - name='name_value', - ) - -def test_stop_scan_run_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc - request = {} - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.stop_scan_run in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.stop_scan_run] = mock_rpc - - request = {} - await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.stop_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StopScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_stop_scan_run_async_from_dict(): - await test_stop_scan_run_async(request_type=dict) - -def test_stop_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.stop_scan_run( - 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_stop_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_stop_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.stop_scan_run( - 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_stop_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListCrawledUrlsRequest, - dict, -]) -def test_list_crawled_urls(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListCrawledUrlsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_crawled_urls_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListCrawledUrlsRequest( - 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_crawled_urls), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_crawled_urls(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_crawled_urls_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_crawled_urls in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_crawled_urls] = mock_rpc - request = {} - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crawled_urls(request) - - # Establish that a new wrapper 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_crawled_urls_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_crawled_urls in client._client._transport._wrapped_methods - - # 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_crawled_urls] = mock_rpc - - request = {} - await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_crawled_urls(request) - - # Establish that a new wrapper 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_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListCrawledUrlsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_from_dict(): - await test_list_crawled_urls_async(request_type=dict) - -def test_list_crawled_urls_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crawled_urls_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crawled_urls_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_crawled_urls( - 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_crawled_urls_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_crawled_urls_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_crawled_urls( - 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_crawled_urls_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - - -def test_list_crawled_urls_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crawled_urls(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, crawled_url.CrawledUrl) - for i in results) -def test_list_crawled_urls_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - 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_crawled_urls(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", [ - web_security_scanner.GetFindingRequest, - dict, -]) -def test_get_finding(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - finding_type=finding.Finding.FindingType.MIXED_CONTENT, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - ) - response = client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -def test_get_finding_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.GetFindingRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetFindingRequest( - name='name_value', - ) - -def test_get_finding_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_finding in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc - request = {} - client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_finding(request) - - # Establish that a new wrapper 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_finding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # 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_finding] = mock_rpc - - request = {} - await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_finding(request) - - # Establish that a new wrapper 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_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - finding_type=finding.Finding.FindingType.MIXED_CONTENT, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - )) - response = await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -@pytest.mark.asyncio -async def test_get_finding_async_from_dict(): - await test_get_finding_async(request_type=dict) - -def test_get_finding_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = finding.Finding() - client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_finding( - 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_finding_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_finding_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_finding( - 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_finding_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_findings_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListFindingsRequest( - 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_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_findings_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_findings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_findings] = mock_rpc - request = {} - client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_findings(request) - - # Establish that a new wrapper 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_findings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_findings in client._client._transport._wrapped_methods - - # 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_findings] = mock_rpc - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_findings(request) - - # Establish that a new wrapper 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_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_findings_async_from_dict(): - await test_list_findings_async(request_type=dict) - -def test_list_findings_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingsResponse() - client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_findings_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_findings_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_findings( - 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_findings_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - -@pytest.mark.asyncio -async def test_list_findings_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_findings( - 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_findings_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_findings_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_findings(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, finding.Finding) - for i in results) -def test_list_findings_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - pages = list(client.list_findings(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_findings_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_findings(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, finding.Finding) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - 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_findings(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", [ - web_security_scanner.ListFindingTypeStatsRequest, - dict, -]) -def test_list_finding_type_stats(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse( - ) - response = client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingTypeStatsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -def test_list_finding_type_stats_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListFindingTypeStatsRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_finding_type_stats(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest( - parent='parent_value', - ) - -def test_list_finding_type_stats_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_finding_type_stats in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_finding_type_stats] = mock_rpc - request = {} - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_finding_type_stats(request) - - # Establish that a new wrapper 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_finding_type_stats_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_finding_type_stats in client._client._transport._wrapped_methods - - # 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_finding_type_stats] = mock_rpc - - request = {} - await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_finding_type_stats(request) - - # Establish that a new wrapper 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_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( - )) - response = await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingTypeStatsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_async_from_dict(): - await test_list_finding_type_stats_async(request_type=dict) - -def test_list_finding_type_stats_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_type_stats_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_type_stats_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_finding_type_stats( - 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_finding_type_stats_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_finding_type_stats_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_finding_type_stats( - 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_finding_type_stats_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - - -def test_create_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - - request = {} - client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_scan_config(request) - - # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.CreateScanConfigRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_scan_config._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_scan_config._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcw_scan_config.ScanConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_scan_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_scan_config_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_scan_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "scanConfig", ))) - - -def test_create_scan_config_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcw_scan_config.ScanConfig() - - # 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', - scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_scan_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*}/scanConfigs" % client.transport._host, args[1]) - - -def test_create_scan_config_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - - -def test_delete_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - - request = {} - client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_scan_config(request) - - # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.DeleteScanConfigRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_scan_config._get_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_scan_config._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - 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 - - response = client.delete_scan_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_scan_config_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_scan_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_scan_config_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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/scanConfigs/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 - - client.delete_scan_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_scan_config_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - - -def test_get_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc - - request = {} - client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_config(request) - - # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.GetScanConfigRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_scan_config._get_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_scan_config._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = scan_config.ScanConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_scan_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_scan_config_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_scan_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_scan_config_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = scan_config.ScanConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_scan_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) - - -def test_get_scan_config_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - - -def test_list_scan_configs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_configs] = mock_rpc - - request = {} - client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_configs(request) - - # Establish 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_scan_configs_rest_required_fields(request_type=web_security_scanner.ListScanConfigsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_scan_configs._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_scan_configs._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListScanConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_scan_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_scan_configs_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_scan_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_scan_configs_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListScanConfigsResponse() - - # 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_scan_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*}/scanConfigs" % client.transport._host, args[1]) - - -def test_list_scan_configs_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - - -def test_list_scan_configs_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListScanConfigsResponse.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_scan_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, scan_config.ScanConfig) - for i in results) - - pages = list(client.list_scan_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - - request = {} - client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_scan_config(request) - - # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.UpdateScanConfigRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_scan_config._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_scan_config._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcw_scan_config.ScanConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_scan_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_scan_config_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_scan_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("scanConfig", "updateMask", ))) - - -def test_update_scan_config_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcw_scan_config.ScanConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_scan_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{scan_config.name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) - - -def test_update_scan_config_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_start_scan_run_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc - - request = {} - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.start_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_start_scan_run_rest_required_fields(request_type=web_security_scanner.StartScanRunRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).start_scan_run._get_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()).start_scan_run._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.start_scan_run(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_start_scan_run_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.start_scan_run._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_start_scan_run_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.start_scan_run(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*}:start" % client.transport._host, args[1]) - - -def test_start_scan_run_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - - -def test_get_scan_run_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc - - request = {} - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_run(request) - - # Establish 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_scan_run_rest_required_fields(request_type=web_security_scanner.GetScanRunRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_scan_run._get_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_scan_run._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_scan_run(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_scan_run_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_scan_run._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_scan_run_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_scan_run(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}" % client.transport._host, args[1]) - - -def test_get_scan_run_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - - -def test_list_scan_runs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_runs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_runs] = mock_rpc - - request = {} - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_runs(request) - - # Establish 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_scan_runs_rest_required_fields(request_type=web_security_scanner.ListScanRunsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_scan_runs._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_scan_runs._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListScanRunsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_scan_runs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_scan_runs_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_scan_runs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_scan_runs_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListScanRunsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_scan_runs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*/scanConfigs/*}/scanRuns" % client.transport._host, args[1]) - - -def test_list_scan_runs_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - - -def test_list_scan_runs_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListScanRunsResponse.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/scanConfigs/sample2'} - - pager = client.list_scan_runs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, scan_run.ScanRun) - for i in results) - - pages = list(client.list_scan_runs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_stop_scan_run_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc - - request = {} - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_stop_scan_run_rest_required_fields(request_type=web_security_scanner.StopScanRunRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).stop_scan_run._get_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()).stop_scan_run._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.stop_scan_run(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_stop_scan_run_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.stop_scan_run._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_stop_scan_run_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.stop_scan_run(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}:stop" % client.transport._host, args[1]) - - -def test_stop_scan_run_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - - -def test_list_crawled_urls_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_crawled_urls in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_crawled_urls] = mock_rpc - - request = {} - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crawled_urls(request) - - # Establish 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_crawled_urls_rest_required_fields(request_type=web_security_scanner.ListCrawledUrlsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_crawled_urls._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_crawled_urls._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListCrawledUrlsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_crawled_urls(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_crawled_urls_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_crawled_urls._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_crawled_urls_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListCrawledUrlsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} - - # 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_crawled_urls(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls" % client.transport._host, args[1]) - - -def test_list_crawled_urls_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - - -def test_list_crawled_urls_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListCrawledUrlsResponse.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/scanConfigs/sample2/scanRuns/sample3'} - - pager = client.list_crawled_urls(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, crawled_url.CrawledUrl) - for i in results) - - pages = list(client.list_crawled_urls(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_finding_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_finding in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc - - request = {} - client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_finding(request) - - # Establish 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_finding_rest_required_fields(request_type=web_security_scanner.GetFindingRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_finding._get_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_finding._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = finding.Finding() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = finding.Finding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_finding_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_finding_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} - - # 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 = finding.Finding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_finding(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}" % client.transport._host, args[1]) - - -def test_get_finding_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - - -def test_list_findings_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_findings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_findings] = mock_rpc - - request = {} - client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_findings(request) - - # Establish 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_findings_rest_required_fields(request_type=web_security_scanner.ListFindingsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["filter"] = "" - request = request_type(**request_init) - pb_request = request_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 "filter" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "filter" in jsonified_request - assert jsonified_request["filter"] == request_init["filter"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["filter"] = 'filter_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_findings._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' - assert "filter" in jsonified_request - assert jsonified_request["filter"] == 'filter_value' - - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_findings(request) - - expected_params = [ - ( - "filter", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_findings_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", "filter", ))) - - -def test_list_findings_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} - - # 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 = web_security_scanner.ListFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_findings(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings" % client.transport._host, args[1]) - - -def test_list_findings_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListFindingsResponse.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/scanConfigs/sample2/scanRuns/sample3'} - - pager = client.list_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, finding.Finding) - for i in results) - - pages = list(client.list_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_finding_type_stats_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_finding_type_stats in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_finding_type_stats] = mock_rpc - - request = {} - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_finding_type_stats(request) - - # Establish 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_finding_type_stats_rest_required_fields(request_type=web_security_scanner.ListFindingTypeStatsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_finding_type_stats._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_finding_type_stats._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListFindingTypeStatsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_finding_type_stats(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_finding_type_stats_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_finding_type_stats._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -def test_list_finding_type_stats_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListFindingTypeStatsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} - - # 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 = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_finding_type_stats(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats" % client.transport._host, args[1]) - - -def test_list_finding_type_stats_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - 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 = WebSecurityScannerClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WebSecurityScannerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - transports.WebSecurityScannerRestTransport, -]) -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 = WebSecurityScannerClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = WebSecurityScannerClient( - 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.create_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.CreateScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = None - client.delete_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.DeleteScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.get_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_configs_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanConfigsResponse() - client.list_scan_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanConfigsRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.update_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.UpdateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_scan_run_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.start_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StartScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_run_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.get_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_runs_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanRunsResponse() - client.list_scan_runs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanRunsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_scan_run_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.stop_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StopScanRunRequest() - - assert args[0] == request_msg - - -# This 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_crawled_urls_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - client.list_crawled_urls(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListCrawledUrlsRequest() - - assert args[0] == request_msg - - -# This 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_finding_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = finding.Finding() - client.get_finding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetFindingRequest() - - assert args[0] == request_msg - - -# This 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_findings_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingsResponse() - client.list_findings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingsRequest() - - assert args[0] == request_msg - - -# This 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_finding_type_stats_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - client.list_finding_type_stats(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingTypeStatsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = WebSecurityScannerAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - )) - await client.create_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.CreateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.DeleteScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - )) - await client.get_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_configs_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - )) - await client.list_scan_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - )) - await client.update_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.UpdateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_start_scan_run_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - await client.start_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StartScanRunRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_run_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - await client.get_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanRunRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_runs_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - )) - await client.list_scan_runs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanRunsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_stop_scan_run_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - await client.stop_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StopScanRunRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_crawled_urls_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - )) - await client.list_crawled_urls(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListCrawledUrlsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_finding_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - finding_type=finding.Finding.FindingType.MIXED_CONTENT, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - )) - await client.get_finding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetFindingRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_findings_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - )) - await client.list_findings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_finding_type_stats_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( - )) - await client.list_finding_type_stats(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingTypeStatsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = WebSecurityScannerClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_scan_config_rest_bad_request(request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerClient( - 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 - client.create_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.CreateScanConfigRequest, - dict, -]) -def test_create_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["scan_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'target_platforms': [1], 'latest_run': {'name': 'name_value', 'execution_state': 1, 'result_state': 1, 'start_time': {}, 'end_time': {}, 'urls_crawled_count': 1935, 'urls_tested_count': 1846, 'has_vulnerabilities': True, 'progress_percent': 1733}} - # 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 = web_security_scanner.CreateScanConfigRequest.meta.fields["scan_config"] - - 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["scan_config"].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["scan_config"][field])): - del request_init["scan_config"][field][i][subfield] - else: - del request_init["scan_config"][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 = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_scan_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_create_scan_config") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_create_scan_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.CreateScanConfigRequest.pb(web_security_scanner.CreateScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = gcw_scan_config.ScanConfig.to_json(gcw_scan_config.ScanConfig()) - req.return_value.content = return_value - - request = web_security_scanner.CreateScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcw_scan_config.ScanConfig() - - client.create_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_scan_config_rest_bad_request(request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - client.delete_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.DeleteScanConfigRequest, - dict, -]) -def test_delete_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - response = client.delete_scan_config(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_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_delete_scan_config") as pre: - pre.assert_not_called() - pb_message = web_security_scanner.DeleteScanConfigRequest.pb(web_security_scanner.DeleteScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - - request = web_security_scanner.DeleteScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_get_scan_config_rest_bad_request(request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - client.get_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanConfigRequest, - dict, -]) -def test_get_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_scan_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_config") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.GetScanConfigRequest.pb(web_security_scanner.GetScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) - req.return_value.content = return_value - - request = web_security_scanner.GetScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_config.ScanConfig() - - client.get_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_scan_configs_rest_bad_request(request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerClient( - 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 - client.list_scan_configs(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanConfigsRequest, - dict, -]) -def test_list_scan_configs_rest_call_success(request_type): - client = WebSecurityScannerClient( - 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 = web_security_scanner.ListScanConfigsResponse( - 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_scan_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_scan_configs_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_configs") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListScanConfigsRequest.pb(web_security_scanner.ListScanConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListScanConfigsResponse.to_json(web_security_scanner.ListScanConfigsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListScanConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListScanConfigsResponse() - - client.list_scan_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_scan_config_rest_bad_request(request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/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 - client.update_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.UpdateScanConfigRequest, - dict, -]) -def test_update_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} - request_init["scan_config"] = {'name': 'projects/sample1/scanConfigs/sample2', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'target_platforms': [1], 'latest_run': {'name': 'name_value', 'execution_state': 1, 'result_state': 1, 'start_time': {}, 'end_time': {}, 'urls_crawled_count': 1935, 'urls_tested_count': 1846, 'has_vulnerabilities': True, 'progress_percent': 1733}} - # 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 = web_security_scanner.UpdateScanConfigRequest.meta.fields["scan_config"] - - 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["scan_config"].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["scan_config"][field])): - del request_init["scan_config"][field][i][subfield] - else: - del request_init["scan_config"][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 = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_scan_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_update_scan_config") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_update_scan_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.UpdateScanConfigRequest.pb(web_security_scanner.UpdateScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = gcw_scan_config.ScanConfig.to_json(gcw_scan_config.ScanConfig()) - req.return_value.content = return_value - - request = web_security_scanner.UpdateScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcw_scan_config.ScanConfig() - - client.update_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_start_scan_run_rest_bad_request(request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - client.start_scan_run(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.StartScanRunRequest, - dict, -]) -def test_start_scan_run_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.start_scan_run(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_start_scan_run_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_start_scan_run") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_start_scan_run") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.StartScanRunRequest.pb(web_security_scanner.StartScanRunRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) - req.return_value.content = return_value - - request = web_security_scanner.StartScanRunRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_run.ScanRun() - - client.start_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_scan_run_rest_bad_request(request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.get_scan_run(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanRunRequest, - dict, -]) -def test_get_scan_run_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_scan_run(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_scan_run_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_run") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_run") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.GetScanRunRequest.pb(web_security_scanner.GetScanRunRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) - req.return_value.content = return_value - - request = web_security_scanner.GetScanRunRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_run.ScanRun() - - client.get_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_scan_runs_rest_bad_request(request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/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 - client.list_scan_runs(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanRunsRequest, - dict, -]) -def test_list_scan_runs_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse( - 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_scan_runs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_scan_runs_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_runs") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_runs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListScanRunsRequest.pb(web_security_scanner.ListScanRunsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListScanRunsResponse.to_json(web_security_scanner.ListScanRunsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListScanRunsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListScanRunsResponse() - - client.list_scan_runs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_stop_scan_run_rest_bad_request(request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.stop_scan_run(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.StopScanRunRequest, - dict, -]) -def test_stop_scan_run_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.stop_scan_run(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_stop_scan_run_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_stop_scan_run") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_stop_scan_run") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.StopScanRunRequest.pb(web_security_scanner.StopScanRunRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) - req.return_value.content = return_value - - request = web_security_scanner.StopScanRunRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_run.ScanRun() - - client.stop_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_crawled_urls_rest_bad_request(request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.list_crawled_urls(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListCrawledUrlsRequest, - dict, -]) -def test_list_crawled_urls_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListCrawledUrlsResponse( - 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_crawled_urls(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_crawled_urls_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_crawled_urls") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_crawled_urls") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListCrawledUrlsRequest.pb(web_security_scanner.ListCrawledUrlsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListCrawledUrlsResponse.to_json(web_security_scanner.ListCrawledUrlsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListCrawledUrlsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListCrawledUrlsResponse() - - client.list_crawled_urls(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_finding_rest_bad_request(request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_finding(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetFindingRequest, - dict, -]) -def test_get_finding_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = finding.Finding( - name='name_value', - finding_type=finding.Finding.FindingType.MIXED_CONTENT, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = finding.Finding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_finding_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_finding") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.GetFindingRequest.pb(web_security_scanner.GetFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = finding.Finding.to_json(finding.Finding()) - req.return_value.content = return_value - - request = web_security_scanner.GetFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.get_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.list_findings(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListFindingsRequest, - dict, -]) -def test_list_findings_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingsResponse( - 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 = web_security_scanner.ListFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListFindingsRequest.pb(web_security_scanner.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListFindingsResponse.to_json(web_security_scanner.ListFindingsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_finding_type_stats_rest_bad_request(request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.list_finding_type_stats(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListFindingTypeStatsRequest, - dict, -]) -def test_list_finding_type_stats_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingTypeStatsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_finding_type_stats(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_finding_type_stats_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_finding_type_stats") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_finding_type_stats") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListFindingTypeStatsRequest.pb(web_security_scanner.ListFindingTypeStatsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListFindingTypeStatsResponse.to_json(web_security_scanner.ListFindingTypeStatsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListFindingTypeStatsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListFindingTypeStatsResponse() - - client.list_finding_type_stats(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = WebSecurityScannerClient( - 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - client.create_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.CreateScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - client.delete_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.DeleteScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - client.get_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_configs_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - client.list_scan_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanConfigsRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - client.update_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.UpdateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_scan_run_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - client.start_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StartScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_run_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - client.get_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_runs_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - client.list_scan_runs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanRunsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_scan_run_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - client.stop_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StopScanRunRequest() - - assert args[0] == request_msg - - -# This 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_crawled_urls_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - client.list_crawled_urls(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListCrawledUrlsRequest() - - assert args[0] == request_msg - - -# This 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_finding_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - client.get_finding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetFindingRequest() - - assert args[0] == request_msg - - -# This 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_findings_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - client.list_findings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingsRequest() - - assert args[0] == request_msg - - -# This 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_finding_type_stats_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - client.list_finding_type_stats(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingTypeStatsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WebSecurityScannerGrpcTransport, - ) - -def test_web_security_scanner_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_web_security_scanner_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_scan_config', - 'delete_scan_config', - 'get_scan_config', - 'list_scan_configs', - 'update_scan_config', - 'start_scan_run', - 'get_scan_run', - 'list_scan_runs', - 'stop_scan_run', - 'list_crawled_urls', - 'get_finding', - 'list_findings', - 'list_finding_type_stats', - ) - 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_web_security_scanner_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - 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_web_security_scanner_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport() - adc.assert_called_once() - - -def test_web_security_scanner_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) - WebSecurityScannerClient() - 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.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - transports.WebSecurityScannerRestTransport, - ], -) -def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, grpc_helpers), - (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_web_security_scanner_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( - "websecurityscanner.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="websecurityscanner.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_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_web_security_scanner_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.WebSecurityScannerRestTransport ( - 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_web_security_scanner_host_no_port(transport_name): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'websecurityscanner.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://websecurityscanner.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_web_security_scanner_host_with_port(transport_name): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'websecurityscanner.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://websecurityscanner.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_web_security_scanner_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = WebSecurityScannerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = WebSecurityScannerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_scan_config._session - session2 = client2.transport.create_scan_config._session - assert session1 != session2 - session1 = client1.transport.delete_scan_config._session - session2 = client2.transport.delete_scan_config._session - assert session1 != session2 - session1 = client1.transport.get_scan_config._session - session2 = client2.transport.get_scan_config._session - assert session1 != session2 - session1 = client1.transport.list_scan_configs._session - session2 = client2.transport.list_scan_configs._session - assert session1 != session2 - session1 = client1.transport.update_scan_config._session - session2 = client2.transport.update_scan_config._session - assert session1 != session2 - session1 = client1.transport.start_scan_run._session - session2 = client2.transport.start_scan_run._session - assert session1 != session2 - session1 = client1.transport.get_scan_run._session - session2 = client2.transport.get_scan_run._session - assert session1 != session2 - session1 = client1.transport.list_scan_runs._session - session2 = client2.transport.list_scan_runs._session - assert session1 != session2 - session1 = client1.transport.stop_scan_run._session - session2 = client2.transport.stop_scan_run._session - assert session1 != session2 - session1 = client1.transport.list_crawled_urls._session - session2 = client2.transport.list_crawled_urls._session - assert session1 != session2 - session1 = client1.transport.get_finding._session - session2 = client2.transport.get_finding._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_finding_type_stats._session - session2 = client2.transport.list_finding_type_stats._session - assert session1 != session2 -def test_web_security_scanner_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcTransport( - 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_web_security_scanner_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - 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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_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_finding_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - finding = "octopus" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "project": "oyster", - "scan_config": "nudibranch", - "scan_run": "cuttlefish", - "finding": "mussel", - } - path = WebSecurityScannerClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_finding_path(path) - assert expected == actual - -def test_scan_config_path(): - project = "winkle" - scan_config = "nautilus" - expected = "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) - actual = WebSecurityScannerClient.scan_config_path(project, scan_config) - assert expected == actual - - -def test_parse_scan_config_path(): - expected = { - "project": "scallop", - "scan_config": "abalone", - } - path = WebSecurityScannerClient.scan_config_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_scan_config_path(path) - assert expected == actual - -def test_scan_run_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) - actual = WebSecurityScannerClient.scan_run_path(project, scan_config, scan_run) - assert expected == actual - - -def test_parse_scan_run_path(): - expected = { - "project": "octopus", - "scan_config": "oyster", - "scan_run": "nudibranch", - } - path = WebSecurityScannerClient.scan_run_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_scan_run_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WebSecurityScannerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = WebSecurityScannerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = WebSecurityScannerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = WebSecurityScannerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WebSecurityScannerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = WebSecurityScannerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = WebSecurityScannerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = WebSecurityScannerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.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 = WebSecurityScannerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = WebSecurityScannerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.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.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - transport_class = WebSecurityScannerClient.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 = WebSecurityScannerClient( - 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 = WebSecurityScannerAsyncClient( - 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 = WebSecurityScannerClient( - 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 = WebSecurityScannerClient( - 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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport), -]) -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-cloud-websecurityscanner/v1beta/.coveragerc b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/.coveragerc deleted file mode 100644 index 085a92b30288..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/websecurityscanner/__init__.py - google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1beta/.flake8 b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/MANIFEST.in deleted file mode 100644 index e23fd8ac9a4f..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/websecurityscanner *.py -recursive-include google/cloud/websecurityscanner_v1beta *.py diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/README.rst deleted file mode 100644 index 4de4c103eee6..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Websecurityscanner 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 Cloud Websecurityscanner 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-cloud-websecurityscanner/v1beta/docs/_static/custom.css b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/conf.py deleted file mode 100644 index 40ff11b301ef..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner 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-cloud-websecurityscanner" -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 Cloud 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-cloud-websecurityscanner-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-cloud-websecurityscanner.tex", - u"google-cloud-websecurityscanner 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-cloud-websecurityscanner", - u"Google Cloud Websecurityscanner 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-cloud-websecurityscanner", - u"google-cloud-websecurityscanner Documentation", - author, - "google-cloud-websecurityscanner", - "GAPIC library for Google Cloud Websecurityscanner 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-cloud-websecurityscanner/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/index.rst deleted file mode 100644 index 1760f1337efd..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - websecurityscanner_v1beta/services_ - websecurityscanner_v1beta/types_ diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/services_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/services_.rst deleted file mode 100644 index 37adbdcbd3bb..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Websecurityscanner v1beta API -======================================================= -.. toctree:: - :maxdepth: 2 - - web_security_scanner diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/types_.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/types_.rst deleted file mode 100644 index 531b92bae980..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Websecurityscanner v1beta API -==================================================== - -.. automodule:: google.cloud.websecurityscanner_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst deleted file mode 100644 index 8918acef9d56..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst +++ /dev/null @@ -1,10 +0,0 @@ -WebSecurityScanner ------------------------------------- - -.. automodule:: google.cloud.websecurityscanner_v1beta.services.web_security_scanner - :members: - :inherited-members: - -.. automodule:: google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/__init__.py deleted file mode 100644 index 9c3ef58bf6b7..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/__init__.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner.client import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient - -from google.cloud.websecurityscanner_v1beta.types.crawled_url import CrawledUrl -from google.cloud.websecurityscanner_v1beta.types.finding import Finding -from google.cloud.websecurityscanner_v1beta.types.finding_addon import Form -from google.cloud.websecurityscanner_v1beta.types.finding_addon import OutdatedLibrary -from google.cloud.websecurityscanner_v1beta.types.finding_addon import ViolatingResource -from google.cloud.websecurityscanner_v1beta.types.finding_addon import VulnerableHeaders -from google.cloud.websecurityscanner_v1beta.types.finding_addon import VulnerableParameters -from google.cloud.websecurityscanner_v1beta.types.finding_addon import Xss -from google.cloud.websecurityscanner_v1beta.types.finding_type_stats import FindingTypeStats -from google.cloud.websecurityscanner_v1beta.types.scan_config import ScanConfig -from google.cloud.websecurityscanner_v1beta.types.scan_config_error import ScanConfigError -from google.cloud.websecurityscanner_v1beta.types.scan_run import ScanRun -from google.cloud.websecurityscanner_v1beta.types.scan_run_error_trace import ScanRunErrorTrace -from google.cloud.websecurityscanner_v1beta.types.scan_run_warning_trace import ScanRunWarningTrace -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import CreateScanConfigRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import DeleteScanConfigRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetFindingRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetScanConfigRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetScanRunRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListCrawledUrlsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListCrawledUrlsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingTypeStatsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingTypeStatsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanConfigsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanConfigsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanRunsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanRunsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import StartScanRunRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import StopScanRunRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ('WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', - 'CrawledUrl', - 'Finding', - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanConfigError', - 'ScanRun', - 'ScanRunErrorTrace', - 'ScanRunWarningTrace', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/py.typed deleted file mode 100644 index 8cfb5d256398..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py deleted file mode 100644 index 5eaa835c5f1d..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/__init__.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 google.cloud.websecurityscanner_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.web_security_scanner import WebSecurityScannerClient -from .services.web_security_scanner import WebSecurityScannerAsyncClient - -from .types.crawled_url import CrawledUrl -from .types.finding import Finding -from .types.finding_addon import Form -from .types.finding_addon import OutdatedLibrary -from .types.finding_addon import ViolatingResource -from .types.finding_addon import VulnerableHeaders -from .types.finding_addon import VulnerableParameters -from .types.finding_addon import Xss -from .types.finding_type_stats import FindingTypeStats -from .types.scan_config import ScanConfig -from .types.scan_config_error import ScanConfigError -from .types.scan_run import ScanRun -from .types.scan_run_error_trace import ScanRunErrorTrace -from .types.scan_run_warning_trace import ScanRunWarningTrace -from .types.web_security_scanner import CreateScanConfigRequest -from .types.web_security_scanner import DeleteScanConfigRequest -from .types.web_security_scanner import GetFindingRequest -from .types.web_security_scanner import GetScanConfigRequest -from .types.web_security_scanner import GetScanRunRequest -from .types.web_security_scanner import ListCrawledUrlsRequest -from .types.web_security_scanner import ListCrawledUrlsResponse -from .types.web_security_scanner import ListFindingsRequest -from .types.web_security_scanner import ListFindingsResponse -from .types.web_security_scanner import ListFindingTypeStatsRequest -from .types.web_security_scanner import ListFindingTypeStatsResponse -from .types.web_security_scanner import ListScanConfigsRequest -from .types.web_security_scanner import ListScanConfigsResponse -from .types.web_security_scanner import ListScanRunsRequest -from .types.web_security_scanner import ListScanRunsResponse -from .types.web_security_scanner import StartScanRunRequest -from .types.web_security_scanner import StopScanRunRequest -from .types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ( - 'WebSecurityScannerAsyncClient', -'CrawledUrl', -'CreateScanConfigRequest', -'DeleteScanConfigRequest', -'Finding', -'FindingTypeStats', -'Form', -'GetFindingRequest', -'GetScanConfigRequest', -'GetScanRunRequest', -'ListCrawledUrlsRequest', -'ListCrawledUrlsResponse', -'ListFindingTypeStatsRequest', -'ListFindingTypeStatsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListScanConfigsRequest', -'ListScanConfigsResponse', -'ListScanRunsRequest', -'ListScanRunsResponse', -'OutdatedLibrary', -'ScanConfig', -'ScanConfigError', -'ScanRun', -'ScanRunErrorTrace', -'ScanRunWarningTrace', -'StartScanRunRequest', -'StopScanRunRequest', -'UpdateScanConfigRequest', -'ViolatingResource', -'VulnerableHeaders', -'VulnerableParameters', -'WebSecurityScannerClient', -'Xss', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json deleted file mode 100644 index 329504a244c4..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json +++ /dev/null @@ -1,223 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.websecurityscanner_v1beta", - "protoPackage": "google.cloud.websecurityscanner.v1beta", - "schema": "1.0", - "services": { - "WebSecurityScanner": { - "clients": { - "grpc": { - "libraryClient": "WebSecurityScannerClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WebSecurityScannerAsyncClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - }, - "rest": { - "libraryClient": "WebSecurityScannerClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/py.typed b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/py.typed deleted file mode 100644 index 8cfb5d256398..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py deleted file mode 100644 index 3aeec5e07d95..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__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 WebSecurityScannerClient -from .async_client import WebSecurityScannerAsyncClient - -__all__ = ( - 'WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py deleted file mode 100644 index 78cb9dc65331..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py +++ /dev/null @@ -1,1700 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.websecurityscanner_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.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import finding_addon -from google.cloud.websecurityscanner_v1beta.types import finding_type_stats -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .client import WebSecurityScannerClient - - -class WebSecurityScannerAsyncClient: - """Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - """ - - _client: WebSecurityScannerClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = WebSecurityScannerClient._DEFAULT_UNIVERSE - - finding_path = staticmethod(WebSecurityScannerClient.finding_path) - parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) - scan_config_path = staticmethod(WebSecurityScannerClient.scan_config_path) - parse_scan_config_path = staticmethod(WebSecurityScannerClient.parse_scan_config_path) - scan_run_path = staticmethod(WebSecurityScannerClient.scan_run_path) - parse_scan_run_path = staticmethod(WebSecurityScannerClient.parse_scan_run_path) - common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) - parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) - common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) - parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) - common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) - parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) - common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) - parse_common_location_path = staticmethod(WebSecurityScannerClient.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: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, 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: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, 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 WebSecurityScannerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: 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 = WebSecurityScannerClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner 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,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): - 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 WebSecurityScannerTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WebSecurityScannerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_scan_config(self, - request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - scan_config: Optional[gcw_scan_config.ScanConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1beta.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1beta.CreateScanConfigRequest( - parent="parent_value", - scan_config=scan_config, - ) - - # Make the request - response = await client.create_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest, dict]]): - The request object. Request for the ``CreateScanConfig`` method. - parent (:class:`str`): - Required. The parent resource name - where the scan is created, which should - be a project resource name in the format - 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - scan_config (:class:`google.cloud.websecurityscanner_v1beta.types.ScanConfig`): - Required. The ScanConfig to be - created. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_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. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, scan_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, web_security_scanner.CreateScanConfigRequest): - request = web_security_scanner.CreateScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if scan_config is not None: - request.scan_config = scan_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_scan_config] - - # Certain fields should be provided within 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_scan_config(self, - request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.DeleteScanConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_scan_config(request=request) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest, dict]]): - The request object. Request for the ``DeleteScanConfig`` method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be deleted. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.DeleteScanConfigRequest): - request = web_security_scanner.DeleteScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_config] - - # Certain fields should be provided within 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 get_scan_config(self, - request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetScanConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest, dict]]): - The request object. Request for the ``GetScanConfig`` method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be returned. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetScanConfigRequest): - request = web_security_scanner.GetScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_config] - - # Certain fields should be provided within 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_scan_configs(self, - request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsAsyncPager: - r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1beta - - async def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListScanConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest, dict]]): - The request object. Request for the ``ListScanConfigs`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a project resource name - in the format 'projects/{projectId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: - Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): - request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] - - # Certain fields should be provided within 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.ListScanConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_scan_config(self, - request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, - *, - scan_config: Optional[gcw_scan_config.ScanConfig] = 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, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1beta.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1beta.UpdateScanConfigRequest( - scan_config=scan_config, - ) - - # Make the request - response = await client.update_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest, dict]]): - The request object. Request for the ``UpdateScanConfigRequest`` method. - scan_config (:class:`google.cloud.websecurityscanner_v1beta.types.ScanConfig`): - Required. The ScanConfig to be - updated. The name field must be set to - identify the resource to be updated. The - values of fields not covered by the mask - will be ignored. - - This corresponds to the ``scan_config`` 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 update mask applies to the resource. For - the ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([scan_config, 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, web_security_scanner.UpdateScanConfigRequest): - request = web_security_scanner.UpdateScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scan_config is not None: - request.scan_config = scan_config - 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_scan_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.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 start_scan_run(self, - request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.StartScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.start_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest, dict]]): - The request object. Request for the ``StartScanRun`` method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be used. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.StartScanRunRequest): - request = web_security_scanner.StartScanRunRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.start_scan_run] - - # Certain fields should be provided within 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_scan_run(self, - request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.get_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest, dict]]): - The request object. Request for the ``GetScanRun`` method. - name (:class:`str`): - Required. The resource name of the - ScanRun to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetScanRunRequest): - request = web_security_scanner.GetScanRunRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_run] - - # Certain fields should be provided within 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_scan_runs(self, - request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsAsyncPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListScanRunsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest, dict]]): - The request object. Request for the ``ListScanRuns`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan resource name in - the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsAsyncPager: - Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): - request = web_security_scanner.ListScanRunsRequest(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_scan_runs] - - # Certain fields should be provided within 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.ListScanRunsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def stop_scan_run(self, - request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.StopScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.stop_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest, dict]]): - The request object. Request for the ``StopScanRun`` method. - name (:class:`str`): - Required. The resource name of the - ScanRun to be stopped. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.StopScanRunRequest): - request = web_security_scanner.StopScanRunRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.stop_scan_run] - - # Certain fields should be provided within 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_crawled_urls(self, - request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsAsyncPager: - r"""List CrawledUrls under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListCrawledUrlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest, dict]]): - The request object. Request for the ``ListCrawledUrls`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: - Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] - - # Certain fields should be provided within 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.ListCrawledUrlsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_finding(self, - request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_get_finding(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetFindingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.GetFindingRequest, dict]]): - The request object. Request for the ``GetFinding`` method. - name (:class:`str`): - Required. The resource name of the - Finding to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetFindingRequest): - request = web_security_scanner.GetFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_finding] - - # Certain fields should be provided within 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_findings(self, - request: Optional[Union[web_security_scanner.ListFindingsRequest, 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, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""List Findings under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_list_findings(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListFindingsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest, dict]]): - The request object. Request for the ``ListFindings`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Required. The filter expression. The expression must be - in the format: . Supported field: 'finding_type'. - Supported operator: '='. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsAsyncPager: - Response for the ListFindings 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, 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, web_security_scanner.ListFindingsRequest): - request = web_security_scanner.ListFindingsRequest(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_findings] - - # Certain fields should be provided within 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.ListFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_finding_type_stats(self, - request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - async def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListFindingTypeStatsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest, dict]]): - The request object. Request for the ``ListFindingTypeStats`` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats method. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - 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, web_security_scanner.ListFindingTypeStatsRequest): - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] - - # Certain fields should be provided within 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) -> "WebSecurityScannerAsyncClient": - 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__ = ( - "WebSecurityScannerAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py deleted file mode 100644 index dca8b7f4c4f1..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py +++ /dev/null @@ -1,2062 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.websecurityscanner_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 - -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import finding_addon -from google.cloud.websecurityscanner_v1beta.types import finding_type_stats -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WebSecurityScannerGrpcTransport -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .transports.rest import WebSecurityScannerRestTransport - - -class WebSecurityScannerClientMeta(type): - """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] - _transport_registry["grpc"] = WebSecurityScannerGrpcTransport - _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport - _transport_registry["rest"] = WebSecurityScannerRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[WebSecurityScannerTransport]: - """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 WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): - """Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - """ - - @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 = "websecurityscanner.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "websecurityscanner.{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: - WebSecurityScannerClient: 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: - WebSecurityScannerClient: 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) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def scan_config_path(project: str,scan_config: str,) -> str: - """Returns a fully-qualified scan_config string.""" - return "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) - - @staticmethod - def parse_scan_config_path(path: str) -> Dict[str,str]: - """Parses a scan_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def scan_run_path(project: str,scan_config: str,scan_run: str,) -> str: - """Returns a fully-qualified scan_run string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) - - @staticmethod - def parse_scan_run_path(path: str) -> Dict[str,str]: - """Parses a scan_run path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?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 = WebSecurityScannerClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = WebSecurityScannerClient._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 = WebSecurityScannerClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - WebSecurityScannerClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, WebSecurityScannerTransport, Callable[..., WebSecurityScannerTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,WebSecurityScannerTransport,Callable[..., WebSecurityScannerTransport]]]): - 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 WebSecurityScannerTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WebSecurityScannerClient._read_environment_variables() - self._client_cert_source = WebSecurityScannerClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = WebSecurityScannerClient._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 - - 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, WebSecurityScannerTransport) - if transport_provided: - # transport is a WebSecurityScannerTransport 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(WebSecurityScannerTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - WebSecurityScannerClient._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[WebSecurityScannerTransport], Callable[..., WebSecurityScannerTransport]] = ( - WebSecurityScannerClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., WebSecurityScannerTransport], 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, - ) - - def create_scan_config(self, - request: Optional[Union[web_security_scanner.CreateScanConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - scan_config: Optional[gcw_scan_config.ScanConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1beta.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1beta.CreateScanConfigRequest( - parent="parent_value", - scan_config=scan_config, - ) - - # Make the request - response = client.create_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest, dict]): - The request object. Request for the ``CreateScanConfig`` method. - parent (str): - Required. The parent resource name - where the scan is created, which should - be a project resource name in the format - 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): - Required. The ScanConfig to be - created. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.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. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, scan_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, web_security_scanner.CreateScanConfigRequest): - request = web_security_scanner.CreateScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if scan_config is not None: - request.scan_config = scan_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_scan_config] - - # Certain fields should be provided within 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_scan_config(self, - request: Optional[Union[web_security_scanner.DeleteScanConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.DeleteScanConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_scan_config(request=request) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest, dict]): - The request object. Request for the ``DeleteScanConfig`` method. - name (str): - Required. The resource name of the - ScanConfig to be deleted. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.DeleteScanConfigRequest): - request = web_security_scanner.DeleteScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_config] - - # Certain fields should be provided within 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 get_scan_config(self, - request: Optional[Union[web_security_scanner.GetScanConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetScanConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest, dict]): - The request object. Request for the ``GetScanConfig`` method. - name (str): - Required. The resource name of the - ScanConfig to be returned. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetScanConfigRequest): - request = web_security_scanner.GetScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_config] - - # Certain fields should be provided within 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_scan_configs(self, - request: Optional[Union[web_security_scanner.ListScanConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsPager: - r"""Lists ScanConfigs under a given 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.cloud import websecurityscanner_v1beta - - def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListScanConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest, dict]): - The request object. Request for the ``ListScanConfigs`` method. - parent (str): - Required. The parent resource name, - which should be a project resource name - in the format 'projects/{projectId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsPager: - Response for the ListScanConfigs 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, web_security_scanner.ListScanConfigsRequest): - request = web_security_scanner.ListScanConfigsRequest(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_scan_configs] - - # Certain fields should be provided within 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.ListScanConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_scan_config(self, - request: Optional[Union[web_security_scanner.UpdateScanConfigRequest, dict]] = None, - *, - scan_config: Optional[gcw_scan_config.ScanConfig] = 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, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1beta.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1beta.UpdateScanConfigRequest( - scan_config=scan_config, - ) - - # Make the request - response = client.update_scan_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest, dict]): - The request object. Request for the ``UpdateScanConfigRequest`` method. - scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): - Required. The ScanConfig to be - updated. The name field must be set to - identify the resource to be updated. The - values of fields not covered by the mask - will be ignored. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For - the ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([scan_config, 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, web_security_scanner.UpdateScanConfigRequest): - request = web_security_scanner.UpdateScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scan_config is not None: - request.scan_config = scan_config - 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_scan_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.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 start_scan_run(self, - request: Optional[Union[web_security_scanner.StartScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.StartScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.start_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest, dict]): - The request object. Request for the ``StartScanRun`` method. - name (str): - Required. The resource name of the - ScanConfig to be used. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.StartScanRunRequest): - request = web_security_scanner.StartScanRunRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.start_scan_run] - - # Certain fields should be provided within 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_scan_run(self, - request: Optional[Union[web_security_scanner.GetScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.get_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest, dict]): - The request object. Request for the ``GetScanRun`` method. - name (str): - Required. The resource name of the - ScanRun to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetScanRunRequest): - request = web_security_scanner.GetScanRunRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_scan_run] - - # Certain fields should be provided within 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_scan_runs(self, - request: Optional[Union[web_security_scanner.ListScanRunsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListScanRunsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest, dict]): - The request object. Request for the ``ListScanRuns`` method. - parent (str): - Required. The parent resource name, - which should be a scan resource name in - the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsPager: - Response for the ListScanRuns 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, web_security_scanner.ListScanRunsRequest): - request = web_security_scanner.ListScanRunsRequest(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_scan_runs] - - # Certain fields should be provided within 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.ListScanRunsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def stop_scan_run(self, - request: Optional[Union[web_security_scanner.StopScanRunRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.StopScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.stop_scan_run(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest, dict]): - The request object. Request for the ``StopScanRun`` method. - name (str): - Required. The resource name of the - ScanRun to be stopped. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.StopScanRunRequest): - request = web_security_scanner.StopScanRunRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.stop_scan_run] - - # Certain fields should be provided within 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_crawled_urls(self, - request: Optional[Union[web_security_scanner.ListCrawledUrlsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsPager: - r"""List CrawledUrls under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListCrawledUrlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest, dict]): - The request object. Request for the ``ListCrawledUrls`` method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsPager: - Response for the ListCrawledUrls 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, web_security_scanner.ListCrawledUrlsRequest): - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] - - # Certain fields should be provided within 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.ListCrawledUrlsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_finding(self, - request: Optional[Union[web_security_scanner.GetFindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_get_finding(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetFindingRequest( - name="name_value", - ) - - # Make the request - response = client.get_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.GetFindingRequest, dict]): - The request object. Request for the ``GetFinding`` method. - name (str): - Required. The resource name of the - Finding to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, web_security_scanner.GetFindingRequest): - request = web_security_scanner.GetFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_finding] - - # Certain fields should be provided within 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_findings(self, - request: Optional[Union[web_security_scanner.ListFindingsRequest, 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, str]] = (), - ) -> pagers.ListFindingsPager: - r"""List Findings under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_list_findings(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListFindingsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest, dict]): - The request object. Request for the ``ListFindings`` method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Required. The filter expression. The expression must be - in the format: . Supported field: 'finding_type'. - Supported operator: '='. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsPager: - Response for the ListFindings 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, 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, web_security_scanner.ListFindingsRequest): - request = web_security_scanner.ListFindingsRequest(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_findings] - - # Certain fields should be provided within 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.ListFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_finding_type_stats(self, - request: Optional[Union[web_security_scanner.ListFindingTypeStatsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import websecurityscanner_v1beta - - def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListFindingTypeStatsRequest( - parent="parent_value", - ) - - # Make the request - response = client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest, dict]): - The request object. Request for the ``ListFindingTypeStats`` method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats method. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - 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, web_security_scanner.ListFindingTypeStatsRequest): - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] - - # Certain fields should be provided within 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) -> "WebSecurityScannerClient": - 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__ = ( - "WebSecurityScannerClient", -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py deleted file mode 100644 index 6efe8a0e28a5..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py +++ /dev/null @@ -1,571 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner - - -class ListScanConfigsPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListScanConfigsResponse], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - for page in self.pages: - yield from page.scan_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanConfigsAsyncPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` - attributes are available on the 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[web_security_scanner.ListScanConfigsResponse]], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanConfigsRequest(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[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListScanRunsResponse], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - for page in self.pages: - yield from page.scan_runs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsAsyncPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` - attributes are available on the 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[web_security_scanner.ListScanRunsResponse]], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListScanRunsRequest(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[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_runs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListCrawledUrlsResponse], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - for page in self.pages: - yield from page.crawled_urls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsAsyncPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` - attributes are available on the 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[web_security_scanner.ListCrawledUrlsResponse]], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListCrawledUrlsRequest(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[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - async def async_generator(): - async for page in self.pages: - for response in page.crawled_urls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListFindingsResponse], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: - 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[finding.Finding]: - for page in self.pages: - yield from page.findings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` - attributes are available on the 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[web_security_scanner.ListFindingsResponse]], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListFindingsRequest(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[web_security_scanner.ListFindingsResponse]: - 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[finding.Finding]: - async def async_generator(): - async for page in self.pages: - for response in page.findings: - 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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/README.rst b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/README.rst deleted file mode 100644 index 3479ee767648..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`WebSecurityScannerTransport` is the ABC for all transports. -- public child `WebSecurityScannerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `WebSecurityScannerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseWebSecurityScannerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `WebSecurityScannerRestTransport` 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-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py deleted file mode 100644 index e24819a4ee07..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/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 WebSecurityScannerTransport -from .grpc import WebSecurityScannerGrpcTransport -from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .rest import WebSecurityScannerRestTransport -from .rest import WebSecurityScannerRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] -_transport_registry['grpc'] = WebSecurityScannerGrpcTransport -_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport -_transport_registry['rest'] = WebSecurityScannerRestTransport - -__all__ = ( - 'WebSecurityScannerTransport', - 'WebSecurityScannerGrpcTransport', - 'WebSecurityScannerGrpcAsyncIOTransport', - 'WebSecurityScannerRestTransport', - 'WebSecurityScannerRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py deleted file mode 100644 index c37593cea39e..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner_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.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class WebSecurityScannerTransport(abc.ABC): - """Abstract transport class for WebSecurityScanner.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_scan_config: gapic_v1.method.wrap_method( - self.create_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.delete_scan_config: gapic_v1.method.wrap_method( - self.delete_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_config: gapic_v1.method.wrap_method( - self.get_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_configs: gapic_v1.method.wrap_method( - self.list_scan_configs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_scan_config: gapic_v1.method.wrap_method( - self.update_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.start_scan_run: gapic_v1.method.wrap_method( - self.start_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_run: gapic_v1.method.wrap_method( - self.get_scan_run, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_runs: gapic_v1.method.wrap_method( - self.list_scan_runs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.stop_scan_run: gapic_v1.method.wrap_method( - self.stop_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.list_crawled_urls: gapic_v1.method.wrap_method( - self.list_crawled_urls, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_finding: gapic_v1.method.wrap_method( - self.get_finding, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_finding_type_stats: gapic_v1.method.wrap_method( - self.list_finding_type_stats, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Union[ - gcw_scan_config.ScanConfig, - Awaitable[gcw_scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Union[ - web_security_scanner.ListScanConfigsResponse, - Awaitable[web_security_scanner.ListScanConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Union[ - gcw_scan_config.ScanConfig, - Awaitable[gcw_scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Union[ - web_security_scanner.ListScanRunsResponse, - Awaitable[web_security_scanner.ListScanRunsResponse] - ]]: - raise NotImplementedError() - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Union[ - web_security_scanner.ListCrawledUrlsResponse, - Awaitable[web_security_scanner.ListCrawledUrlsResponse] - ]]: - raise NotImplementedError() - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Union[ - web_security_scanner.ListFindingsResponse, - Awaitable[web_security_scanner.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Union[ - web_security_scanner.ListFindingTypeStatsResponse, - Awaitable[web_security_scanner.ListFindingTypeStatsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'WebSecurityScannerTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py deleted file mode 100644 index e7ee11f751a4..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO - - -class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): - """gRPC backend transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'websecurityscanner.googleapis.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_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - gcw_scan_config.ScanConfig]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - ~.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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - web_security_scanner.ListScanConfigsResponse]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - ~.ListScanConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - gcw_scan_config.ScanConfig]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - web_security_scanner.ListScanRunsResponse]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - ~.ListScanRunsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - web_security_scanner.ListCrawledUrlsResponse]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - ~.ListCrawledUrlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - finding.Finding]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - web_security_scanner.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - Returns: - Callable[[~.ListFindingsRequest], - ~.ListFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - web_security_scanner.ListFindingTypeStatsResponse]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - ~.ListFindingTypeStatsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'WebSecurityScannerGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py deleted file mode 100644 index e8b3e6905c4c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py +++ /dev/null @@ -1,764 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .grpc import WebSecurityScannerGrpcTransport - - -class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): - """gRPC AsyncIO backend transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'websecurityscanner.googleapis.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 = 'websecurityscanner.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: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Awaitable[gcw_scan_config.ScanConfig]]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - 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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Awaitable[web_security_scanner.ListScanConfigsResponse]]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - Awaitable[~.ListScanConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Awaitable[gcw_scan_config.ScanConfig]]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Awaitable[web_security_scanner.ListScanRunsResponse]]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - Awaitable[~.ListScanRunsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - Awaitable[~.ListCrawledUrlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Awaitable[web_security_scanner.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - Returns: - Callable[[~.ListFindingsRequest], - Awaitable[~.ListFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - Awaitable[~.ListFindingTypeStatsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - 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_scan_config: self._wrap_method( - self.create_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.delete_scan_config: self._wrap_method( - self.delete_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_config: self._wrap_method( - self.get_scan_config, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_configs: self._wrap_method( - self.list_scan_configs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_scan_config: self._wrap_method( - self.update_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.start_scan_run: self._wrap_method( - self.start_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_run: self._wrap_method( - self.get_scan_run, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_runs: self._wrap_method( - self.list_scan_runs, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.stop_scan_run: self._wrap_method( - self.stop_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.list_crawled_urls: self._wrap_method( - self.list_crawled_urls, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_finding: self._wrap_method( - self.get_finding, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_findings: self._wrap_method( - self.list_findings, - 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=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_finding_type_stats: self._wrap_method( - self.list_finding_type_stats, - 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=600.0, - ), - default_timeout=600.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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'WebSecurityScannerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py deleted file mode 100644 index 0047e1ffa541..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py +++ /dev/null @@ -1,1533 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - - -from .rest_base import _BaseWebSecurityScannerRestTransport -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 - - -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 WebSecurityScannerRestInterceptor: - """Interceptor for WebSecurityScanner. - - 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 WebSecurityScannerRestTransport. - - .. code-block:: python - class MyCustomWebSecurityScannerInterceptor(WebSecurityScannerRestInterceptor): - def pre_create_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_scan_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_scan_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_scan_run(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_scan_run(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_crawled_urls(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_crawled_urls(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_finding_type_stats(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_finding_type_stats(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_scan_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_scan_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_scan_runs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_scan_runs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_start_scan_run(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_start_scan_run(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stop_scan_run(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stop_scan_run(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_scan_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_scan_config(self, response): - logging.log(f"Received response: {response}") - return response - - transport = WebSecurityScannerRestTransport(interceptor=MyCustomWebSecurityScannerInterceptor()) - client = WebSecurityScannerClient(transport=transport) - - - """ - def pre_create_scan_config(self, request: web_security_scanner.CreateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.CreateScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_create_scan_config(self, response: gcw_scan_config.ScanConfig) -> gcw_scan_config.ScanConfig: - """Post-rpc interceptor for create_scan_config - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_delete_scan_config(self, request: web_security_scanner.DeleteScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.DeleteScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def pre_get_finding(self, request: web_security_scanner.GetFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_get_finding(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for get_finding - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_get_scan_config(self, request: web_security_scanner.GetScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_get_scan_config(self, response: scan_config.ScanConfig) -> scan_config.ScanConfig: - """Post-rpc interceptor for get_scan_config - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_get_scan_run(self, request: web_security_scanner.GetScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.GetScanRunRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_scan_run - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_get_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: - """Post-rpc interceptor for get_scan_run - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_crawled_urls(self, request: web_security_scanner.ListCrawledUrlsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListCrawledUrlsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_crawled_urls - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_crawled_urls(self, response: web_security_scanner.ListCrawledUrlsResponse) -> web_security_scanner.ListCrawledUrlsResponse: - """Post-rpc interceptor for list_crawled_urls - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_findings(self, request: web_security_scanner.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_findings(self, response: web_security_scanner.ListFindingsResponse) -> web_security_scanner.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_finding_type_stats(self, request: web_security_scanner.ListFindingTypeStatsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListFindingTypeStatsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_finding_type_stats - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_finding_type_stats(self, response: web_security_scanner.ListFindingTypeStatsResponse) -> web_security_scanner.ListFindingTypeStatsResponse: - """Post-rpc interceptor for list_finding_type_stats - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_scan_configs(self, request: web_security_scanner.ListScanConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_scan_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_scan_configs(self, response: web_security_scanner.ListScanConfigsResponse) -> web_security_scanner.ListScanConfigsResponse: - """Post-rpc interceptor for list_scan_configs - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_list_scan_runs(self, request: web_security_scanner.ListScanRunsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.ListScanRunsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_scan_runs - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_list_scan_runs(self, response: web_security_scanner.ListScanRunsResponse) -> web_security_scanner.ListScanRunsResponse: - """Post-rpc interceptor for list_scan_runs - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_start_scan_run(self, request: web_security_scanner.StartScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StartScanRunRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for start_scan_run - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_start_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: - """Post-rpc interceptor for start_scan_run - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_stop_scan_run(self, request: web_security_scanner.StopScanRunRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.StopScanRunRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for stop_scan_run - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_stop_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: - """Post-rpc interceptor for stop_scan_run - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - def pre_update_scan_config(self, request: web_security_scanner.UpdateScanConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[web_security_scanner.UpdateScanConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_scan_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the WebSecurityScanner server. - """ - return request, metadata - - def post_update_scan_config(self, response: gcw_scan_config.ScanConfig) -> gcw_scan_config.ScanConfig: - """Post-rpc interceptor for update_scan_config - - Override in a subclass to manipulate the response - after it is returned by the WebSecurityScanner server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class WebSecurityScannerRestStub: - _session: AuthorizedSession - _host: str - _interceptor: WebSecurityScannerRestInterceptor - - -class WebSecurityScannerRestTransport(_BaseWebSecurityScannerRestTransport): - """REST backend synchronous transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'websecurityscanner.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[WebSecurityScannerRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'websecurityscanner.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 WebSecurityScannerRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateScanConfig(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.CreateScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.CreateScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcw_scan_config.ScanConfig: - r"""Call the create scan config method over HTTP. - - Args: - request (~.web_security_scanner.CreateScanConfigRequest): - The request object. Request for the ``CreateScanConfig`` method. - retry (google.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. - - Returns: - ~.gcw_scan_config.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_http_options() - request, metadata = self._interceptor.pre_create_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._CreateScanConfig._get_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 = gcw_scan_config.ScanConfig() - pb_resp = gcw_scan_config.ScanConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_scan_config(resp) - return resp - - class _DeleteScanConfig(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.DeleteScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.DeleteScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete scan config method over HTTP. - - Args: - request (~.web_security_scanner.DeleteScanConfigRequest): - The request object. Request for the ``DeleteScanConfig`` method. - retry (google.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. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_http_options() - request, metadata = self._interceptor.pre_delete_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._DeleteScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 _GetFinding(_BaseWebSecurityScannerRestTransport._BaseGetFinding, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.GetFinding") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.GetFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the get finding method over HTTP. - - Args: - request (~.web_security_scanner.GetFindingRequest): - The request object. Request for the ``GetFinding`` method. - retry (google.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. - - Returns: - ~.finding.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_http_options() - request, metadata = self._interceptor.pre_get_finding(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseGetFinding._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._GetFinding._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = finding.Finding() - pb_resp = finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_finding(resp) - return resp - - class _GetScanConfig(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.GetScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.GetScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_config.ScanConfig: - r"""Call the get scan config method over HTTP. - - Args: - request (~.web_security_scanner.GetScanConfigRequest): - The request object. Request for the ``GetScanConfig`` method. - retry (google.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. - - Returns: - ~.scan_config.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_http_options() - request, metadata = self._interceptor.pre_get_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._GetScanConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = scan_config.ScanConfig() - pb_resp = scan_config.ScanConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_scan_config(resp) - return resp - - class _GetScanRun(_BaseWebSecurityScannerRestTransport._BaseGetScanRun, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.GetScanRun") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.GetScanRunRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_run.ScanRun: - r"""Call the get scan run method over HTTP. - - Args: - request (~.web_security_scanner.GetScanRunRequest): - The request object. Request for the ``GetScanRun`` method. - retry (google.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. - - Returns: - ~.scan_run.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_http_options() - request, metadata = self._interceptor.pre_get_scan_run(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._GetScanRun._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = scan_run.ScanRun() - pb_resp = scan_run.ScanRun.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_scan_run(resp) - return resp - - class _ListCrawledUrls(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListCrawledUrls") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListCrawledUrlsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListCrawledUrlsResponse: - r"""Call the list crawled urls method over HTTP. - - Args: - request (~.web_security_scanner.ListCrawledUrlsRequest): - The request object. Request for the ``ListCrawledUrls`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListCrawledUrlsResponse: - Response for the ``ListCrawledUrls`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_http_options() - request, metadata = self._interceptor.pre_list_crawled_urls(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListCrawledUrls._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListCrawledUrlsResponse() - pb_resp = web_security_scanner.ListCrawledUrlsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_crawled_urls(resp) - return resp - - class _ListFindings(_BaseWebSecurityScannerRestTransport._BaseListFindings, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListFindings") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.web_security_scanner.ListFindingsRequest): - The request object. Request for the ``ListFindings`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListFindingsResponse: - Response for the ``ListFindings`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_http_options() - request, metadata = self._interceptor.pre_list_findings(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListFindings._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListFindings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListFindingsResponse() - pb_resp = web_security_scanner.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListFindingTypeStats(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListFindingTypeStats") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListFindingTypeStatsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""Call the list finding type stats method over HTTP. - - Args: - request (~.web_security_scanner.ListFindingTypeStatsRequest): - The request object. Request for the ``ListFindingTypeStats`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListFindingTypeStatsResponse: - Response for the ``ListFindingTypeStats`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_http_options() - request, metadata = self._interceptor.pre_list_finding_type_stats(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListFindingTypeStats._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListFindingTypeStatsResponse() - pb_resp = web_security_scanner.ListFindingTypeStatsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_finding_type_stats(resp) - return resp - - class _ListScanConfigs(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListScanConfigs") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListScanConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListScanConfigsResponse: - r"""Call the list scan configs method over HTTP. - - Args: - request (~.web_security_scanner.ListScanConfigsRequest): - The request object. Request for the ``ListScanConfigs`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListScanConfigsResponse: - Response for the ``ListScanConfigs`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_http_options() - request, metadata = self._interceptor.pre_list_scan_configs(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListScanConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListScanConfigsResponse() - pb_resp = web_security_scanner.ListScanConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_scan_configs(resp) - return resp - - class _ListScanRuns(_BaseWebSecurityScannerRestTransport._BaseListScanRuns, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.ListScanRuns") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: web_security_scanner.ListScanRunsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> web_security_scanner.ListScanRunsResponse: - r"""Call the list scan runs method over HTTP. - - Args: - request (~.web_security_scanner.ListScanRunsRequest): - The request object. Request for the ``ListScanRuns`` method. - retry (google.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. - - Returns: - ~.web_security_scanner.ListScanRunsResponse: - Response for the ``ListScanRuns`` method. - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_http_options() - request, metadata = self._interceptor.pre_list_scan_runs(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._ListScanRuns._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = web_security_scanner.ListScanRunsResponse() - pb_resp = web_security_scanner.ListScanRunsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_scan_runs(resp) - return resp - - class _StartScanRun(_BaseWebSecurityScannerRestTransport._BaseStartScanRun, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.StartScanRun") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.StartScanRunRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_run.ScanRun: - r"""Call the start scan run method over HTTP. - - Args: - request (~.web_security_scanner.StartScanRunRequest): - The request object. Request for the ``StartScanRun`` method. - retry (google.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. - - Returns: - ~.scan_run.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_http_options() - request, metadata = self._interceptor.pre_start_scan_run(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._StartScanRun._get_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 = scan_run.ScanRun() - pb_resp = scan_run.ScanRun.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_start_scan_run(resp) - return resp - - class _StopScanRun(_BaseWebSecurityScannerRestTransport._BaseStopScanRun, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.StopScanRun") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.StopScanRunRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> scan_run.ScanRun: - r"""Call the stop scan run method over HTTP. - - Args: - request (~.web_security_scanner.StopScanRunRequest): - The request object. Request for the ``StopScanRun`` method. - retry (google.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. - - Returns: - ~.scan_run.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_http_options() - request, metadata = self._interceptor.pre_stop_scan_run(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._StopScanRun._get_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 = scan_run.ScanRun() - pb_resp = scan_run.ScanRun.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_stop_scan_run(resp) - return resp - - class _UpdateScanConfig(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig, WebSecurityScannerRestStub): - def __hash__(self): - return hash("WebSecurityScannerRestTransport.UpdateScanConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: web_security_scanner.UpdateScanConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcw_scan_config.ScanConfig: - r"""Call the update scan config method over HTTP. - - Args: - request (~.web_security_scanner.UpdateScanConfigRequest): - The request object. Request for the ``UpdateScanConfigRequest`` method. - retry (google.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. - - Returns: - ~.gcw_scan_config.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - - http_options = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_http_options() - request, metadata = self._interceptor.pre_update_scan_config(request, metadata) - transcoded_request = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_transcoded_request(http_options, request) - - body = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WebSecurityScannerRestTransport._UpdateScanConfig._get_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 = gcw_scan_config.ScanConfig() - pb_resp = gcw_scan_config.ScanConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_scan_config(resp) - return resp - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - gcw_scan_config.ScanConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - 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._DeleteScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - finding.Finding]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - scan_config.ScanConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - scan_run.ScanRun]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetScanRun(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - web_security_scanner.ListCrawledUrlsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListCrawledUrls(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - web_security_scanner.ListFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - web_security_scanner.ListFindingTypeStatsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListFindingTypeStats(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - web_security_scanner.ListScanConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListScanConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - web_security_scanner.ListScanRunsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListScanRuns(self._session, self._host, self._interceptor) # type: ignore - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - scan_run.ScanRun]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StartScanRun(self._session, self._host, self._interceptor) # type: ignore - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - scan_run.ScanRun]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StopScanRun(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - gcw_scan_config.ScanConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateScanConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'WebSecurityScannerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest_base.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest_base.py deleted file mode 100644 index 0f5225b1985e..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest_base.py +++ /dev/null @@ -1,617 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 WebSecurityScannerTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - - -class _BaseWebSecurityScannerRestTransport(WebSecurityScannerTransport): - """Base REST backend transport for WebSecurityScanner. - - 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 = 'websecurityscanner.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: 'websecurityscanner.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 _BaseCreateScanConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{parent=projects/*}/scanConfigs', - 'body': 'scan_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.CreateScanConfigRequest.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(_BaseWebSecurityScannerRestTransport._BaseCreateScanConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteScanConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{name=projects/*/scanConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.DeleteScanConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseDeleteScanConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetFinding: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.GetFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetFinding._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetScanConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/scanConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.GetScanConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetScanConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetScanRun: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.GetScanRunRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseGetScanRun._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListCrawledUrls: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListCrawledUrlsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListCrawledUrls._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListFindings: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "filter" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListFindings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListFindingTypeStats: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListFindingTypeStatsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListFindingTypeStats._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListScanConfigs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*}/scanConfigs', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListScanConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListScanConfigs._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListScanRuns: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/scanConfigs/*}/scanRuns', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.ListScanRunsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWebSecurityScannerRestTransport._BaseListScanRuns._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStartScanRun: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{name=projects/*/scanConfigs/*}:start', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.StartScanRunRequest.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(_BaseWebSecurityScannerRestTransport._BaseStartScanRun._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStopScanRun: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}:stop', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.StopScanRunRequest.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(_BaseWebSecurityScannerRestTransport._BaseStopScanRun._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateScanConfig: - 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': '/v1beta/{scan_config.name=projects/*/scanConfigs/*}', - 'body': 'scan_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = web_security_scanner.UpdateScanConfigRequest.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(_BaseWebSecurityScannerRestTransport._BaseUpdateScanConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseWebSecurityScannerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py deleted file mode 100644 index b1fb4aa1c3eb..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.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 .crawled_url import ( - CrawledUrl, -) -from .finding import ( - Finding, -) -from .finding_addon import ( - Form, - OutdatedLibrary, - ViolatingResource, - VulnerableHeaders, - VulnerableParameters, - Xss, -) -from .finding_type_stats import ( - FindingTypeStats, -) -from .scan_config import ( - ScanConfig, -) -from .scan_config_error import ( - ScanConfigError, -) -from .scan_run import ( - ScanRun, -) -from .scan_run_error_trace import ( - ScanRunErrorTrace, -) -from .scan_run_warning_trace import ( - ScanRunWarningTrace, -) -from .web_security_scanner import ( - CreateScanConfigRequest, - DeleteScanConfigRequest, - GetFindingRequest, - GetScanConfigRequest, - GetScanRunRequest, - ListCrawledUrlsRequest, - ListCrawledUrlsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListFindingTypeStatsRequest, - ListFindingTypeStatsResponse, - ListScanConfigsRequest, - ListScanConfigsResponse, - ListScanRunsRequest, - ListScanRunsResponse, - StartScanRunRequest, - StopScanRunRequest, - UpdateScanConfigRequest, -) - -__all__ = ( - 'CrawledUrl', - 'Finding', - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanConfigError', - 'ScanRun', - 'ScanRunErrorTrace', - 'ScanRunWarningTrace', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py deleted file mode 100644 index cd27919d0274..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.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.cloud.websecurityscanner.v1beta', - manifest={ - 'CrawledUrl', - }, -) - - -class CrawledUrl(proto.Message): - r"""A CrawledUrl resource represents a URL that was crawled - during a ScanRun. Web Security Scanner Service crawls the web - applications, following all links within the scope of sites, to - find the URLs to test against. - - Attributes: - http_method (str): - The http method of the request that was used - to visit the URL, in uppercase. - url (str): - The URL that was crawled. - body (str): - The body of the request that was used to - visit the URL. - """ - - http_method: str = proto.Field( - proto.STRING, - number=1, - ) - url: str = proto.Field( - proto.STRING, - number=2, - ) - body: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py deleted file mode 100644 index 7dbf038192cb..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py +++ /dev/null @@ -1,169 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner_v1beta.types import finding_addon - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""A Finding resource represents a vulnerability instance - identified during a ScanRun. - - Attributes: - name (str): - The resource name of the Finding. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. - The finding IDs are generated by the system. - finding_type (str): - The type of the Finding. - Detailed and up-to-date information on findings - can be found here: - - https://cloud.google.com/security-scanner/docs/scan-result-details - http_method (str): - The http method of the request that triggered - the vulnerability, in uppercase. - fuzzed_url (str): - The URL produced by the server-side fuzzer - and used in the request that triggered the - vulnerability. - body (str): - The body of the request that triggered the - vulnerability. - description (str): - The description of the vulnerability. - reproduction_url (str): - The URL containing human-readable payload - that user can leverage to reproduce the - vulnerability. - frame_url (str): - If the vulnerability was originated from - nested IFrame, the immediate parent IFrame is - reported. - final_url (str): - The URL where the browser lands when the - vulnerability is detected. - tracking_id (str): - The tracking ID uniquely identifies a - vulnerability instance across multiple ScanRuns. - form (google.cloud.websecurityscanner_v1beta.types.Form): - An addon containing information reported for - a vulnerability with an HTML form, if any. - outdated_library (google.cloud.websecurityscanner_v1beta.types.OutdatedLibrary): - An addon containing information about - outdated libraries. - violating_resource (google.cloud.websecurityscanner_v1beta.types.ViolatingResource): - An addon containing detailed information - regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, - etc. - vulnerable_headers (google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders): - An addon containing information about - vulnerable or missing HTTP headers. - vulnerable_parameters (google.cloud.websecurityscanner_v1beta.types.VulnerableParameters): - An addon containing information about request - parameters which were found to be vulnerable. - xss (google.cloud.websecurityscanner_v1beta.types.Xss): - An addon containing information reported for - an XSS, if any. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - finding_type: str = proto.Field( - proto.STRING, - number=2, - ) - http_method: str = proto.Field( - proto.STRING, - number=3, - ) - fuzzed_url: str = proto.Field( - proto.STRING, - number=4, - ) - body: str = proto.Field( - proto.STRING, - number=5, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - reproduction_url: str = proto.Field( - proto.STRING, - number=7, - ) - frame_url: str = proto.Field( - proto.STRING, - number=8, - ) - final_url: str = proto.Field( - proto.STRING, - number=9, - ) - tracking_id: str = proto.Field( - proto.STRING, - number=10, - ) - form: finding_addon.Form = proto.Field( - proto.MESSAGE, - number=16, - message=finding_addon.Form, - ) - outdated_library: finding_addon.OutdatedLibrary = proto.Field( - proto.MESSAGE, - number=11, - message=finding_addon.OutdatedLibrary, - ) - violating_resource: finding_addon.ViolatingResource = proto.Field( - proto.MESSAGE, - number=12, - message=finding_addon.ViolatingResource, - ) - vulnerable_headers: finding_addon.VulnerableHeaders = proto.Field( - proto.MESSAGE, - number=15, - message=finding_addon.VulnerableHeaders, - ) - vulnerable_parameters: finding_addon.VulnerableParameters = proto.Field( - proto.MESSAGE, - number=13, - message=finding_addon.VulnerableParameters, - ) - xss: finding_addon.Xss = proto.Field( - proto.MESSAGE, - number=14, - message=finding_addon.Xss, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py deleted file mode 100644 index 43f2fac68a72..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableParameters', - 'VulnerableHeaders', - 'Xss', - }, -) - - -class Form(proto.Message): - r"""! Information about a vulnerability with an HTML. - - Attributes: - action_uri (str): - ! The URI where to send the form when it's - submitted. - fields (MutableSequence[str]): - ! The names of form fields related to the - vulnerability. - """ - - action_uri: str = proto.Field( - proto.STRING, - number=1, - ) - fields: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class OutdatedLibrary(proto.Message): - r"""Information reported for an outdated library. - - Attributes: - library_name (str): - The name of the outdated library. - version (str): - The version number. - learn_more_urls (MutableSequence[str]): - URLs to learn more information about the - vulnerabilities in the library. - """ - - library_name: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - learn_more_urls: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ViolatingResource(proto.Message): - r"""Information regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, etc. - - Attributes: - content_type (str): - The MIME type of this resource. - resource_url (str): - URL of this violating resource. - """ - - content_type: str = proto.Field( - proto.STRING, - number=1, - ) - resource_url: str = proto.Field( - proto.STRING, - number=2, - ) - - -class VulnerableParameters(proto.Message): - r"""Information about vulnerable request parameters. - - Attributes: - parameter_names (MutableSequence[str]): - The vulnerable parameter names. - """ - - parameter_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class VulnerableHeaders(proto.Message): - r"""Information about vulnerable or missing HTTP Headers. - - Attributes: - headers (MutableSequence[google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders.Header]): - List of vulnerable headers. - missing_headers (MutableSequence[google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders.Header]): - List of missing headers. - """ - - class Header(proto.Message): - r"""Describes a HTTP Header. - - Attributes: - name (str): - Header name. - value (str): - Header value. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - - headers: MutableSequence[Header] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Header, - ) - missing_headers: MutableSequence[Header] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Header, - ) - - -class Xss(proto.Message): - r"""Information reported for an XSS. - - Attributes: - stack_traces (MutableSequence[str]): - Stack traces leading to the point where the - XSS occurred. - error_message (str): - An error message generated by a javascript - breakage. - """ - - stack_traces: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - error_message: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py deleted file mode 100644 index 23166655b9b3..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'FindingTypeStats', - }, -) - - -class FindingTypeStats(proto.Message): - r"""A FindingTypeStats resource represents stats regarding a - specific FindingType of Findings under a given ScanRun. - - Attributes: - finding_type (str): - The finding type associated with the stats. - finding_count (int): - The count of findings belonging to this - finding type. - """ - - finding_type: str = proto.Field( - proto.STRING, - number=1, - ) - finding_count: int = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py deleted file mode 100644 index 8ce53ebfbd04..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py +++ /dev/null @@ -1,319 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner_v1beta.types import scan_run -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanConfig', - }, -) - - -class ScanConfig(proto.Message): - r"""A ScanConfig resource contains the configurations to launch a - scan. - - Attributes: - name (str): - The resource name of the ScanConfig. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - The ScanConfig IDs are generated by the system. - display_name (str): - Required. The user provided display name of - the ScanConfig. - max_qps (int): - The maximum QPS during scanning. A valid value ranges from 5 - to 20 inclusively. If the field is unspecified or its value - is set 0, server will default to 15. Other values outside of - [5, 20] range will be rejected with INVALID_ARGUMENT error. - starting_urls (MutableSequence[str]): - Required. The starting URLs from which the - scanner finds site pages. - authentication (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication): - The authentication configuration. If - specified, service will use the authentication - configuration during scanning. - user_agent (google.cloud.websecurityscanner_v1beta.types.ScanConfig.UserAgent): - The user agent used during scanning. - blacklist_patterns (MutableSequence[str]): - The blacklist URL patterns as described in - https://cloud.google.com/security-scanner/docs/excluded-urls - schedule (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Schedule): - The schedule of the ScanConfig. - target_platforms (MutableSequence[google.cloud.websecurityscanner_v1beta.types.ScanConfig.TargetPlatform]): - Set of Cloud Platforms targeted by the scan. If empty, - APP_ENGINE will be used as a default. - export_to_security_command_center (google.cloud.websecurityscanner_v1beta.types.ScanConfig.ExportToSecurityCommandCenter): - Controls export of scan configurations and - results to Cloud Security Command Center. - latest_run (google.cloud.websecurityscanner_v1beta.types.ScanRun): - Latest ScanRun if available. - risk_level (google.cloud.websecurityscanner_v1beta.types.ScanConfig.RiskLevel): - The risk level selected for the scan - """ - class UserAgent(proto.Enum): - r"""Type of user agents used for scanning. - - Values: - USER_AGENT_UNSPECIFIED (0): - The user agent is unknown. Service will default to - CHROME_LINUX. - CHROME_LINUX (1): - Chrome on Linux. This is the service default - if unspecified. - CHROME_ANDROID (2): - Chrome on Android. - SAFARI_IPHONE (3): - Safari on IPhone. - """ - USER_AGENT_UNSPECIFIED = 0 - CHROME_LINUX = 1 - CHROME_ANDROID = 2 - SAFARI_IPHONE = 3 - - class TargetPlatform(proto.Enum): - r"""Cloud platforms supported by Cloud Web Security Scanner. - - Values: - TARGET_PLATFORM_UNSPECIFIED (0): - The target platform is unknown. Requests with this enum - value will be rejected with INVALID_ARGUMENT error. - APP_ENGINE (1): - Google App Engine service. - COMPUTE (2): - Google Compute Engine service. - """ - TARGET_PLATFORM_UNSPECIFIED = 0 - APP_ENGINE = 1 - COMPUTE = 2 - - class RiskLevel(proto.Enum): - r"""Scan risk levels supported by Cloud Web Security Scanner. LOW - impact scanning will minimize requests with the potential to - modify data. To achieve the maximum scan coverage, NORMAL risk - level is recommended. - - Values: - RISK_LEVEL_UNSPECIFIED (0): - Use default, which is NORMAL. - NORMAL (1): - Normal scanning (Recommended) - LOW (2): - Lower impact scanning - """ - RISK_LEVEL_UNSPECIFIED = 0 - NORMAL = 1 - LOW = 2 - - class ExportToSecurityCommandCenter(proto.Enum): - r"""Controls export of scan configurations and results to Cloud - Security Command Center. - - Values: - EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED (0): - Use default, which is ENABLED. - ENABLED (1): - Export results of this scan to Cloud Security - Command Center. - DISABLED (2): - Do not export results of this scan to Cloud - Security Command Center. - """ - EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - - class Authentication(proto.Message): - r"""Scan authentication configuration. - - 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_account (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication.GoogleAccount): - Authentication using a Google account. - - This field is a member of `oneof`_ ``authentication``. - custom_account (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication.CustomAccount): - Authentication using a custom account. - - This field is a member of `oneof`_ ``authentication``. - """ - - class GoogleAccount(proto.Message): - r"""Describes authentication configuration that uses a Google - account. - - Attributes: - username (str): - Required. The user name of the Google - account. - password (str): - Required. Input only. The password of the - Google account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - password: str = proto.Field( - proto.STRING, - number=2, - ) - - class CustomAccount(proto.Message): - r"""Describes authentication configuration that uses a custom - account. - - Attributes: - username (str): - Required. The user name of the custom - account. - password (str): - Required. Input only. The password of the - custom account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - login_url (str): - Required. The login form URL of the website. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - password: str = proto.Field( - proto.STRING, - number=2, - ) - login_url: str = proto.Field( - proto.STRING, - number=3, - ) - - google_account: 'ScanConfig.Authentication.GoogleAccount' = proto.Field( - proto.MESSAGE, - number=1, - oneof='authentication', - message='ScanConfig.Authentication.GoogleAccount', - ) - custom_account: 'ScanConfig.Authentication.CustomAccount' = proto.Field( - proto.MESSAGE, - number=2, - oneof='authentication', - message='ScanConfig.Authentication.CustomAccount', - ) - - class Schedule(proto.Message): - r"""Scan schedule configuration. - - Attributes: - schedule_time (google.protobuf.timestamp_pb2.Timestamp): - A timestamp indicates when the next run will - be scheduled. The value is refreshed by the - server after each run. If unspecified, it will - default to current server time, which means the - scan will be scheduled to start immediately. - interval_duration_days (int): - Required. The duration of time between - executions in days. - """ - - schedule_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - interval_duration_days: int = proto.Field( - proto.INT32, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - max_qps: int = proto.Field( - proto.INT32, - number=3, - ) - starting_urls: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - authentication: Authentication = proto.Field( - proto.MESSAGE, - number=5, - message=Authentication, - ) - user_agent: UserAgent = proto.Field( - proto.ENUM, - number=6, - enum=UserAgent, - ) - blacklist_patterns: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - schedule: Schedule = proto.Field( - proto.MESSAGE, - number=8, - message=Schedule, - ) - target_platforms: MutableSequence[TargetPlatform] = proto.RepeatedField( - proto.ENUM, - number=9, - enum=TargetPlatform, - ) - export_to_security_command_center: ExportToSecurityCommandCenter = proto.Field( - proto.ENUM, - number=10, - enum=ExportToSecurityCommandCenter, - ) - latest_run: scan_run.ScanRun = proto.Field( - proto.MESSAGE, - number=11, - message=scan_run.ScanRun, - ) - risk_level: RiskLevel = proto.Field( - proto.ENUM, - number=12, - enum=RiskLevel, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py deleted file mode 100644 index 9e301d626790..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanConfigError', - }, -) - - -class ScanConfigError(proto.Message): - r"""Defines a custom error message used by CreateScanConfig and - UpdateScanConfig APIs when scan configuration validation fails. - It is also reported as part of a ScanRunErrorTrace message if - scan validation fails due to a scan configuration error. - - Attributes: - code (google.cloud.websecurityscanner_v1beta.types.ScanConfigError.Code): - Indicates the reason code for a configuration - failure. - field_name (str): - Indicates the full name of the ScanConfig field that - triggers this error, for example "scan_config.max_qps". This - field is provided for troubleshooting purposes only and its - actual value can change in the future. - """ - class Code(proto.Enum): - r"""Output only. - Defines an error reason code. - Next id: 44 - - Values: - CODE_UNSPECIFIED (0): - There is no error. - OK (0): - There is no error. - INTERNAL_ERROR (1): - Indicates an internal server error. - Please DO NOT USE THIS ERROR CODE unless the - root cause is truly unknown. - APPENGINE_API_BACKEND_ERROR (2): - One of the seed URLs is an App Engine URL but - we cannot validate the scan settings due to an - App Engine API backend error. - APPENGINE_API_NOT_ACCESSIBLE (3): - One of the seed URLs is an App Engine URL but - we cannot access the App Engine API to validate - scan settings. - APPENGINE_DEFAULT_HOST_MISSING (4): - One of the seed URLs is an App Engine URL but - the Default Host of the App Engine is not set. - CANNOT_USE_GOOGLE_COM_ACCOUNT (6): - Google corporate accounts can not be used for - scanning. - CANNOT_USE_OWNER_ACCOUNT (7): - The account of the scan creator can not be - used for scanning. - COMPUTE_API_BACKEND_ERROR (8): - This scan targets Compute Engine, but we - cannot validate scan settings due to a Compute - Engine API backend error. - COMPUTE_API_NOT_ACCESSIBLE (9): - This scan targets Compute Engine, but we - cannot access the Compute Engine API to validate - the scan settings. - CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT (10): - The Custom Login URL does not belong to the - current project. - CUSTOM_LOGIN_URL_MALFORMED (11): - The Custom Login URL is malformed (can not be - parsed). - CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS (12): - The Custom Login URL is mapped to a - non-routable IP address in DNS. - CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS (13): - The Custom Login URL is mapped to an IP - address which is not reserved for the current - project. - CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS (14): - The Custom Login URL has a non-routable IP - address. - CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS (15): - The Custom Login URL has an IP address which - is not reserved for the current project. - DUPLICATE_SCAN_NAME (16): - Another scan with the same name - (case-sensitive) already exists. - INVALID_FIELD_VALUE (18): - A field is set to an invalid value. - FAILED_TO_AUTHENTICATE_TO_TARGET (19): - There was an error trying to authenticate to - the scan target. - FINDING_TYPE_UNSPECIFIED (20): - Finding type value is not specified in the - list findings request. - FORBIDDEN_TO_SCAN_COMPUTE (21): - Scan targets Compute Engine, yet current - project was not whitelisted for Google Compute - Engine Scanning Alpha access. - FORBIDDEN_UPDATE_TO_MANAGED_SCAN (43): - User tries to update managed scan - MALFORMED_FILTER (22): - The supplied filter is malformed. For - example, it can not be parsed, does not have a - filter type in expression, or the same filter - type appears more than once. - MALFORMED_RESOURCE_NAME (23): - The supplied resource name is malformed (can - not be parsed). - PROJECT_INACTIVE (24): - The current project is not in an active - state. - REQUIRED_FIELD (25): - A required field is not set. - RESOURCE_NAME_INCONSISTENT (26): - Project id, scanconfig id, scanrun id, or - finding id are not consistent with each other in - resource name. - SCAN_ALREADY_RUNNING (27): - The scan being requested to start is already - running. - SCAN_NOT_RUNNING (28): - The scan that was requested to be stopped is - not running. - SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT (29): - One of the seed URLs does not belong to the - current project. - SEED_URL_MALFORMED (30): - One of the seed URLs is malformed (can not be - parsed). - SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS (31): - One of the seed URLs is mapped to a - non-routable IP address in DNS. - SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS (32): - One of the seed URLs is mapped to an IP - address which is not reserved for the current - project. - SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS (33): - One of the seed URLs has on-routable IP - address. - SEED_URL_HAS_UNRESERVED_IP_ADDRESS (35): - One of the seed URLs has an IP address that - is not reserved for the current project. - SERVICE_ACCOUNT_NOT_CONFIGURED (36): - The Cloud Security Scanner service account is - not configured under the project. - TOO_MANY_SCANS (37): - A project has reached the maximum number of - scans. - UNABLE_TO_RESOLVE_PROJECT_INFO (38): - Resolving the details of the current project - fails. - UNSUPPORTED_BLACKLIST_PATTERN_FORMAT (39): - One or more blacklist patterns were in the - wrong format. - UNSUPPORTED_FILTER (40): - The supplied filter is not supported. - UNSUPPORTED_FINDING_TYPE (41): - The supplied finding type is not supported. - For example, we do not provide findings of the - given finding type. - UNSUPPORTED_URL_SCHEME (42): - The URL scheme of one or more of the supplied - URLs is not supported. - """ - _pb_options = {'allow_alias': True} - CODE_UNSPECIFIED = 0 - OK = 0 - INTERNAL_ERROR = 1 - APPENGINE_API_BACKEND_ERROR = 2 - APPENGINE_API_NOT_ACCESSIBLE = 3 - APPENGINE_DEFAULT_HOST_MISSING = 4 - CANNOT_USE_GOOGLE_COM_ACCOUNT = 6 - CANNOT_USE_OWNER_ACCOUNT = 7 - COMPUTE_API_BACKEND_ERROR = 8 - COMPUTE_API_NOT_ACCESSIBLE = 9 - CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 10 - CUSTOM_LOGIN_URL_MALFORMED = 11 - CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 12 - CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS = 13 - CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 14 - CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS = 15 - DUPLICATE_SCAN_NAME = 16 - INVALID_FIELD_VALUE = 18 - FAILED_TO_AUTHENTICATE_TO_TARGET = 19 - FINDING_TYPE_UNSPECIFIED = 20 - FORBIDDEN_TO_SCAN_COMPUTE = 21 - FORBIDDEN_UPDATE_TO_MANAGED_SCAN = 43 - MALFORMED_FILTER = 22 - MALFORMED_RESOURCE_NAME = 23 - PROJECT_INACTIVE = 24 - REQUIRED_FIELD = 25 - RESOURCE_NAME_INCONSISTENT = 26 - SCAN_ALREADY_RUNNING = 27 - SCAN_NOT_RUNNING = 28 - SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 29 - SEED_URL_MALFORMED = 30 - SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 31 - SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS = 32 - SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 33 - SEED_URL_HAS_UNRESERVED_IP_ADDRESS = 35 - SERVICE_ACCOUNT_NOT_CONFIGURED = 36 - TOO_MANY_SCANS = 37 - UNABLE_TO_RESOLVE_PROJECT_INFO = 38 - UNSUPPORTED_BLACKLIST_PATTERN_FORMAT = 39 - UNSUPPORTED_FILTER = 40 - UNSUPPORTED_FINDING_TYPE = 41 - UNSUPPORTED_URL_SCHEME = 42 - - code: Code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - field_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py deleted file mode 100644 index 0afd6f989f90..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py +++ /dev/null @@ -1,178 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner_v1beta.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanRun', - }, -) - - -class ScanRun(proto.Message): - r"""A ScanRun is a output-only resource representing an actual - run of the scan. Next id: 12 - - Attributes: - name (str): - The resource name of the ScanRun. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - The ScanRun IDs are generated by the system. - execution_state (google.cloud.websecurityscanner_v1beta.types.ScanRun.ExecutionState): - The execution state of the ScanRun. - result_state (google.cloud.websecurityscanner_v1beta.types.ScanRun.ResultState): - The result state of the ScanRun. This field - is only available after the execution state - reaches "FINISHED". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the ScanRun started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the ScanRun reached - termination state - that the ScanRun is either - finished or stopped by user. - urls_crawled_count (int): - The number of URLs crawled during this - ScanRun. If the scan is in progress, the value - represents the number of URLs crawled up to now. - urls_tested_count (int): - The number of URLs tested during this - ScanRun. If the scan is in progress, the value - represents the number of URLs tested up to now. - The number of URLs tested is usually larger than - the number URLS crawled because typically a - crawled URL is tested with multiple test - payloads. - has_vulnerabilities (bool): - Whether the scan run has found any - vulnerabilities. - progress_percent (int): - The percentage of total completion ranging - from 0 to 100. If the scan is in queue, the - value is 0. If the scan is running, the value - ranges from 0 to 100. If the scan is finished, - the value is 100. - error_trace (google.cloud.websecurityscanner_v1beta.types.ScanRunErrorTrace): - If result_state is an ERROR, this field provides the primary - reason for scan's termination and more details, if such are - available. - warning_traces (MutableSequence[google.cloud.websecurityscanner_v1beta.types.ScanRunWarningTrace]): - A list of warnings, if such are encountered - during this scan run. - """ - class ExecutionState(proto.Enum): - r"""Types of ScanRun execution state. - - Values: - EXECUTION_STATE_UNSPECIFIED (0): - Represents an invalid state caused by - internal server error. This value should never - be returned. - QUEUED (1): - The scan is waiting in the queue. - SCANNING (2): - The scan is in progress. - FINISHED (3): - The scan is either finished or stopped by - user. - """ - EXECUTION_STATE_UNSPECIFIED = 0 - QUEUED = 1 - SCANNING = 2 - FINISHED = 3 - - class ResultState(proto.Enum): - r"""Types of ScanRun result state. - - Values: - RESULT_STATE_UNSPECIFIED (0): - Default value. This value is returned when - the ScanRun is not yet finished. - SUCCESS (1): - The scan finished without errors. - ERROR (2): - The scan finished with errors. - KILLED (3): - The scan was terminated by user. - """ - RESULT_STATE_UNSPECIFIED = 0 - SUCCESS = 1 - ERROR = 2 - KILLED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - execution_state: ExecutionState = proto.Field( - proto.ENUM, - number=2, - enum=ExecutionState, - ) - result_state: ResultState = proto.Field( - proto.ENUM, - number=3, - enum=ResultState, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - urls_crawled_count: int = proto.Field( - proto.INT64, - number=6, - ) - urls_tested_count: int = proto.Field( - proto.INT64, - number=7, - ) - has_vulnerabilities: bool = proto.Field( - proto.BOOL, - number=8, - ) - progress_percent: int = proto.Field( - proto.INT32, - number=9, - ) - error_trace: scan_run_error_trace.ScanRunErrorTrace = proto.Field( - proto.MESSAGE, - number=10, - message=scan_run_error_trace.ScanRunErrorTrace, - ) - warning_traces: MutableSequence[scan_run_warning_trace.ScanRunWarningTrace] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=scan_run_warning_trace.ScanRunWarningTrace, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py deleted file mode 100644 index 97e6976dec77..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py +++ /dev/null @@ -1,106 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner_v1beta.types import scan_config_error as gcw_scan_config_error - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanRunErrorTrace', - }, -) - - -class ScanRunErrorTrace(proto.Message): - r"""Output only. - Defines an error trace message for a ScanRun. - - Attributes: - code (google.cloud.websecurityscanner_v1beta.types.ScanRunErrorTrace.Code): - Indicates the error reason code. - scan_config_error (google.cloud.websecurityscanner_v1beta.types.ScanConfigError): - If the scan encounters SCAN_CONFIG_ISSUE error, this field - has the error message encountered during scan configuration - validation that is performed before each scan run. - most_common_http_error_code (int): - If the scan encounters TOO_MANY_HTTP_ERRORS, this field - indicates the most common HTTP error code, if such is - available. For example, if this code is 404, the scan has - encountered too many NOT_FOUND responses. - """ - class Code(proto.Enum): - r"""Output only. - Defines an error reason code. - Next id: 7 - - Values: - CODE_UNSPECIFIED (0): - Default value is never used. - INTERNAL_ERROR (1): - Indicates that the scan run failed due to an - internal server error. - SCAN_CONFIG_ISSUE (2): - Indicates a scan configuration error, usually due to - outdated ScanConfig settings, such as starting_urls or the - DNS configuration. - AUTHENTICATION_CONFIG_ISSUE (3): - Indicates an authentication error, usually - due to outdated ScanConfig authentication - settings. - TIMED_OUT_WHILE_SCANNING (4): - Indicates a scan operation timeout, usually - caused by a very large site. - TOO_MANY_REDIRECTS (5): - Indicates that a scan encountered excessive - redirects, either to authentication or some - other page outside of the scan scope. - TOO_MANY_HTTP_ERRORS (6): - Indicates that a scan encountered numerous errors from the - web site pages. When available, most_common_http_error_code - field indicates the most common HTTP error code encountered - during the scan. - """ - CODE_UNSPECIFIED = 0 - INTERNAL_ERROR = 1 - SCAN_CONFIG_ISSUE = 2 - AUTHENTICATION_CONFIG_ISSUE = 3 - TIMED_OUT_WHILE_SCANNING = 4 - TOO_MANY_REDIRECTS = 5 - TOO_MANY_HTTP_ERRORS = 6 - - code: Code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - scan_config_error: gcw_scan_config_error.ScanConfigError = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config_error.ScanConfigError, - ) - most_common_http_error_code: int = proto.Field( - proto.INT32, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py deleted file mode 100644 index c603b733380e..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py +++ /dev/null @@ -1,79 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanRunWarningTrace', - }, -) - - -class ScanRunWarningTrace(proto.Message): - r"""Output only. - Defines a warning trace message for ScanRun. Warning traces - provide customers with useful information that helps make the - scanning process more effective. - - Attributes: - code (google.cloud.websecurityscanner_v1beta.types.ScanRunWarningTrace.Code): - Indicates the warning code. - """ - class Code(proto.Enum): - r"""Output only. - Defines a warning message code. - Next id: 6 - - Values: - CODE_UNSPECIFIED (0): - Default value is never used. - INSUFFICIENT_CRAWL_RESULTS (1): - Indicates that a scan discovered an - unexpectedly low number of URLs. This is - sometimes caused by complex navigation features - or by using a single URL for numerous pages. - TOO_MANY_CRAWL_RESULTS (2): - Indicates that a scan discovered too many - URLs to test, or excessive redundant URLs. - TOO_MANY_FUZZ_TASKS (3): - Indicates that too many tests have been - generated for the scan. Customer should try - reducing the number of starting URLs, increasing - the QPS rate, or narrowing down the scope of the - scan using the excluded patterns. - BLOCKED_BY_IAP (4): - Indicates that a scan is blocked by IAP. - """ - CODE_UNSPECIFIED = 0 - INSUFFICIENT_CRAWL_RESULTS = 1 - TOO_MANY_CRAWL_RESULTS = 2 - TOO_MANY_FUZZ_TASKS = 3 - BLOCKED_BY_IAP = 4 - - code: Code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py deleted file mode 100644 index 4a19eeb9d038..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import finding_type_stats as gcw_finding_type_stats -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetScanConfigRequest', - 'ListScanConfigsRequest', - 'UpdateScanConfigRequest', - 'ListScanConfigsResponse', - 'StartScanRunRequest', - 'GetScanRunRequest', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StopScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'GetFindingRequest', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - }, -) - - -class CreateScanConfigRequest(proto.Message): - r"""Request for the ``CreateScanConfig`` method. - - Attributes: - parent (str): - Required. The parent resource name where the - scan is created, which should be a project - resource name in the format - 'projects/{projectId}'. - scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): - Required. The ScanConfig to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - scan_config: gcw_scan_config.ScanConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - - -class DeleteScanConfigRequest(proto.Message): - r"""Request for the ``DeleteScanConfig`` method. - - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be deleted. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanConfigRequest(proto.Message): - r"""Request for the ``GetScanConfig`` method. - - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanConfigsRequest(proto.Message): - r"""Request for the ``ListScanConfigs`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a project resource name in the format - 'projects/{projectId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanConfigs to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class UpdateScanConfigRequest(proto.Message): - r"""Request for the ``UpdateScanConfigRequest`` method. - - Attributes: - scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): - Required. The ScanConfig to be updated. The - name field must be set to identify the resource - to be updated. The values of fields not covered - by the mask will be ignored. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For the - ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - """ - - scan_config: gcw_scan_config.ScanConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ListScanConfigsResponse(proto.Message): - r"""Response for the ``ListScanConfigs`` method. - - Attributes: - scan_configs (MutableSequence[google.cloud.websecurityscanner_v1beta.types.ScanConfig]): - The list of ScanConfigs returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_configs: MutableSequence[gcw_scan_config.ScanConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_scan_config.ScanConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class StartScanRunRequest(proto.Message): - r"""Request for the ``StartScanRun`` method. - - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be used. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanRunRequest(proto.Message): - r"""Request for the ``GetScanRun`` method. - - Attributes: - name (str): - Required. The resource name of the ScanRun to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanRunsRequest(proto.Message): - r"""Request for the ``ListScanRuns`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanRuns to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListScanRunsResponse(proto.Message): - r"""Response for the ``ListScanRuns`` method. - - Attributes: - scan_runs (MutableSequence[google.cloud.websecurityscanner_v1beta.types.ScanRun]): - The list of ScanRuns returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_runs: MutableSequence[scan_run.ScanRun] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=scan_run.ScanRun, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class StopScanRunRequest(proto.Message): - r"""Request for the ``StopScanRun`` method. - - Attributes: - name (str): - Required. The resource name of the ScanRun to - be stopped. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListCrawledUrlsRequest(proto.Message): - r"""Request for the ``ListCrawledUrls`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of CrawledUrls to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCrawledUrlsResponse(proto.Message): - r"""Response for the ``ListCrawledUrls`` method. - - Attributes: - crawled_urls (MutableSequence[google.cloud.websecurityscanner_v1beta.types.CrawledUrl]): - The list of CrawledUrls returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - crawled_urls: MutableSequence[crawled_url.CrawledUrl] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=crawled_url.CrawledUrl, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFindingRequest(proto.Message): - r"""Request for the ``GetFinding`` method. - - Attributes: - name (str): - Required. The resource name of the Finding to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request for the ``ListFindings`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - filter (str): - Required. The filter expression. The expression must be in - the format: . Supported field: 'finding_type'. Supported - operator: '='. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of Findings to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response for the ``ListFindings`` method. - - Attributes: - findings (MutableSequence[google.cloud.websecurityscanner_v1beta.types.Finding]): - The list of Findings returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - findings: MutableSequence[finding.Finding] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=finding.Finding, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListFindingTypeStatsRequest(proto.Message): - r"""Request for the ``ListFindingTypeStats`` method. - - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingTypeStatsResponse(proto.Message): - r"""Response for the ``ListFindingTypeStats`` method. - - Attributes: - finding_type_stats (MutableSequence[google.cloud.websecurityscanner_v1beta.types.FindingTypeStats]): - The list of FindingTypeStats returned. - """ - - finding_type_stats: MutableSequence[gcw_finding_type_stats.FindingTypeStats] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_finding_type_stats.FindingTypeStats, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/mypy.ini b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/noxfile.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/noxfile.py deleted file mode 100644 index 71f9c4528104..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner' - -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/cloud/websecurityscanner_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/cloud/websecurityscanner_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-cloud-websecurityscanner/v1beta/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json deleted file mode 100644 index 3896b1676525..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json +++ /dev/null @@ -1,2126 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.websecurityscanner.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-cloud-websecurityscanner", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.create_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.CreateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "CreateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "scan_config", - "type": "google.cloud.websecurityscanner_v1beta.types.ScanConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", - "shortName": "create_scan_config" - }, - "description": "Sample for CreateScanConfig", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.create_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.CreateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "CreateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "scan_config", - "type": "google.cloud.websecurityscanner_v1beta.types.ScanConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", - "shortName": "create_scan_config" - }, - "description": "Sample for CreateScanConfig", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.delete_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.DeleteScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "DeleteScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_scan_config" - }, - "description": "Sample for DeleteScanConfig", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.delete_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.DeleteScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "DeleteScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_scan_config" - }, - "description": "Sample for DeleteScanConfig", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.get_finding", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetFinding", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.GetFindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.Finding", - "shortName": "get_finding" - }, - "description": "Sample for GetFinding", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.get_finding", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetFinding", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.GetFindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.Finding", - "shortName": "get_finding" - }, - "description": "Sample for GetFinding", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.get_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", - "shortName": "get_scan_config" - }, - "description": "Sample for GetScanConfig", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.get_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", - "shortName": "get_scan_config" - }, - "description": "Sample for GetScanConfig", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.get_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", - "shortName": "get_scan_run" - }, - "description": "Sample for GetScanRun", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.get_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.GetScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "GetScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", - "shortName": "get_scan_run" - }, - "description": "Sample for GetScanRun", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_crawled_urls", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListCrawledUrls", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListCrawledUrls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager", - "shortName": "list_crawled_urls" - }, - "description": "Sample for ListCrawledUrls", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_crawled_urls", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListCrawledUrls", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListCrawledUrls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsPager", - "shortName": "list_crawled_urls" - }, - "description": "Sample for ListCrawledUrls", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_finding_type_stats", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListFindingTypeStats", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindingTypeStats" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse", - "shortName": "list_finding_type_stats" - }, - "description": "Sample for ListFindingTypeStats", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_finding_type_stats", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListFindingTypeStats", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindingTypeStats" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse", - "shortName": "list_finding_type_stats" - }, - "description": "Sample for ListFindingTypeStats", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListFindings", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest" - }, - { - "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, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_findings", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListFindings", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest" - }, - { - "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, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_scan_configs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListScanConfigs", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsAsyncPager", - "shortName": "list_scan_configs" - }, - "description": "Sample for ListScanConfigs", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_scan_configs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListScanConfigs", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsPager", - "shortName": "list_scan_configs" - }, - "description": "Sample for ListScanConfigs", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.list_scan_runs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListScanRuns", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanRuns" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsAsyncPager", - "shortName": "list_scan_runs" - }, - "description": "Sample for ListScanRuns", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.list_scan_runs", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.ListScanRuns", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "ListScanRuns" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsPager", - "shortName": "list_scan_runs" - }, - "description": "Sample for ListScanRuns", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_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": "websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.start_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.StartScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StartScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", - "shortName": "start_scan_run" - }, - "description": "Sample for StartScanRun", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.start_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.StartScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StartScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", - "shortName": "start_scan_run" - }, - "description": "Sample for StartScanRun", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.stop_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.StopScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StopScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", - "shortName": "stop_scan_run" - }, - "description": "Sample for StopScanRun", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.stop_scan_run", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.StopScanRun", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "StopScanRun" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanRun", - "shortName": "stop_scan_run" - }, - "description": "Sample for StopScanRun", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_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": "websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient", - "shortName": "WebSecurityScannerAsyncClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerAsyncClient.update_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.UpdateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "UpdateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest" - }, - { - "name": "scan_config", - "type": "google.cloud.websecurityscanner_v1beta.types.ScanConfig" - }, - { - "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, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", - "shortName": "update_scan_config" - }, - "description": "Sample for UpdateScanConfig", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient", - "shortName": "WebSecurityScannerClient" - }, - "fullName": "google.cloud.websecurityscanner_v1beta.WebSecurityScannerClient.update_scan_config", - "method": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner.UpdateScanConfig", - "service": { - "fullName": "google.cloud.websecurityscanner.v1beta.WebSecurityScanner", - "shortName": "WebSecurityScanner" - }, - "shortName": "UpdateScanConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest" - }, - { - "name": "scan_config", - "type": "google.cloud.websecurityscanner_v1beta.types.ScanConfig" - }, - { - "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, str]" - } - ], - "resultType": "google.cloud.websecurityscanner_v1beta.types.ScanConfig", - "shortName": "update_scan_config" - }, - "description": "Sample for UpdateScanConfig", - "file": "websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_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": "websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_async.py deleted file mode 100644 index b69fdbd77cdf..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_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 CreateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1beta.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1beta.CreateScanConfigRequest( - parent="parent_value", - scan_config=scan_config, - ) - - # Make the request - response = await client.create_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_sync.py deleted file mode 100644 index 6fe99be4457b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_create_scan_config_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 CreateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_create_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1beta.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1beta.CreateScanConfigRequest( - parent="parent_value", - scan_config=scan_config, - ) - - # Make the request - response = client.create_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_CreateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_async.py deleted file mode 100644 index 844e1b3a81cc..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_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 DeleteScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.DeleteScanConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_scan_config(request=request) - - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_sync.py deleted file mode 100644 index 41f63690845d..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_delete_scan_config_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 DeleteScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_delete_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.DeleteScanConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_scan_config(request=request) - - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_DeleteScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_async.py deleted file mode 100644 index 196cfe27ed50..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_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 GetFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_get_finding(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetFindingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_finding(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py deleted file mode 100644 index bfa360711c75..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_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 GetFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_get_finding(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetFindingRequest( - name="name_value", - ) - - # Make the request - response = client.get_finding(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_async.py deleted file mode 100644 index e49ee7d4fab3..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_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 GetScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetScanConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_sync.py deleted file mode 100644 index 29677cd1be18..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_config_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 GetScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_get_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetScanConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_async.py deleted file mode 100644 index 0f798e6cd152..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_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 GetScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.get_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_sync.py deleted file mode 100644 index 5fbb1c0e5989..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_scan_run_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 GetScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_get_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.GetScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.get_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_async.py deleted file mode 100644 index fa6e68fd9ba6..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListCrawledUrlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_sync.py deleted file mode 100644 index 3c159200f640..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_crawled_urls_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 ListCrawledUrls -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_list_crawled_urls(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListCrawledUrlsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crawled_urls(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListCrawledUrls_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_async.py deleted file mode 100644 index 11826a1426ca..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListFindingTypeStatsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_sync.py deleted file mode 100644 index 619e67e6b80b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_finding_type_stats_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 ListFindingTypeStats -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_list_finding_type_stats(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListFindingTypeStatsRequest( - parent="parent_value", - ) - - # Make the request - response = client.list_finding_type_stats(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindingTypeStats_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_async.py deleted file mode 100644 index e6500adb0ce4..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_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 ListFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_list_findings(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListFindingsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_sync.py deleted file mode 100644 index f28ebd0c35d2..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_findings_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 ListFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_list_findings(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListFindingsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_async.py deleted file mode 100644 index c556ee10a2fc..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListScanConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_sync.py deleted file mode 100644 index 85b6f5e9b731..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_configs_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 ListScanConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_list_scan_configs(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListScanConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanConfigs_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_async.py deleted file mode 100644 index 48091d8d1bbf..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_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 ListScanRuns -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListScanRunsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_sync.py deleted file mode 100644 index 2667ce75f2bb..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_list_scan_runs_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 ListScanRuns -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_list_scan_runs(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.ListScanRunsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_scan_runs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_ListScanRuns_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_async.py deleted file mode 100644 index b8a6de14516c..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_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 StartScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.StartScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.start_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_sync.py deleted file mode 100644 index b60a0d5c70bf..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_start_scan_run_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 StartScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_start_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.StartScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.start_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_StartScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_async.py deleted file mode 100644 index f4a6d65e2f61..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_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 StopScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.StopScanRunRequest( - name="name_value", - ) - - # Make the request - response = await client.stop_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_sync.py deleted file mode 100644 index 63a1f9e5f899..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_stop_scan_run_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 StopScanRun -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_stop_scan_run(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - request = websecurityscanner_v1beta.StopScanRunRequest( - name="name_value", - ) - - # Make the request - response = client.stop_scan_run(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_StopScanRun_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_async.py deleted file mode 100644 index 3829aeb7f538..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -async def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerAsyncClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1beta.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1beta.UpdateScanConfigRequest( - scan_config=scan_config, - ) - - # Make the request - response = await client.update_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_async] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_sync.py deleted file mode 100644 index 42579467412b..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_update_scan_config_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 UpdateScanConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-websecurityscanner - - -# [START websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import websecurityscanner_v1beta - - -def sample_update_scan_config(): - # Create a client - client = websecurityscanner_v1beta.WebSecurityScannerClient() - - # Initialize request argument(s) - scan_config = websecurityscanner_v1beta.ScanConfig() - scan_config.display_name = "display_name_value" - scan_config.starting_urls = ['starting_urls_value1', 'starting_urls_value2'] - - request = websecurityscanner_v1beta.UpdateScanConfigRequest( - scan_config=scan_config, - ) - - # Make the request - response = client.update_scan_config(request=request) - - # Handle the response - print(response) - -# [END websecurityscanner_v1beta_generated_WebSecurityScanner_UpdateScanConfig_sync] diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py deleted file mode 100644 index cbe5261ddc2a..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py +++ /dev/null @@ -1,188 +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 websecurityscannerCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_scan_config': ('parent', 'scan_config', ), - 'delete_scan_config': ('name', ), - 'get_finding': ('name', ), - 'get_scan_config': ('name', ), - 'get_scan_run': ('name', ), - 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_finding_type_stats': ('parent', ), - 'list_scan_configs': ('parent', 'page_token', 'page_size', ), - 'list_scan_runs': ('parent', 'page_token', 'page_size', ), - 'start_scan_run': ('name', ), - 'stop_scan_run': ('name', ), - 'update_scan_config': ('scan_config', '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=websecurityscannerCallTransformer(), -): - """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 websecurityscanner 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-cloud-websecurityscanner/v1beta/setup.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/setup.py deleted file mode 100644 index b89eea40fd8f..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner' - - -description = "Google Cloud Websecurityscanner API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/websecurityscanner/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-cloud-websecurityscanner" - -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-cloud-websecurityscanner/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/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-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_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-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py b/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py deleted file mode 100644 index 8e3982546372..000000000000 --- a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py +++ /dev/null @@ -1,11533 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.websecurityscanner_v1beta.services.web_security_scanner import WebSecurityScannerAsyncClient -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import transports -from google.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import finding_addon -from google.cloud.websecurityscanner_v1beta.types import finding_type_stats -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config_error -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_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 WebSecurityScannerClient._get_default_mtls_endpoint(None) is None - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert WebSecurityScannerClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - WebSecurityScannerClient._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 WebSecurityScannerClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert WebSecurityScannerClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert WebSecurityScannerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - WebSecurityScannerClient._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 WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, False) is None - assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert WebSecurityScannerClient._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 WebSecurityScannerClient._get_client_cert_source(None, True) is mock_default_cert_source - assert WebSecurityScannerClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE - default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert WebSecurityScannerClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - assert WebSecurityScannerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - assert WebSecurityScannerClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert WebSecurityScannerClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - WebSecurityScannerClient._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 WebSecurityScannerClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert WebSecurityScannerClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert WebSecurityScannerClient._get_universe_domain(None, None) == WebSecurityScannerClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - WebSecurityScannerClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (WebSecurityScannerClient, "grpc"), - (WebSecurityScannerAsyncClient, "grpc_asyncio"), - (WebSecurityScannerClient, "rest"), -]) -def test_web_security_scanner_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 == ( - 'websecurityscanner.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://websecurityscanner.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WebSecurityScannerGrpcTransport, "grpc"), - (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.WebSecurityScannerRestTransport, "rest"), -]) -def test_web_security_scanner_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", [ - (WebSecurityScannerClient, "grpc"), - (WebSecurityScannerAsyncClient, "grpc_asyncio"), - (WebSecurityScannerClient, "rest"), -]) -def test_web_security_scanner_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 == ( - 'websecurityscanner.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://websecurityscanner.googleapis.com' - ) - - -def test_web_security_scanner_client_get_transport_class(): - transport = WebSecurityScannerClient.get_transport_class() - available_transports = [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerRestTransport, - ] - assert transport in available_transports - - transport = WebSecurityScannerClient.get_transport_class("grpc") - assert transport == transports.WebSecurityScannerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), -]) -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_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(WebSecurityScannerClient, '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(WebSecurityScannerClient, '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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "true"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", "false"), -]) -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_web_security_scanner_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", [ - WebSecurityScannerClient, WebSecurityScannerAsyncClient -]) -@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_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", [ - WebSecurityScannerClient, WebSecurityScannerAsyncClient -]) -@mock.patch.object(WebSecurityScannerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = WebSecurityScannerClient._DEFAULT_UNIVERSE - default_endpoint = WebSecurityScannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WebSecurityScannerClient._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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), -]) -def test_web_security_scanner_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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest", None), -]) -def test_web_security_scanner_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_web_security_scanner_client_client_options_from_dict(): - with mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WebSecurityScannerClient( - 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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", grpc_helpers), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_web_security_scanner_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( - "websecurityscanner.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="websecurityscanner.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.CreateScanConfigRequest, - dict, -]) -def test_create_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - ) - response = client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.CreateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -def test_create_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.CreateScanConfigRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.CreateScanConfigRequest( - parent='parent_value', - ) - -def test_create_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - request = {} - client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - )) - response = await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.CreateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -@pytest.mark.asyncio -async def test_create_scan_config_async_from_dict(): - await test_create_scan_config_async(request_type=dict) - -def test_create_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_scan_config( - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(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].scan_config - mock_val = gcw_scan_config.ScanConfig(name='name_value') - assert arg == mock_val - - -def test_create_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_scan_config( - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(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].scan_config - mock_val = gcw_scan_config.ScanConfig(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.DeleteScanConfigRequest, - dict, -]) -def test_delete_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.DeleteScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.DeleteScanConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.DeleteScanConfigRequest( - name='name_value', - ) - -def test_delete_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - request = {} - client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.DeleteScanConfigRequest() - 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_scan_config_async_from_dict(): - await test_delete_scan_config_async(request_type=dict) - -def test_delete_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = None - client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__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_scan_config( - 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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__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_scan_config( - 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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanConfigRequest, - dict, -]) -def test_get_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - ) - response = client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - - -def test_get_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.GetScanConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanConfigRequest( - name='name_value', - ) - -def test_get_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc - request = {} - client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - )) - response = await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - - -@pytest.mark.asyncio -async def test_get_scan_config_async_from_dict(): - await test_get_scan_config_async(request_type=dict) - -def test_get_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_scan_config( - 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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_scan_config( - 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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanConfigsRequest, - dict, -]) -def test_list_scan_configs(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_configs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListScanConfigsRequest( - 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_scan_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_scan_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_scan_configs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_configs] = mock_rpc - request = {} - client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_configs(request) - - # Establish that a new wrapper 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_scan_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_configs in client._client._transport._wrapped_methods - - # 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_scan_configs] = mock_rpc - - request = {} - await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_scan_configs(request) - - # Establish that a new wrapper 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_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_configs_async_from_dict(): - await test_list_scan_configs_async(request_type=dict) - -def test_list_scan_configs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanConfigsResponse() - client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_configs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_configs_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_scan_configs( - 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_scan_configs_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_scan_configs_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_scan_configs( - 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_scan_configs_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - - -def test_list_scan_configs_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_configs(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, scan_config.ScanConfig) - for i in results) -def test_list_scan_configs_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_configs(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_scan_configs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_configs(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, scan_config.ScanConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_scan_configs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - 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_scan_configs(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", [ - web_security_scanner.UpdateScanConfigRequest, - dict, -]) -def test_update_scan_config(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - ) - response = client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.UpdateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -def test_update_scan_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.UpdateScanConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_scan_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.UpdateScanConfigRequest( - ) - -def test_update_scan_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - request = {} - client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_config in client._client._transport._wrapped_methods - - # 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_scan_config] = mock_rpc - - request = {} - await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_scan_config(request) - - # Establish that a new wrapper 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_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - )) - response = await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.UpdateScanConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -@pytest.mark.asyncio -async def test_update_scan_config_async_from_dict(): - await test_update_scan_config_async(request_type=dict) - -def test_update_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'scan_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'scan_config.name=name_value', - ) in kw['metadata'] - - -def test_update_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_scan_config( - scan_config=gcw_scan_config.ScanConfig(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].scan_config - mock_val = gcw_scan_config.ScanConfig(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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_scan_config( - scan_config=gcw_scan_config.ScanConfig(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].scan_config - mock_val = gcw_scan_config.ScanConfig(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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.StartScanRunRequest, - dict, -]) -def test_start_scan_run(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StartScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_start_scan_run_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.StartScanRunRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.start_scan_run(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest( - name='name_value', - ) - -def test_start_scan_run_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc - request = {} - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.start_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.start_scan_run in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.start_scan_run] = mock_rpc - - request = {} - await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.start_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StartScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_start_scan_run_async_from_dict(): - await test_start_scan_run_async(request_type=dict) - -def test_start_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.start_scan_run( - 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_start_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_start_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.start_scan_run( - 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_start_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanRunRequest, - dict, -]) -def test_get_scan_run(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_get_scan_run_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.GetScanRunRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_scan_run(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest( - name='name_value', - ) - -def test_get_scan_run_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc - request = {} - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_run(request) - - # Establish that a new wrapper 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_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_run in client._client._transport._wrapped_methods - - # 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_scan_run] = mock_rpc - - request = {} - await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_scan_run(request) - - # Establish that a new wrapper 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_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_get_scan_run_async_from_dict(): - await test_get_scan_run_async(request_type=dict) - -def test_get_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_scan_run( - 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_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_scan_run( - 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_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanRunsRequest, - dict, -]) -def test_list_scan_runs(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanRunsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_runs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListScanRunsRequest( - 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_scan_runs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_scan_runs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_scan_runs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_scan_runs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_runs] = mock_rpc - request = {} - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_runs(request) - - # Establish that a new wrapper 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_scan_runs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_scan_runs in client._client._transport._wrapped_methods - - # 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_scan_runs] = mock_rpc - - request = {} - await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_scan_runs(request) - - # Establish that a new wrapper 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_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListScanRunsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_runs_async_from_dict(): - await test_list_scan_runs_async(request_type=dict) - -def test_list_scan_runs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanRunsResponse() - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_runs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_scan_runs_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_scan_runs( - 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_scan_runs_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_scan_runs_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_scan_runs( - 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_scan_runs_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - - -def test_list_scan_runs_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_runs(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, scan_run.ScanRun) - for i in results) -def test_list_scan_runs_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_runs(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_scan_runs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_runs(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, scan_run.ScanRun) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_scan_runs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - 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_scan_runs(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", [ - web_security_scanner.StopScanRunRequest, - dict, -]) -def test_stop_scan_run(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StopScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_stop_scan_run_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.StopScanRunRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.stop_scan_run(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest( - name='name_value', - ) - -def test_stop_scan_run_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc - request = {} - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_scan_run_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.stop_scan_run in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.stop_scan_run] = mock_rpc - - request = {} - await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.stop_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.StopScanRunRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_stop_scan_run_async_from_dict(): - await test_stop_scan_run_async(request_type=dict) - -def test_stop_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.stop_scan_run( - 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_stop_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_stop_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.stop_scan_run( - 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_stop_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListCrawledUrlsRequest, - dict, -]) -def test_list_crawled_urls(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListCrawledUrlsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_crawled_urls_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListCrawledUrlsRequest( - 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_crawled_urls), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_crawled_urls(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_crawled_urls_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_crawled_urls in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_crawled_urls] = mock_rpc - request = {} - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crawled_urls(request) - - # Establish that a new wrapper 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_crawled_urls_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_crawled_urls in client._client._transport._wrapped_methods - - # 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_crawled_urls] = mock_rpc - - request = {} - await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_crawled_urls(request) - - # Establish that a new wrapper 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_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListCrawledUrlsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_from_dict(): - await test_list_crawled_urls_async(request_type=dict) - -def test_list_crawled_urls_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crawled_urls_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crawled_urls_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_crawled_urls( - 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_crawled_urls_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_crawled_urls_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_crawled_urls( - 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_crawled_urls_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - - -def test_list_crawled_urls_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crawled_urls(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, crawled_url.CrawledUrl) - for i in results) -def test_list_crawled_urls_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - 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_crawled_urls(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", [ - web_security_scanner.GetFindingRequest, - dict, -]) -def test_get_finding(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - finding_type='finding_type_value', - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - ) - response = client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -def test_get_finding_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.GetFindingRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetFindingRequest( - name='name_value', - ) - -def test_get_finding_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_finding in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc - request = {} - client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_finding(request) - - # Establish that a new wrapper 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_finding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # 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_finding] = mock_rpc - - request = {} - await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_finding(request) - - # Establish that a new wrapper 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_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - finding_type='finding_type_value', - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - )) - response = await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.GetFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -@pytest.mark.asyncio -async def test_get_finding_async_from_dict(): - await test_get_finding_async(request_type=dict) - -def test_get_finding_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = finding.Finding() - client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_finding( - 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_finding_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_finding_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_finding( - 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_finding_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_findings_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListFindingsRequest( - 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_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_findings_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_findings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_findings] = mock_rpc - request = {} - client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_findings(request) - - # Establish that a new wrapper 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_findings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_findings in client._client._transport._wrapped_methods - - # 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_findings] = mock_rpc - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_findings(request) - - # Establish that a new wrapper 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_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_findings_async_from_dict(): - await test_list_findings_async(request_type=dict) - -def test_list_findings_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingsResponse() - client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_findings_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_findings_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_findings( - 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_findings_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - -@pytest.mark.asyncio -async def test_list_findings_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_findings( - 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_findings_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_findings_pager(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_findings(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, finding.Finding) - for i in results) -def test_list_findings_pages(transport_name: str = "grpc"): - client = WebSecurityScannerClient( - 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_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - pages = list(client.list_findings(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_findings_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_findings(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, finding.Finding) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - 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_findings(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", [ - web_security_scanner.ListFindingTypeStatsRequest, - dict, -]) -def test_list_finding_type_stats(request_type, transport: str = 'grpc'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse( - ) - response = client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingTypeStatsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -def test_list_finding_type_stats_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = web_security_scanner.ListFindingTypeStatsRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_finding_type_stats(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest( - parent='parent_value', - ) - -def test_list_finding_type_stats_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_finding_type_stats in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_finding_type_stats] = mock_rpc - request = {} - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_finding_type_stats(request) - - # Establish that a new wrapper 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_finding_type_stats_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_finding_type_stats in client._client._transport._wrapped_methods - - # 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_finding_type_stats] = mock_rpc - - request = {} - await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_finding_type_stats(request) - - # Establish that a new wrapper 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_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( - )) - response = await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = web_security_scanner.ListFindingTypeStatsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_async_from_dict(): - await test_list_finding_type_stats_async(request_type=dict) - -def test_list_finding_type_stats_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_type_stats_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_finding_type_stats_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_finding_type_stats( - 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_finding_type_stats_flattened_error(): - client = WebSecurityScannerClient( - credentials=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_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_finding_type_stats_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_finding_type_stats( - 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_finding_type_stats_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=async_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_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - - -def test_create_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - - request = {} - client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_scan_config(request) - - # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.CreateScanConfigRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_scan_config._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_scan_config._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcw_scan_config.ScanConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_scan_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_scan_config_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_scan_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "scanConfig", ))) - - -def test_create_scan_config_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcw_scan_config.ScanConfig() - - # 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', - scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_scan_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*}/scanConfigs" % client.transport._host, args[1]) - - -def test_create_scan_config_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - - -def test_delete_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - - request = {} - client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_scan_config(request) - - # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.DeleteScanConfigRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_scan_config._get_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_scan_config._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - 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 - - response = client.delete_scan_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_scan_config_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_scan_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_scan_config_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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/scanConfigs/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 - - client.delete_scan_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_scan_config_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - - -def test_get_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_config] = mock_rpc - - request = {} - client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_config(request) - - # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.GetScanConfigRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_scan_config._get_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_scan_config._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = scan_config.ScanConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_scan_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_scan_config_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_scan_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_scan_config_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = scan_config.ScanConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_scan_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) - - -def test_get_scan_config_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - - -def test_list_scan_configs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_configs] = mock_rpc - - request = {} - client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_configs(request) - - # Establish 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_scan_configs_rest_required_fields(request_type=web_security_scanner.ListScanConfigsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_scan_configs._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_scan_configs._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListScanConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_scan_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_scan_configs_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_scan_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_scan_configs_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListScanConfigsResponse() - - # 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_scan_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*}/scanConfigs" % client.transport._host, args[1]) - - -def test_list_scan_configs_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - - -def test_list_scan_configs_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListScanConfigsResponse.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_scan_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, scan_config.ScanConfig) - for i in results) - - pages = list(client.list_scan_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_scan_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_config] = mock_rpc - - request = {} - client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_scan_config(request) - - # Establish 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_scan_config_rest_required_fields(request_type=web_security_scanner.UpdateScanConfigRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_scan_config._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_scan_config._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcw_scan_config.ScanConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_scan_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_scan_config_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_scan_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("scanConfig", "updateMask", ))) - - -def test_update_scan_config_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcw_scan_config.ScanConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_scan_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{scan_config.name=projects/*/scanConfigs/*}" % client.transport._host, args[1]) - - -def test_update_scan_config_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_start_scan_run_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_scan_run] = mock_rpc - - request = {} - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.start_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_start_scan_run_rest_required_fields(request_type=web_security_scanner.StartScanRunRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).start_scan_run._get_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()).start_scan_run._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.start_scan_run(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_start_scan_run_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.start_scan_run._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_start_scan_run_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.start_scan_run(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*}:start" % client.transport._host, args[1]) - - -def test_start_scan_run_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - - -def test_get_scan_run_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_scan_run] = mock_rpc - - request = {} - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_scan_run(request) - - # Establish 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_scan_run_rest_required_fields(request_type=web_security_scanner.GetScanRunRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_scan_run._get_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_scan_run._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_scan_run(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_scan_run_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_scan_run._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_scan_run_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_scan_run(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}" % client.transport._host, args[1]) - - -def test_get_scan_run_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - - -def test_list_scan_runs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_scan_runs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_scan_runs] = mock_rpc - - request = {} - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_scan_runs(request) - - # Establish 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_scan_runs_rest_required_fields(request_type=web_security_scanner.ListScanRunsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_scan_runs._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_scan_runs._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListScanRunsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_scan_runs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_scan_runs_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_scan_runs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_scan_runs_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListScanRunsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_scan_runs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/scanConfigs/*}/scanRuns" % client.transport._host, args[1]) - - -def test_list_scan_runs_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - - -def test_list_scan_runs_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListScanRunsResponse.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/scanConfigs/sample2'} - - pager = client.list_scan_runs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, scan_run.ScanRun) - for i in results) - - pages = list(client.list_scan_runs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_stop_scan_run_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_scan_run in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_scan_run] = mock_rpc - - request = {} - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_scan_run(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_stop_scan_run_rest_required_fields(request_type=web_security_scanner.StopScanRunRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).stop_scan_run._get_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()).stop_scan_run._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.stop_scan_run(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_stop_scan_run_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.stop_scan_run._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_stop_scan_run_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = scan_run.ScanRun() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.stop_scan_run(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}:stop" % client.transport._host, args[1]) - - -def test_stop_scan_run_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - - -def test_list_crawled_urls_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_crawled_urls in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_crawled_urls] = mock_rpc - - request = {} - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crawled_urls(request) - - # Establish 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_crawled_urls_rest_required_fields(request_type=web_security_scanner.ListCrawledUrlsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_crawled_urls._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_crawled_urls._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListCrawledUrlsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_crawled_urls(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_crawled_urls_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_crawled_urls._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_crawled_urls_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListCrawledUrlsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} - - # 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_crawled_urls(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls" % client.transport._host, args[1]) - - -def test_list_crawled_urls_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - - -def test_list_crawled_urls_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListCrawledUrlsResponse.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/scanConfigs/sample2/scanRuns/sample3'} - - pager = client.list_crawled_urls(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, crawled_url.CrawledUrl) - for i in results) - - pages = list(client.list_crawled_urls(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_finding_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_finding in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_finding] = mock_rpc - - request = {} - client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_finding(request) - - # Establish 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_finding_rest_required_fields(request_type=web_security_scanner.GetFindingRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_finding._get_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_finding._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = finding.Finding() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = finding.Finding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_finding_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_finding_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} - - # 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 = finding.Finding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_finding(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}" % client.transport._host, args[1]) - - -def test_get_finding_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - - -def test_list_findings_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_findings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_findings] = mock_rpc - - request = {} - client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_findings(request) - - # Establish 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_findings_rest_required_fields(request_type=web_security_scanner.ListFindingsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["filter"] = "" - request = request_type(**request_init) - pb_request = request_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 "filter" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "filter" in jsonified_request - assert jsonified_request["filter"] == request_init["filter"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["filter"] = 'filter_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_findings._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' - assert "filter" in jsonified_request - assert jsonified_request["filter"] == 'filter_value' - - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_findings(request) - - expected_params = [ - ( - "filter", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_findings_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", "filter", ))) - - -def test_list_findings_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} - - # 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 = web_security_scanner.ListFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_findings(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings" % client.transport._host, args[1]) - - -def test_list_findings_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = WebSecurityScannerClient( - 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 = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(web_security_scanner.ListFindingsResponse.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/scanConfigs/sample2/scanRuns/sample3'} - - pager = client.list_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, finding.Finding) - for i in results) - - pages = list(client.list_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_finding_type_stats_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_finding_type_stats in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_finding_type_stats] = mock_rpc - - request = {} - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_finding_type_stats(request) - - # Establish 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_finding_type_stats_rest_required_fields(request_type=web_security_scanner.ListFindingTypeStatsRequest): - transport_class = transports.WebSecurityScannerRestTransport - - 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_finding_type_stats._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_finding_type_stats._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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListFindingTypeStatsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_finding_type_stats(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_finding_type_stats_rest_unset_required_fields(): - transport = transports.WebSecurityScannerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_finding_type_stats._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -def test_list_finding_type_stats_rest_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = web_security_scanner.ListFindingTypeStatsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3'} - - # 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 = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_finding_type_stats(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats" % client.transport._host, args[1]) - - -def test_list_finding_type_stats_rest_flattened_error(transport: str = 'rest'): - client = WebSecurityScannerClient( - credentials=ga_credentials.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_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - 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 = WebSecurityScannerClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WebSecurityScannerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - transports.WebSecurityScannerRestTransport, -]) -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 = WebSecurityScannerClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = WebSecurityScannerClient( - 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.create_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.CreateScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = None - client.delete_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.DeleteScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.get_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_configs_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanConfigsResponse() - client.list_scan_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanConfigsRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.update_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.UpdateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_scan_run_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.start_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StartScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_run_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.get_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_runs_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanRunsResponse() - client.list_scan_runs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanRunsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_scan_run_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.stop_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StopScanRunRequest() - - assert args[0] == request_msg - - -# This 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_crawled_urls_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - client.list_crawled_urls(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListCrawledUrlsRequest() - - assert args[0] == request_msg - - -# This 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_finding_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = finding.Finding() - client.get_finding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetFindingRequest() - - assert args[0] == request_msg - - -# This 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_findings_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingsResponse() - client.list_findings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingsRequest() - - assert args[0] == request_msg - - -# This 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_finding_type_stats_empty_call_grpc(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - client.list_finding_type_stats(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingTypeStatsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = WebSecurityScannerAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - )) - await client.create_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.CreateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.DeleteScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - )) - await client.get_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_configs_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - )) - await client.list_scan_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_config_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - )) - await client.update_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.UpdateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_start_scan_run_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - await client.start_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StartScanRunRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_run_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - await client.get_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanRunRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_scan_runs_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - )) - await client.list_scan_runs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanRunsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_stop_scan_run_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - await client.stop_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StopScanRunRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_crawled_urls_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - )) - await client.list_crawled_urls(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListCrawledUrlsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_finding_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - finding_type='finding_type_value', - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - )) - await client.get_finding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetFindingRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_findings_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - )) - await client.list_findings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_finding_type_stats_empty_call_grpc_asyncio(): - client = WebSecurityScannerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( - )) - await client.list_finding_type_stats(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingTypeStatsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = WebSecurityScannerClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_scan_config_rest_bad_request(request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerClient( - 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 - client.create_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.CreateScanConfigRequest, - dict, -]) -def test_create_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["scan_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'target_platforms': [1], 'export_to_security_command_center': 1, 'latest_run': {'name': 'name_value', 'execution_state': 1, 'result_state': 1, 'start_time': {}, 'end_time': {}, 'urls_crawled_count': 1935, 'urls_tested_count': 1846, 'has_vulnerabilities': True, 'progress_percent': 1733, 'error_trace': {'code': 1, 'scan_config_error': {'code': 1, 'field_name': 'field_name_value'}, 'most_common_http_error_code': 2893}, 'warning_traces': [{'code': 1}]}, 'risk_level': 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 = web_security_scanner.CreateScanConfigRequest.meta.fields["scan_config"] - - 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["scan_config"].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["scan_config"][field])): - del request_init["scan_config"][field][i][subfield] - else: - del request_init["scan_config"][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 = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_scan_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_create_scan_config") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_create_scan_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.CreateScanConfigRequest.pb(web_security_scanner.CreateScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = gcw_scan_config.ScanConfig.to_json(gcw_scan_config.ScanConfig()) - req.return_value.content = return_value - - request = web_security_scanner.CreateScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcw_scan_config.ScanConfig() - - client.create_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_scan_config_rest_bad_request(request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - client.delete_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.DeleteScanConfigRequest, - dict, -]) -def test_delete_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - response = client.delete_scan_config(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_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_delete_scan_config") as pre: - pre.assert_not_called() - pb_message = web_security_scanner.DeleteScanConfigRequest.pb(web_security_scanner.DeleteScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - - request = web_security_scanner.DeleteScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_get_scan_config_rest_bad_request(request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - client.get_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanConfigRequest, - dict, -]) -def test_get_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_scan_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_config") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.GetScanConfigRequest.pb(web_security_scanner.GetScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_config.ScanConfig.to_json(scan_config.ScanConfig()) - req.return_value.content = return_value - - request = web_security_scanner.GetScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_config.ScanConfig() - - client.get_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_scan_configs_rest_bad_request(request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerClient( - 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 - client.list_scan_configs(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanConfigsRequest, - dict, -]) -def test_list_scan_configs_rest_call_success(request_type): - client = WebSecurityScannerClient( - 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 = web_security_scanner.ListScanConfigsResponse( - 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 = web_security_scanner.ListScanConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_scan_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_scan_configs_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_configs") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListScanConfigsRequest.pb(web_security_scanner.ListScanConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListScanConfigsResponse.to_json(web_security_scanner.ListScanConfigsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListScanConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListScanConfigsResponse() - - client.list_scan_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_scan_config_rest_bad_request(request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/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 - client.update_scan_config(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.UpdateScanConfigRequest, - dict, -]) -def test_update_scan_config_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'scan_config': {'name': 'projects/sample1/scanConfigs/sample2'}} - request_init["scan_config"] = {'name': 'projects/sample1/scanConfigs/sample2', 'display_name': 'display_name_value', 'max_qps': 761, 'starting_urls': ['starting_urls_value1', 'starting_urls_value2'], 'authentication': {'google_account': {'username': 'username_value', 'password': 'password_value'}, 'custom_account': {'username': 'username_value', 'password': 'password_value', 'login_url': 'login_url_value'}}, 'user_agent': 1, 'blacklist_patterns': ['blacklist_patterns_value1', 'blacklist_patterns_value2'], 'schedule': {'schedule_time': {'seconds': 751, 'nanos': 543}, 'interval_duration_days': 2362}, 'target_platforms': [1], 'export_to_security_command_center': 1, 'latest_run': {'name': 'name_value', 'execution_state': 1, 'result_state': 1, 'start_time': {}, 'end_time': {}, 'urls_crawled_count': 1935, 'urls_tested_count': 1846, 'has_vulnerabilities': True, 'progress_percent': 1733, 'error_trace': {'code': 1, 'scan_config_error': {'code': 1, 'field_name': 'field_name_value'}, 'most_common_http_error_code': 2893}, 'warning_traces': [{'code': 1}]}, 'risk_level': 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 = web_security_scanner.UpdateScanConfigRequest.meta.fields["scan_config"] - - 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["scan_config"].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["scan_config"][field])): - del request_init["scan_config"][field][i][subfield] - else: - del request_init["scan_config"][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 = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcw_scan_config.ScanConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_scan_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_scan_config_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_update_scan_config") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_update_scan_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.UpdateScanConfigRequest.pb(web_security_scanner.UpdateScanConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = gcw_scan_config.ScanConfig.to_json(gcw_scan_config.ScanConfig()) - req.return_value.content = return_value - - request = web_security_scanner.UpdateScanConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcw_scan_config.ScanConfig() - - client.update_scan_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_start_scan_run_rest_bad_request(request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 - client.start_scan_run(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.StartScanRunRequest, - dict, -]) -def test_start_scan_run_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/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 = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.start_scan_run(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_start_scan_run_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_start_scan_run") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_start_scan_run") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.StartScanRunRequest.pb(web_security_scanner.StartScanRunRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) - req.return_value.content = return_value - - request = web_security_scanner.StartScanRunRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_run.ScanRun() - - client.start_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_scan_run_rest_bad_request(request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.get_scan_run(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetScanRunRequest, - dict, -]) -def test_get_scan_run_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_scan_run(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_scan_run_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_scan_run") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_scan_run") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.GetScanRunRequest.pb(web_security_scanner.GetScanRunRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) - req.return_value.content = return_value - - request = web_security_scanner.GetScanRunRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_run.ScanRun() - - client.get_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_scan_runs_rest_bad_request(request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/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 - client.list_scan_runs(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListScanRunsRequest, - dict, -]) -def test_list_scan_runs_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse( - 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 = web_security_scanner.ListScanRunsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_scan_runs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_scan_runs_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_scan_runs") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_scan_runs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListScanRunsRequest.pb(web_security_scanner.ListScanRunsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListScanRunsResponse.to_json(web_security_scanner.ListScanRunsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListScanRunsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListScanRunsResponse() - - client.list_scan_runs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_stop_scan_run_rest_bad_request(request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.stop_scan_run(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.StopScanRunRequest, - dict, -]) -def test_stop_scan_run_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = scan_run.ScanRun.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.stop_scan_run(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_stop_scan_run_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_stop_scan_run") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_stop_scan_run") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.StopScanRunRequest.pb(web_security_scanner.StopScanRunRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = scan_run.ScanRun.to_json(scan_run.ScanRun()) - req.return_value.content = return_value - - request = web_security_scanner.StopScanRunRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = scan_run.ScanRun() - - client.stop_scan_run(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_crawled_urls_rest_bad_request(request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.list_crawled_urls(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListCrawledUrlsRequest, - dict, -]) -def test_list_crawled_urls_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListCrawledUrlsResponse( - 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 = web_security_scanner.ListCrawledUrlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_crawled_urls(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_crawled_urls_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_crawled_urls") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_crawled_urls") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListCrawledUrlsRequest.pb(web_security_scanner.ListCrawledUrlsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListCrawledUrlsResponse.to_json(web_security_scanner.ListCrawledUrlsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListCrawledUrlsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListCrawledUrlsResponse() - - client.list_crawled_urls(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_finding_rest_bad_request(request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_finding(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.GetFindingRequest, - dict, -]) -def test_get_finding_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = finding.Finding( - name='name_value', - finding_type='finding_type_value', - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = finding.Finding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_finding_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_get_finding") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_get_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.GetFindingRequest.pb(web_security_scanner.GetFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = finding.Finding.to_json(finding.Finding()) - req.return_value.content = return_value - - request = web_security_scanner.GetFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.get_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.list_findings(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListFindingsRequest, - dict, -]) -def test_list_findings_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingsResponse( - 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 = web_security_scanner.ListFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListFindingsRequest.pb(web_security_scanner.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListFindingsResponse.to_json(web_security_scanner.ListFindingsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_finding_type_stats_rest_bad_request(request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 - client.list_finding_type_stats(request) - - -@pytest.mark.parametrize("request_type", [ - web_security_scanner.ListFindingTypeStatsRequest, - dict, -]) -def test_list_finding_type_stats_rest_call_success(request_type): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingTypeStatsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = web_security_scanner.ListFindingTypeStatsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_finding_type_stats(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_finding_type_stats_rest_interceptors(null_interceptor): - transport = transports.WebSecurityScannerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WebSecurityScannerRestInterceptor(), - ) - client = WebSecurityScannerClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "post_list_finding_type_stats") as post, \ - mock.patch.object(transports.WebSecurityScannerRestInterceptor, "pre_list_finding_type_stats") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = web_security_scanner.ListFindingTypeStatsRequest.pb(web_security_scanner.ListFindingTypeStatsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = web_security_scanner.ListFindingTypeStatsResponse.to_json(web_security_scanner.ListFindingTypeStatsResponse()) - req.return_value.content = return_value - - request = web_security_scanner.ListFindingTypeStatsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = web_security_scanner.ListFindingTypeStatsResponse() - - client.list_finding_type_stats(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = WebSecurityScannerClient( - 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - client.create_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.CreateScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - client.delete_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.DeleteScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - client.get_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanConfigRequest() - - assert args[0] == request_msg - - -# This 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_scan_configs_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - client.list_scan_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanConfigsRequest() - - assert args[0] == request_msg - - -# This 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_scan_config_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - client.update_scan_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.UpdateScanConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_scan_run_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - client.start_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StartScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_run_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - client.get_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetScanRunRequest() - - assert args[0] == request_msg - - -# This 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_scan_runs_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - client.list_scan_runs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListScanRunsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_scan_run_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - client.stop_scan_run(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.StopScanRunRequest() - - assert args[0] == request_msg - - -# This 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_crawled_urls_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - client.list_crawled_urls(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListCrawledUrlsRequest() - - assert args[0] == request_msg - - -# This 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_finding_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - client.get_finding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.GetFindingRequest() - - assert args[0] == request_msg - - -# This 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_findings_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - client.list_findings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingsRequest() - - assert args[0] == request_msg - - -# This 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_finding_type_stats_empty_call_rest(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - client.list_finding_type_stats(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = web_security_scanner.ListFindingTypeStatsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WebSecurityScannerGrpcTransport, - ) - -def test_web_security_scanner_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_web_security_scanner_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_scan_config', - 'delete_scan_config', - 'get_scan_config', - 'list_scan_configs', - 'update_scan_config', - 'start_scan_run', - 'get_scan_run', - 'list_scan_runs', - 'stop_scan_run', - 'list_crawled_urls', - 'get_finding', - 'list_findings', - 'list_finding_type_stats', - ) - 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_web_security_scanner_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - 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_web_security_scanner_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport() - adc.assert_called_once() - - -def test_web_security_scanner_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) - WebSecurityScannerClient() - 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.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - transports.WebSecurityScannerRestTransport, - ], -) -def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, grpc_helpers), - (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_web_security_scanner_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( - "websecurityscanner.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="websecurityscanner.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_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_web_security_scanner_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.WebSecurityScannerRestTransport ( - 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_web_security_scanner_host_no_port(transport_name): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'websecurityscanner.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://websecurityscanner.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_web_security_scanner_host_with_port(transport_name): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'websecurityscanner.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://websecurityscanner.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_web_security_scanner_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = WebSecurityScannerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = WebSecurityScannerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_scan_config._session - session2 = client2.transport.create_scan_config._session - assert session1 != session2 - session1 = client1.transport.delete_scan_config._session - session2 = client2.transport.delete_scan_config._session - assert session1 != session2 - session1 = client1.transport.get_scan_config._session - session2 = client2.transport.get_scan_config._session - assert session1 != session2 - session1 = client1.transport.list_scan_configs._session - session2 = client2.transport.list_scan_configs._session - assert session1 != session2 - session1 = client1.transport.update_scan_config._session - session2 = client2.transport.update_scan_config._session - assert session1 != session2 - session1 = client1.transport.start_scan_run._session - session2 = client2.transport.start_scan_run._session - assert session1 != session2 - session1 = client1.transport.get_scan_run._session - session2 = client2.transport.get_scan_run._session - assert session1 != session2 - session1 = client1.transport.list_scan_runs._session - session2 = client2.transport.list_scan_runs._session - assert session1 != session2 - session1 = client1.transport.stop_scan_run._session - session2 = client2.transport.stop_scan_run._session - assert session1 != session2 - session1 = client1.transport.list_crawled_urls._session - session2 = client2.transport.list_crawled_urls._session - assert session1 != session2 - session1 = client1.transport.get_finding._session - session2 = client2.transport.get_finding._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_finding_type_stats._session - session2 = client2.transport.list_finding_type_stats._session - assert session1 != session2 -def test_web_security_scanner_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcTransport( - 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_web_security_scanner_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - 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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_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.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_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_finding_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - finding = "octopus" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "project": "oyster", - "scan_config": "nudibranch", - "scan_run": "cuttlefish", - "finding": "mussel", - } - path = WebSecurityScannerClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_finding_path(path) - assert expected == actual - -def test_scan_config_path(): - project = "winkle" - scan_config = "nautilus" - expected = "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) - actual = WebSecurityScannerClient.scan_config_path(project, scan_config) - assert expected == actual - - -def test_parse_scan_config_path(): - expected = { - "project": "scallop", - "scan_config": "abalone", - } - path = WebSecurityScannerClient.scan_config_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_scan_config_path(path) - assert expected == actual - -def test_scan_run_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) - actual = WebSecurityScannerClient.scan_run_path(project, scan_config, scan_run) - assert expected == actual - - -def test_parse_scan_run_path(): - expected = { - "project": "octopus", - "scan_config": "oyster", - "scan_run": "nudibranch", - } - path = WebSecurityScannerClient.scan_run_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_scan_run_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WebSecurityScannerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = WebSecurityScannerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = WebSecurityScannerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = WebSecurityScannerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WebSecurityScannerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = WebSecurityScannerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = WebSecurityScannerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = WebSecurityScannerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.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 = WebSecurityScannerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = WebSecurityScannerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.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.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - transport_class = WebSecurityScannerClient.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 = WebSecurityScannerClient( - 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 = WebSecurityScannerAsyncClient( - 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 = WebSecurityScannerClient( - 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 = WebSecurityScannerClient( - 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", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport), -]) -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-cloud-workflows/v1/.coveragerc b/owl-bot-staging/google-cloud-workflows/v1/.coveragerc deleted file mode 100644 index 0b3eb91ee6c6..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/workflows/__init__.py - google/cloud/workflows/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-cloud-workflows/v1/.flake8 b/owl-bot-staging/google-cloud-workflows/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/MANIFEST.in b/owl-bot-staging/google-cloud-workflows/v1/MANIFEST.in deleted file mode 100644 index 73e61ee8a1fe..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/workflows *.py -recursive-include google/cloud/workflows_v1 *.py diff --git a/owl-bot-staging/google-cloud-workflows/v1/README.rst b/owl-bot-staging/google-cloud-workflows/v1/README.rst deleted file mode 100644 index 9ff50ef51f9e..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Workflows 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 Cloud Workflows 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-cloud-workflows/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-workflows/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/docs/conf.py b/owl-bot-staging/google-cloud-workflows/v1/docs/conf.py deleted file mode 100644 index aa65085dd2d2..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows 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-cloud-workflows" -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 Cloud 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-cloud-workflows-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-cloud-workflows.tex", - u"google-cloud-workflows 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-cloud-workflows", - u"Google Cloud Workflows 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-cloud-workflows", - u"google-cloud-workflows Documentation", - author, - "google-cloud-workflows", - "GAPIC library for Google Cloud Workflows 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-cloud-workflows/v1/docs/executions_v1/executions.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/executions.rst deleted file mode 100644 index 4bae72f3fd23..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/executions.rst +++ /dev/null @@ -1,10 +0,0 @@ -Executions ----------------------------- - -.. automodule:: google.cloud.workflows.executions_v1.services.executions - :members: - :inherited-members: - -.. automodule:: google.cloud.workflows.executions_v1.services.executions.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/services_.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/services_.rst deleted file mode 100644 index bc1bbaa59487..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Workflows Executions v1 API -===================================================== -.. toctree:: - :maxdepth: 2 - - executions diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/types_.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/types_.rst deleted file mode 100644 index e17d766321ac..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/docs/executions_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Workflows Executions v1 API -================================================== - -.. automodule:: google.cloud.workflows.executions_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/index.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/index.rst deleted file mode 100644 index 88b2eb9495a5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - workflows_v1/services_ - workflows_v1/types_ diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/services_.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/services_.rst deleted file mode 100644 index 460e0a385474..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Workflows v1 API -========================================== -.. toctree:: - :maxdepth: 2 - - workflows diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/types_.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/types_.rst deleted file mode 100644 index 054c4fedc752..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Workflows v1 API -======================================= - -.. automodule:: google.cloud.workflows_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/workflows.rst b/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/workflows.rst deleted file mode 100644 index 3c916583a384..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/docs/workflows_v1/workflows.rst +++ /dev/null @@ -1,10 +0,0 @@ -Workflows ---------------------------- - -.. automodule:: google.cloud.workflows_v1.services.workflows - :members: - :inherited-members: - -.. automodule:: google.cloud.workflows_v1.services.workflows.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/__init__.py deleted file mode 100644 index 176e5116247b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/__init__.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.workflows_v1.services.workflows.client import WorkflowsClient -from google.cloud.workflows_v1.services.workflows.async_client import WorkflowsAsyncClient - -from google.cloud.workflows_v1.types.workflows import CreateWorkflowRequest -from google.cloud.workflows_v1.types.workflows import DeleteWorkflowRequest -from google.cloud.workflows_v1.types.workflows import GetWorkflowRequest -from google.cloud.workflows_v1.types.workflows import ListWorkflowsRequest -from google.cloud.workflows_v1.types.workflows import ListWorkflowsResponse -from google.cloud.workflows_v1.types.workflows import OperationMetadata -from google.cloud.workflows_v1.types.workflows import UpdateWorkflowRequest -from google.cloud.workflows_v1.types.workflows import Workflow - -__all__ = ('WorkflowsClient', - 'WorkflowsAsyncClient', - 'CreateWorkflowRequest', - 'DeleteWorkflowRequest', - 'GetWorkflowRequest', - 'ListWorkflowsRequest', - 'ListWorkflowsResponse', - 'OperationMetadata', - 'UpdateWorkflowRequest', - 'Workflow', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/__init__.py deleted file mode 100644 index f864a66be6f0..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows.executions import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.workflows.executions_v1.services.executions.client import ExecutionsClient -from google.cloud.workflows.executions_v1.services.executions.async_client import ExecutionsAsyncClient - -from google.cloud.workflows.executions_v1.types.executions import CancelExecutionRequest -from google.cloud.workflows.executions_v1.types.executions import CreateExecutionRequest -from google.cloud.workflows.executions_v1.types.executions import Execution -from google.cloud.workflows.executions_v1.types.executions import GetExecutionRequest -from google.cloud.workflows.executions_v1.types.executions import ListExecutionsRequest -from google.cloud.workflows.executions_v1.types.executions import ListExecutionsResponse -from google.cloud.workflows.executions_v1.types.executions import ExecutionView - -__all__ = ('ExecutionsClient', - 'ExecutionsAsyncClient', - 'CancelExecutionRequest', - 'CreateExecutionRequest', - 'Execution', - 'GetExecutionRequest', - 'ListExecutionsRequest', - 'ListExecutionsResponse', - 'ExecutionView', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/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-cloud-workflows/v1/google/cloud/workflows/executions/py.typed b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/py.typed deleted file mode 100644 index ff4d7c1ed09d..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workflows-executions package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/__init__.py deleted file mode 100644 index b87f2559c8a8..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/__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 google.cloud.workflows.executions_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.executions import ExecutionsClient -from .services.executions import ExecutionsAsyncClient - -from .types.executions import CancelExecutionRequest -from .types.executions import CreateExecutionRequest -from .types.executions import Execution -from .types.executions import GetExecutionRequest -from .types.executions import ListExecutionsRequest -from .types.executions import ListExecutionsResponse -from .types.executions import ExecutionView - -__all__ = ( - 'ExecutionsAsyncClient', -'CancelExecutionRequest', -'CreateExecutionRequest', -'Execution', -'ExecutionView', -'ExecutionsClient', -'GetExecutionRequest', -'ListExecutionsRequest', -'ListExecutionsResponse', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_metadata.json deleted file mode 100644 index f17943ae3dfa..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_metadata.json +++ /dev/null @@ -1,63 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.workflows.executions_v1", - "protoPackage": "google.cloud.workflows.executions.v1", - "schema": "1.0", - "services": { - "Executions": { - "clients": { - "grpc": { - "libraryClient": "ExecutionsClient", - "rpcs": { - "CancelExecution": { - "methods": [ - "cancel_execution" - ] - }, - "CreateExecution": { - "methods": [ - "create_execution" - ] - }, - "GetExecution": { - "methods": [ - "get_execution" - ] - }, - "ListExecutions": { - "methods": [ - "list_executions" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ExecutionsAsyncClient", - "rpcs": { - "CancelExecution": { - "methods": [ - "cancel_execution" - ] - }, - "CreateExecution": { - "methods": [ - "create_execution" - ] - }, - "GetExecution": { - "methods": [ - "get_execution" - ] - }, - "ListExecutions": { - "methods": [ - "list_executions" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_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-cloud-workflows/v1/google/cloud/workflows/executions_v1/py.typed b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/py.typed deleted file mode 100644 index ff4d7c1ed09d..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workflows-executions package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_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-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/__init__.py deleted file mode 100644 index 9295dd9a3cb5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/__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 ExecutionsClient -from .async_client import ExecutionsAsyncClient - -__all__ = ( - 'ExecutionsClient', - 'ExecutionsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/async_client.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/async_client.py deleted file mode 100644 index 384010c7f7e3..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/async_client.py +++ /dev/null @@ -1,697 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.workflows.executions_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.cloud.workflows.executions_v1.services.executions import pagers -from google.cloud.workflows.executions_v1.types import executions -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ExecutionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ExecutionsGrpcAsyncIOTransport -from .client import ExecutionsClient - - -class ExecutionsAsyncClient: - """Executions is used to start and manage running instances of - [Workflows][google.cloud.workflows.v1.Workflow] called executions. - """ - - _client: ExecutionsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ExecutionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ExecutionsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ExecutionsClient._DEFAULT_UNIVERSE - - execution_path = staticmethod(ExecutionsClient.execution_path) - parse_execution_path = staticmethod(ExecutionsClient.parse_execution_path) - workflow_path = staticmethod(ExecutionsClient.workflow_path) - parse_workflow_path = staticmethod(ExecutionsClient.parse_workflow_path) - common_billing_account_path = staticmethod(ExecutionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ExecutionsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ExecutionsClient.common_folder_path) - parse_common_folder_path = staticmethod(ExecutionsClient.parse_common_folder_path) - common_organization_path = staticmethod(ExecutionsClient.common_organization_path) - parse_common_organization_path = staticmethod(ExecutionsClient.parse_common_organization_path) - common_project_path = staticmethod(ExecutionsClient.common_project_path) - parse_common_project_path = staticmethod(ExecutionsClient.parse_common_project_path) - common_location_path = staticmethod(ExecutionsClient.common_location_path) - parse_common_location_path = staticmethod(ExecutionsClient.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: - ExecutionsAsyncClient: The constructed client. - """ - return ExecutionsClient.from_service_account_info.__func__(ExecutionsAsyncClient, 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: - ExecutionsAsyncClient: The constructed client. - """ - return ExecutionsClient.from_service_account_file.__func__(ExecutionsAsyncClient, 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 ExecutionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ExecutionsTransport: - """Returns the transport used by the client instance. - - Returns: - ExecutionsTransport: 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 = ExecutionsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ExecutionsTransport, Callable[..., ExecutionsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the executions 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,ExecutionsTransport,Callable[..., ExecutionsTransport]]]): - 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 ExecutionsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = ExecutionsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_executions(self, - request: Optional[Union[executions.ListExecutionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExecutionsAsyncPager: - r"""Returns a list of executions which belong to the - workflow with the given name. The method returns - executions of all workflow revisions. Returned - executions are ordered by their start time (newest - first). - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1 - - async def sample_list_executions(): - # Create a client - client = executions_v1.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1.ListExecutionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_executions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workflows.executions_v1.types.ListExecutionsRequest, dict]]): - The request object. Request for the [ListExecutions][] method. - parent (:class:`str`): - Required. Name of the workflow for - which the executions should be listed. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1.services.executions.pagers.ListExecutionsAsyncPager: - Response for the - [ListExecutions][google.cloud.workflows.executions.v1.Executions.ListExecutions] - 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, executions.ListExecutionsRequest): - request = executions.ListExecutionsRequest(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_executions] - - # Certain fields should be provided within 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.ListExecutionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_execution(self, - request: Optional[Union[executions.CreateExecutionRequest, dict]] = None, - *, - parent: Optional[str] = None, - execution: Optional[executions.Execution] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Creates a new execution using the latest revision of - the given workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1 - - async def sample_create_execution(): - # Create a client - client = executions_v1.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1.CreateExecutionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows.executions_v1.types.CreateExecutionRequest, dict]]): - The request object. Request for the - [CreateExecution][google.cloud.workflows.executions.v1.Executions.CreateExecution] - method. - parent (:class:`str`): - Required. Name of the workflow for - which an execution should be created. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - The latest revision of the workflow will - be used. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - execution (:class:`google.cloud.workflows.executions_v1.types.Execution`): - Required. Execution to be created. - This corresponds to the ``execution`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_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. - - Returns: - google.cloud.workflows.executions_v1.types.Execution: - A running instance of a - [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). - - """ - # Create or coerce a protobuf request object. - # - Quick 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, execution]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, executions.CreateExecutionRequest): - request = executions.CreateExecutionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if execution is not None: - request.execution = execution - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_execution] - - # Certain fields should be provided within 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_execution(self, - request: Optional[Union[executions.GetExecutionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Returns an execution of the given name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1 - - async def sample_get_execution(): - # Create a client - client = executions_v1.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1.GetExecutionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows.executions_v1.types.GetExecutionRequest, dict]]): - The request object. Request for the - [GetExecution][google.cloud.workflows.executions.v1.Executions.GetExecution] - method. - name (:class:`str`): - Required. Name of the execution to be - retrieved. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1.types.Execution: - A running instance of a - [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). - - """ - # Create or coerce a protobuf request object. - # - Quick 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, executions.GetExecutionRequest): - request = executions.GetExecutionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_execution] - - # Certain fields should be provided within 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 cancel_execution(self, - request: Optional[Union[executions.CancelExecutionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Cancels an execution of the given name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1 - - async def sample_cancel_execution(): - # Create a client - client = executions_v1.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1.CancelExecutionRequest( - name="name_value", - ) - - # Make the request - response = await client.cancel_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows.executions_v1.types.CancelExecutionRequest, dict]]): - The request object. Request for the - [CancelExecution][google.cloud.workflows.executions.v1.Executions.CancelExecution] - method. - name (:class:`str`): - Required. Name of the execution to be - cancelled. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1.types.Execution: - A running instance of a - [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). - - """ - # Create or coerce a protobuf request object. - # - Quick 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, executions.CancelExecutionRequest): - request = executions.CancelExecutionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.cancel_execution] - - # Certain fields should be provided within 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) -> "ExecutionsAsyncClient": - 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__ = ( - "ExecutionsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/client.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/client.py deleted file mode 100644 index 27a2c765747c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/client.py +++ /dev/null @@ -1,1057 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.workflows.executions_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 - -from google.cloud.workflows.executions_v1.services.executions import pagers -from google.cloud.workflows.executions_v1.types import executions -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ExecutionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ExecutionsGrpcTransport -from .transports.grpc_asyncio import ExecutionsGrpcAsyncIOTransport - - -class ExecutionsClientMeta(type): - """Metaclass for the Executions 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[ExecutionsTransport]] - _transport_registry["grpc"] = ExecutionsGrpcTransport - _transport_registry["grpc_asyncio"] = ExecutionsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ExecutionsTransport]: - """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 ExecutionsClient(metaclass=ExecutionsClientMeta): - """Executions is used to start and manage running instances of - [Workflows][google.cloud.workflows.v1.Workflow] called executions. - """ - - @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 = "workflowexecutions.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "workflowexecutions.{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: - ExecutionsClient: 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: - ExecutionsClient: 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) -> ExecutionsTransport: - """Returns the transport used by the client instance. - - Returns: - ExecutionsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def execution_path(project: str,location: str,workflow: str,execution: str,) -> str: - """Returns a fully-qualified execution string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}".format(project=project, location=location, workflow=workflow, execution=execution, ) - - @staticmethod - def parse_execution_path(path: str) -> Dict[str,str]: - """Parses a execution path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)/executions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workflow_path(project: str,location: str,workflow: str,) -> str: - """Returns a fully-qualified workflow string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - - @staticmethod - def parse_workflow_path(path: str) -> Dict[str,str]: - """Parses a workflow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = ExecutionsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ExecutionsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ExecutionsClient._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 = ExecutionsClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ExecutionsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - ExecutionsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, ExecutionsTransport, Callable[..., ExecutionsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the executions client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,ExecutionsTransport,Callable[..., ExecutionsTransport]]]): - 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 ExecutionsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = ExecutionsClient._read_environment_variables() - self._client_cert_source = ExecutionsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ExecutionsClient._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 - - 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, ExecutionsTransport) - if transport_provided: - # transport is a ExecutionsTransport 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(ExecutionsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ExecutionsClient._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[ExecutionsTransport], Callable[..., ExecutionsTransport]] = ( - ExecutionsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ExecutionsTransport], 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, - ) - - def list_executions(self, - request: Optional[Union[executions.ListExecutionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExecutionsPager: - r"""Returns a list of executions which belong to the - workflow with the given name. The method returns - executions of all workflow revisions. Returned - executions are ordered by their start time (newest - first). - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1 - - def sample_list_executions(): - # Create a client - client = executions_v1.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1.ListExecutionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_executions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workflows.executions_v1.types.ListExecutionsRequest, dict]): - The request object. Request for the [ListExecutions][] method. - parent (str): - Required. Name of the workflow for - which the executions should be listed. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1.services.executions.pagers.ListExecutionsPager: - Response for the - [ListExecutions][google.cloud.workflows.executions.v1.Executions.ListExecutions] - 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, executions.ListExecutionsRequest): - request = executions.ListExecutionsRequest(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_executions] - - # Certain fields should be provided within 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.ListExecutionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_execution(self, - request: Optional[Union[executions.CreateExecutionRequest, dict]] = None, - *, - parent: Optional[str] = None, - execution: Optional[executions.Execution] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Creates a new execution using the latest revision of - the given workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1 - - def sample_create_execution(): - # Create a client - client = executions_v1.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1.CreateExecutionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows.executions_v1.types.CreateExecutionRequest, dict]): - The request object. Request for the - [CreateExecution][google.cloud.workflows.executions.v1.Executions.CreateExecution] - method. - parent (str): - Required. Name of the workflow for - which an execution should be created. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - The latest revision of the workflow will - be used. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - execution (google.cloud.workflows.executions_v1.types.Execution): - Required. Execution to be created. - This corresponds to the ``execution`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.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. - - Returns: - google.cloud.workflows.executions_v1.types.Execution: - A running instance of a - [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). - - """ - # Create or coerce a protobuf request object. - # - Quick 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, execution]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, executions.CreateExecutionRequest): - request = executions.CreateExecutionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if execution is not None: - request.execution = execution - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_execution] - - # Certain fields should be provided within 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_execution(self, - request: Optional[Union[executions.GetExecutionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Returns an execution of the given name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1 - - def sample_get_execution(): - # Create a client - client = executions_v1.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1.GetExecutionRequest( - name="name_value", - ) - - # Make the request - response = client.get_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows.executions_v1.types.GetExecutionRequest, dict]): - The request object. Request for the - [GetExecution][google.cloud.workflows.executions.v1.Executions.GetExecution] - method. - name (str): - Required. Name of the execution to be - retrieved. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1.types.Execution: - A running instance of a - [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). - - """ - # Create or coerce a protobuf request object. - # - Quick 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, executions.GetExecutionRequest): - request = executions.GetExecutionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_execution] - - # Certain fields should be provided within 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 cancel_execution(self, - request: Optional[Union[executions.CancelExecutionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Cancels an execution of the given name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1 - - def sample_cancel_execution(): - # Create a client - client = executions_v1.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1.CancelExecutionRequest( - name="name_value", - ) - - # Make the request - response = client.cancel_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows.executions_v1.types.CancelExecutionRequest, dict]): - The request object. Request for the - [CancelExecution][google.cloud.workflows.executions.v1.Executions.CancelExecution] - method. - name (str): - Required. Name of the execution to be - cancelled. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1.types.Execution: - A running instance of a - [Workflow](/workflows/docs/reference/rest/v1/projects.locations.workflows). - - """ - # Create or coerce a protobuf request object. - # - Quick 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, executions.CancelExecutionRequest): - request = executions.CancelExecutionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.cancel_execution] - - # Certain fields should be provided within 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) -> "ExecutionsClient": - 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__ = ( - "ExecutionsClient", -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/pagers.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/pagers.py deleted file mode 100644 index 15cd30651438..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows.executions_v1.types import executions - - -class ListExecutionsPager: - """A pager for iterating through ``list_executions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workflows.executions_v1.types.ListExecutionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``executions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListExecutions`` requests and continue to iterate - through the ``executions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workflows.executions_v1.types.ListExecutionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., executions.ListExecutionsResponse], - request: executions.ListExecutionsRequest, - response: executions.ListExecutionsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workflows.executions_v1.types.ListExecutionsRequest): - The initial request object. - response (google.cloud.workflows.executions_v1.types.ListExecutionsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = executions.ListExecutionsRequest(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[executions.ListExecutionsResponse]: - 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[executions.Execution]: - for page in self.pages: - yield from page.executions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListExecutionsAsyncPager: - """A pager for iterating through ``list_executions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workflows.executions_v1.types.ListExecutionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``executions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListExecutions`` requests and continue to iterate - through the ``executions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workflows.executions_v1.types.ListExecutionsResponse` - attributes are available on the 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[executions.ListExecutionsResponse]], - request: executions.ListExecutionsRequest, - response: executions.ListExecutionsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workflows.executions_v1.types.ListExecutionsRequest): - The initial request object. - response (google.cloud.workflows.executions_v1.types.ListExecutionsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = executions.ListExecutionsRequest(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[executions.ListExecutionsResponse]: - 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[executions.Execution]: - async def async_generator(): - async for page in self.pages: - for response in page.executions: - 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-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/README.rst b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/README.rst deleted file mode 100644 index 6555db202c9c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ExecutionsTransport` is the ABC for all transports. -- public child `ExecutionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ExecutionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseExecutionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ExecutionsRestTransport` 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-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/__init__.py deleted file mode 100644 index fbf990808f62..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 ExecutionsTransport -from .grpc import ExecutionsGrpcTransport -from .grpc_asyncio import ExecutionsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ExecutionsTransport]] -_transport_registry['grpc'] = ExecutionsGrpcTransport -_transport_registry['grpc_asyncio'] = ExecutionsGrpcAsyncIOTransport - -__all__ = ( - 'ExecutionsTransport', - 'ExecutionsGrpcTransport', - 'ExecutionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/base.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/base.py deleted file mode 100644 index 685f383ca66b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/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.cloud.workflows.executions_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.cloud.workflows.executions_v1.types import executions - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ExecutionsTransport(abc.ABC): - """Abstract transport class for Executions.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_executions: gapic_v1.method.wrap_method( - self.list_executions, - default_timeout=None, - client_info=client_info, - ), - self.create_execution: gapic_v1.method.wrap_method( - self.create_execution, - default_timeout=None, - client_info=client_info, - ), - self.get_execution: gapic_v1.method.wrap_method( - self.get_execution, - default_timeout=None, - client_info=client_info, - ), - self.cancel_execution: gapic_v1.method.wrap_method( - self.cancel_execution, - 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_executions(self) -> Callable[ - [executions.ListExecutionsRequest], - Union[ - executions.ListExecutionsResponse, - Awaitable[executions.ListExecutionsResponse] - ]]: - raise NotImplementedError() - - @property - def create_execution(self) -> Callable[ - [executions.CreateExecutionRequest], - Union[ - executions.Execution, - Awaitable[executions.Execution] - ]]: - raise NotImplementedError() - - @property - def get_execution(self) -> Callable[ - [executions.GetExecutionRequest], - Union[ - executions.Execution, - Awaitable[executions.Execution] - ]]: - raise NotImplementedError() - - @property - def cancel_execution(self) -> Callable[ - [executions.CancelExecutionRequest], - Union[ - executions.Execution, - Awaitable[executions.Execution] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ExecutionsTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc.py deleted file mode 100644 index 634f6ada2a5b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc.py +++ /dev/null @@ -1,354 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.cloud.workflows.executions_v1.types import executions -from .base import ExecutionsTransport, DEFAULT_CLIENT_INFO - - -class ExecutionsGrpcTransport(ExecutionsTransport): - """gRPC backend transport for Executions. - - Executions is used to start and manage running instances of - [Workflows][google.cloud.workflows.v1.Workflow] called executions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'workflowexecutions.googleapis.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_executions(self) -> Callable[ - [executions.ListExecutionsRequest], - executions.ListExecutionsResponse]: - r"""Return a callable for the list executions method over gRPC. - - Returns a list of executions which belong to the - workflow with the given name. The method returns - executions of all workflow revisions. Returned - executions are ordered by their start time (newest - first). - - Returns: - Callable[[~.ListExecutionsRequest], - ~.ListExecutionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_executions' not in self._stubs: - self._stubs['list_executions'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1.Executions/ListExecutions', - request_serializer=executions.ListExecutionsRequest.serialize, - response_deserializer=executions.ListExecutionsResponse.deserialize, - ) - return self._stubs['list_executions'] - - @property - def create_execution(self) -> Callable[ - [executions.CreateExecutionRequest], - executions.Execution]: - r"""Return a callable for the create execution method over gRPC. - - Creates a new execution using the latest revision of - the given workflow. - - Returns: - Callable[[~.CreateExecutionRequest], - ~.Execution]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_execution' not in self._stubs: - self._stubs['create_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1.Executions/CreateExecution', - request_serializer=executions.CreateExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['create_execution'] - - @property - def get_execution(self) -> Callable[ - [executions.GetExecutionRequest], - executions.Execution]: - r"""Return a callable for the get execution method over gRPC. - - Returns an execution of the given name. - - Returns: - Callable[[~.GetExecutionRequest], - ~.Execution]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_execution' not in self._stubs: - self._stubs['get_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1.Executions/GetExecution', - request_serializer=executions.GetExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['get_execution'] - - @property - def cancel_execution(self) -> Callable[ - [executions.CancelExecutionRequest], - executions.Execution]: - r"""Return a callable for the cancel execution method over gRPC. - - Cancels an execution of the given name. - - Returns: - Callable[[~.CancelExecutionRequest], - ~.Execution]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'cancel_execution' not in self._stubs: - self._stubs['cancel_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1.Executions/CancelExecution', - request_serializer=executions.CancelExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['cancel_execution'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ExecutionsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc_asyncio.py deleted file mode 100644 index 1bcafa2551d5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/services/executions/transports/grpc_asyncio.py +++ /dev/null @@ -1,390 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.workflows.executions_v1.types import executions -from .base import ExecutionsTransport, DEFAULT_CLIENT_INFO -from .grpc import ExecutionsGrpcTransport - - -class ExecutionsGrpcAsyncIOTransport(ExecutionsTransport): - """gRPC AsyncIO backend transport for Executions. - - Executions is used to start and manage running instances of - [Workflows][google.cloud.workflows.v1.Workflow] called executions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workflowexecutions.googleapis.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 = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_executions(self) -> Callable[ - [executions.ListExecutionsRequest], - Awaitable[executions.ListExecutionsResponse]]: - r"""Return a callable for the list executions method over gRPC. - - Returns a list of executions which belong to the - workflow with the given name. The method returns - executions of all workflow revisions. Returned - executions are ordered by their start time (newest - first). - - Returns: - Callable[[~.ListExecutionsRequest], - Awaitable[~.ListExecutionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_executions' not in self._stubs: - self._stubs['list_executions'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1.Executions/ListExecutions', - request_serializer=executions.ListExecutionsRequest.serialize, - response_deserializer=executions.ListExecutionsResponse.deserialize, - ) - return self._stubs['list_executions'] - - @property - def create_execution(self) -> Callable[ - [executions.CreateExecutionRequest], - Awaitable[executions.Execution]]: - r"""Return a callable for the create execution method over gRPC. - - Creates a new execution using the latest revision of - the given workflow. - - Returns: - Callable[[~.CreateExecutionRequest], - Awaitable[~.Execution]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_execution' not in self._stubs: - self._stubs['create_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1.Executions/CreateExecution', - request_serializer=executions.CreateExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['create_execution'] - - @property - def get_execution(self) -> Callable[ - [executions.GetExecutionRequest], - Awaitable[executions.Execution]]: - r"""Return a callable for the get execution method over gRPC. - - Returns an execution of the given name. - - Returns: - Callable[[~.GetExecutionRequest], - Awaitable[~.Execution]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_execution' not in self._stubs: - self._stubs['get_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1.Executions/GetExecution', - request_serializer=executions.GetExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['get_execution'] - - @property - def cancel_execution(self) -> Callable[ - [executions.CancelExecutionRequest], - Awaitable[executions.Execution]]: - r"""Return a callable for the cancel execution method over gRPC. - - Cancels an execution of the given name. - - Returns: - Callable[[~.CancelExecutionRequest], - Awaitable[~.Execution]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'cancel_execution' not in self._stubs: - self._stubs['cancel_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1.Executions/CancelExecution', - request_serializer=executions.CancelExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['cancel_execution'] - - 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_executions: self._wrap_method( - self.list_executions, - default_timeout=None, - client_info=client_info, - ), - self.create_execution: self._wrap_method( - self.create_execution, - default_timeout=None, - client_info=client_info, - ), - self.get_execution: self._wrap_method( - self.get_execution, - default_timeout=None, - client_info=client_info, - ), - self.cancel_execution: self._wrap_method( - self.cancel_execution, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'ExecutionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/__init__.py deleted file mode 100644 index 52fb1dab35df..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .executions import ( - CancelExecutionRequest, - CreateExecutionRequest, - Execution, - GetExecutionRequest, - ListExecutionsRequest, - ListExecutionsResponse, - ExecutionView, -) - -__all__ = ( - 'CancelExecutionRequest', - 'CreateExecutionRequest', - 'Execution', - 'GetExecutionRequest', - 'ListExecutionsRequest', - 'ListExecutionsResponse', - 'ExecutionView', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/executions.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/executions.py deleted file mode 100644 index f6eb9a3d8228..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/executions_v1/types/executions.py +++ /dev/null @@ -1,580 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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 - - -__protobuf__ = proto.module( - package='google.cloud.workflows.executions.v1', - manifest={ - 'ExecutionView', - 'Execution', - 'ListExecutionsRequest', - 'ListExecutionsResponse', - 'CreateExecutionRequest', - 'GetExecutionRequest', - 'CancelExecutionRequest', - }, -) - - -class ExecutionView(proto.Enum): - r"""Defines possible views for execution resource. - - Values: - EXECUTION_VIEW_UNSPECIFIED (0): - The default / unset value. - BASIC (1): - Includes only basic metadata about the execution. The - following fields are returned: name, start_time, end_time, - duration, state, and workflow_revision_id. - FULL (2): - Includes all data. - """ - EXECUTION_VIEW_UNSPECIFIED = 0 - BASIC = 1 - FULL = 2 - - -class Execution(proto.Message): - r"""A running instance of a - `Workflow `__. - - Attributes: - name (str): - Output only. The resource name of the - execution. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Marks the beginning of - execution. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Marks the end of execution, - successful or not. - duration (google.protobuf.duration_pb2.Duration): - Output only. Measures the duration of the - execution. - state (google.cloud.workflows.executions_v1.types.Execution.State): - Output only. Current state of the execution. - argument (str): - Input parameters of the execution represented as a JSON - string. The size limit is 32KB. - - *Note*: If you are using the REST API directly to run your - workflow, you must escape any JSON string value of - ``argument``. Example: - ``'{"argument":"{\"firstName\":\"FIRST\",\"lastName\":\"LAST\"}"}'`` - result (str): - Output only. Output of the execution represented as a JSON - string. The value can only be present if the execution's - state is ``SUCCEEDED``. - error (google.cloud.workflows.executions_v1.types.Execution.Error): - Output only. The error which caused the execution to finish - prematurely. The value is only present if the execution's - state is ``FAILED`` or ``CANCELLED``. - workflow_revision_id (str): - Output only. Revision of the workflow this - execution is using. - call_log_level (google.cloud.workflows.executions_v1.types.Execution.CallLogLevel): - The call logging level associated to this - execution. - status (google.cloud.workflows.executions_v1.types.Execution.Status): - Output only. Status tracks the current steps - and progress data of this execution. - labels (MutableMapping[str, str]): - Labels associated with this execution. - Labels can contain at most 64 entries. Keys and - values can be no longer than 63 characters and - can only contain lowercase letters, numeric - characters, underscores, and dashes. Label keys - must start with a letter. International - characters are allowed. - By default, labels are inherited from the - workflow but are overridden by any labels - associated with the execution. - state_error (google.cloud.workflows.executions_v1.types.Execution.StateError): - Output only. Error regarding the state of the - Execution resource. For example, this field will - have error details if the execution data is - unavailable due to revoked KMS key permissions. - """ - class State(proto.Enum): - r"""Describes the current state of the execution. More states - might be added in the future. - - Values: - STATE_UNSPECIFIED (0): - Invalid state. - ACTIVE (1): - The execution is in progress. - SUCCEEDED (2): - The execution finished successfully. - FAILED (3): - The execution failed with an error. - CANCELLED (4): - The execution was stopped intentionally. - UNAVAILABLE (5): - Execution data is unavailable. See the ``state_error`` - field. - QUEUED (6): - Request has been placed in the backlog for - processing at a later time. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - SUCCEEDED = 2 - FAILED = 3 - CANCELLED = 4 - UNAVAILABLE = 5 - QUEUED = 6 - - class CallLogLevel(proto.Enum): - r"""Describes the level of platform logging to apply to calls and - call responses during workflow executions. - - Values: - CALL_LOG_LEVEL_UNSPECIFIED (0): - No call logging level specified. - LOG_ALL_CALLS (1): - Log all call steps within workflows, all call - returns, and all exceptions raised. - LOG_ERRORS_ONLY (2): - Log only exceptions that are raised from call - steps within workflows. - LOG_NONE (3): - Explicitly log nothing. - """ - CALL_LOG_LEVEL_UNSPECIFIED = 0 - LOG_ALL_CALLS = 1 - LOG_ERRORS_ONLY = 2 - LOG_NONE = 3 - - class StackTraceElement(proto.Message): - r"""A single stack element (frame) where an error occurred. - - Attributes: - step (str): - The step the error occurred at. - routine (str): - The routine where the error occurred. - position (google.cloud.workflows.executions_v1.types.Execution.StackTraceElement.Position): - The source position information of the stack - trace element. - """ - - class Position(proto.Message): - r"""Position contains source position information about the stack - trace element such as line number, column number and length of - the code block in bytes. - - Attributes: - line (int): - The source code line number the current - instruction was generated from. - column (int): - The source code column position (of the line) - the current instruction was generated from. - length (int): - The number of bytes of source code making up - this stack trace element. - """ - - line: int = proto.Field( - proto.INT64, - number=1, - ) - column: int = proto.Field( - proto.INT64, - number=2, - ) - length: int = proto.Field( - proto.INT64, - number=3, - ) - - step: str = proto.Field( - proto.STRING, - number=1, - ) - routine: str = proto.Field( - proto.STRING, - number=2, - ) - position: 'Execution.StackTraceElement.Position' = proto.Field( - proto.MESSAGE, - number=3, - message='Execution.StackTraceElement.Position', - ) - - class StackTrace(proto.Message): - r"""A collection of stack elements (frames) where an error - occurred. - - Attributes: - elements (MutableSequence[google.cloud.workflows.executions_v1.types.Execution.StackTraceElement]): - An array of stack elements. - """ - - elements: MutableSequence['Execution.StackTraceElement'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Execution.StackTraceElement', - ) - - class Error(proto.Message): - r"""Error describes why the execution was abnormally terminated. - - Attributes: - payload (str): - Error message and data returned represented - as a JSON string. - context (str): - Human-readable stack trace string. - stack_trace (google.cloud.workflows.executions_v1.types.Execution.StackTrace): - Stack trace with detailed information of - where error was generated. - """ - - payload: str = proto.Field( - proto.STRING, - number=1, - ) - context: str = proto.Field( - proto.STRING, - number=2, - ) - stack_trace: 'Execution.StackTrace' = proto.Field( - proto.MESSAGE, - number=3, - message='Execution.StackTrace', - ) - - class Status(proto.Message): - r"""Represents the current status of this execution. - - Attributes: - current_steps (MutableSequence[google.cloud.workflows.executions_v1.types.Execution.Status.Step]): - A list of currently executing or last executed step names - for the workflow execution currently running. If the - workflow has succeeded or failed, this is the last attempted - or executed step. Presently, if the current step is inside a - subworkflow, the list only includes that step. In the - future, the list will contain items for each step in the - call stack, starting with the outermost step in the ``main`` - subworkflow, and ending with the most deeply nested step. - """ - - class Step(proto.Message): - r"""Represents a step of the workflow this execution is running. - - Attributes: - routine (str): - Name of a routine within the workflow. - step (str): - Name of a step within the routine. - """ - - routine: str = proto.Field( - proto.STRING, - number=1, - ) - step: str = proto.Field( - proto.STRING, - number=2, - ) - - current_steps: MutableSequence['Execution.Status.Step'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Execution.Status.Step', - ) - - class StateError(proto.Message): - r"""Describes an error related to the current state of the - Execution resource. - - Attributes: - details (str): - Provides specifics about the error. - type_ (google.cloud.workflows.executions_v1.types.Execution.StateError.Type): - The type of this state error. - """ - class Type(proto.Enum): - r"""Describes the possible types of a state error. - - Values: - TYPE_UNSPECIFIED (0): - No type specified. - KMS_ERROR (1): - Caused by an issue with KMS. - """ - TYPE_UNSPECIFIED = 0 - KMS_ERROR = 1 - - details: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'Execution.StateError.Type' = proto.Field( - proto.ENUM, - number=2, - enum='Execution.StateError.Type', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=12, - message=duration_pb2.Duration, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - argument: str = proto.Field( - proto.STRING, - number=5, - ) - result: str = proto.Field( - proto.STRING, - number=6, - ) - error: Error = proto.Field( - proto.MESSAGE, - number=7, - message=Error, - ) - workflow_revision_id: str = proto.Field( - proto.STRING, - number=8, - ) - call_log_level: CallLogLevel = proto.Field( - proto.ENUM, - number=9, - enum=CallLogLevel, - ) - status: Status = proto.Field( - proto.MESSAGE, - number=10, - message=Status, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=11, - ) - state_error: StateError = proto.Field( - proto.MESSAGE, - number=13, - message=StateError, - ) - - -class ListExecutionsRequest(proto.Message): - r"""Request for the [ListExecutions][] method. - - Attributes: - parent (str): - Required. Name of the workflow for which the - executions should be listed. Format: - projects/{project}/locations/{location}/workflows/{workflow} - page_size (int): - Maximum number of executions to return per - call. Max supported value depends on the - selected Execution view: it's 1000 for BASIC and - 100 for FULL. The default value used if the - field is not specified is 100, regardless of the - selected view. Values greater than the max value - will be coerced down to it. - page_token (str): - A page token, received from a previous ``ListExecutions`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListExecutions`` must match the call that provided the - page token. - - Note that pagination is applied to dynamic data. The list of - executions returned can change between page requests. - view (google.cloud.workflows.executions_v1.types.ExecutionView): - Optional. A view defining which fields should - be filled in the returned executions. The API - will default to the BASIC view. - filter (str): - Optional. Filters applied to the [Executions.ListExecutions] - results. The following fields are supported for filtering: - executionID, state, startTime, endTime, duration, - workflowRevisionID, stepName, and label. - order_by (str): - Optional. The ordering applied to the - [Executions.ListExecutions] results. By default the ordering - is based on descending start time. The following fields are - supported for order by: executionID, startTime, endTime, - duration, state, and workflowRevisionID. - """ - - 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, - ) - view: 'ExecutionView' = proto.Field( - proto.ENUM, - number=4, - enum='ExecutionView', - ) - filter: str = proto.Field( - proto.STRING, - number=5, - ) - order_by: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ListExecutionsResponse(proto.Message): - r"""Response for the - [ListExecutions][google.cloud.workflows.executions.v1.Executions.ListExecutions] - method. - - Attributes: - executions (MutableSequence[google.cloud.workflows.executions_v1.types.Execution]): - The executions which match the request. - 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 - - executions: MutableSequence['Execution'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Execution', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateExecutionRequest(proto.Message): - r"""Request for the - [CreateExecution][google.cloud.workflows.executions.v1.Executions.CreateExecution] - method. - - Attributes: - parent (str): - Required. Name of the workflow for which an - execution should be created. Format: - projects/{project}/locations/{location}/workflows/{workflow} - The latest revision of the workflow will be - used. - execution (google.cloud.workflows.executions_v1.types.Execution): - Required. Execution to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - execution: 'Execution' = proto.Field( - proto.MESSAGE, - number=2, - message='Execution', - ) - - -class GetExecutionRequest(proto.Message): - r"""Request for the - [GetExecution][google.cloud.workflows.executions.v1.Executions.GetExecution] - method. - - Attributes: - name (str): - Required. Name of the execution to be - retrieved. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - view (google.cloud.workflows.executions_v1.types.ExecutionView): - Optional. A view defining which fields should - be filled in the returned execution. The API - will default to the FULL view. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - view: 'ExecutionView' = proto.Field( - proto.ENUM, - number=2, - enum='ExecutionView', - ) - - -class CancelExecutionRequest(proto.Message): - r"""Request for the - [CancelExecution][google.cloud.workflows.executions.v1.Executions.CancelExecution] - method. - - Attributes: - name (str): - Required. Name of the execution to be - cancelled. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/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-cloud-workflows/v1/google/cloud/workflows/py.typed b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/py.typed deleted file mode 100644 index b753e6a6bf5b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workflows package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/__init__.py deleted file mode 100644 index 2550c3833296..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/__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 google.cloud.workflows_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.workflows import WorkflowsClient -from .services.workflows import WorkflowsAsyncClient - -from .types.workflows import CreateWorkflowRequest -from .types.workflows import DeleteWorkflowRequest -from .types.workflows import GetWorkflowRequest -from .types.workflows import ListWorkflowsRequest -from .types.workflows import ListWorkflowsResponse -from .types.workflows import OperationMetadata -from .types.workflows import UpdateWorkflowRequest -from .types.workflows import Workflow - -__all__ = ( - 'WorkflowsAsyncClient', -'CreateWorkflowRequest', -'DeleteWorkflowRequest', -'GetWorkflowRequest', -'ListWorkflowsRequest', -'ListWorkflowsResponse', -'OperationMetadata', -'UpdateWorkflowRequest', -'Workflow', -'WorkflowsClient', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_metadata.json deleted file mode 100644 index a41eecf2981e..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_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.cloud.workflows_v1", - "protoPackage": "google.cloud.workflows.v1", - "schema": "1.0", - "services": { - "Workflows": { - "clients": { - "grpc": { - "libraryClient": "WorkflowsClient", - "rpcs": { - "CreateWorkflow": { - "methods": [ - "create_workflow" - ] - }, - "DeleteWorkflow": { - "methods": [ - "delete_workflow" - ] - }, - "GetWorkflow": { - "methods": [ - "get_workflow" - ] - }, - "ListWorkflows": { - "methods": [ - "list_workflows" - ] - }, - "UpdateWorkflow": { - "methods": [ - "update_workflow" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WorkflowsAsyncClient", - "rpcs": { - "CreateWorkflow": { - "methods": [ - "create_workflow" - ] - }, - "DeleteWorkflow": { - "methods": [ - "delete_workflow" - ] - }, - "GetWorkflow": { - "methods": [ - "get_workflow" - ] - }, - "ListWorkflows": { - "methods": [ - "list_workflows" - ] - }, - "UpdateWorkflow": { - "methods": [ - "update_workflow" - ] - } - } - }, - "rest": { - "libraryClient": "WorkflowsClient", - "rpcs": { - "CreateWorkflow": { - "methods": [ - "create_workflow" - ] - }, - "DeleteWorkflow": { - "methods": [ - "delete_workflow" - ] - }, - "GetWorkflow": { - "methods": [ - "get_workflow" - ] - }, - "ListWorkflows": { - "methods": [ - "list_workflows" - ] - }, - "UpdateWorkflow": { - "methods": [ - "update_workflow" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_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-cloud-workflows/v1/google/cloud/workflows_v1/py.typed b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/py.typed deleted file mode 100644 index b753e6a6bf5b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workflows package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_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-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/__init__.py deleted file mode 100644 index 5c7fa07ed889..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/__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 WorkflowsClient -from .async_client import WorkflowsAsyncClient - -__all__ = ( - 'WorkflowsClient', - 'WorkflowsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/async_client.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/async_client.py deleted file mode 100644 index 9dffa143847f..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/async_client.py +++ /dev/null @@ -1,1149 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.workflows_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.cloud.location import locations_pb2 # type: ignore -from google.cloud.workflows_v1.services.workflows import pagers -from google.cloud.workflows_v1.types import workflows -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WorkflowsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WorkflowsGrpcAsyncIOTransport -from .client import WorkflowsClient - - -class WorkflowsAsyncClient: - """Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - """ - - _client: WorkflowsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = WorkflowsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WorkflowsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = WorkflowsClient._DEFAULT_UNIVERSE - - crypto_key_path = staticmethod(WorkflowsClient.crypto_key_path) - parse_crypto_key_path = staticmethod(WorkflowsClient.parse_crypto_key_path) - workflow_path = staticmethod(WorkflowsClient.workflow_path) - parse_workflow_path = staticmethod(WorkflowsClient.parse_workflow_path) - common_billing_account_path = staticmethod(WorkflowsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WorkflowsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WorkflowsClient.common_folder_path) - parse_common_folder_path = staticmethod(WorkflowsClient.parse_common_folder_path) - common_organization_path = staticmethod(WorkflowsClient.common_organization_path) - parse_common_organization_path = staticmethod(WorkflowsClient.parse_common_organization_path) - common_project_path = staticmethod(WorkflowsClient.common_project_path) - parse_common_project_path = staticmethod(WorkflowsClient.parse_common_project_path) - common_location_path = staticmethod(WorkflowsClient.common_location_path) - parse_common_location_path = staticmethod(WorkflowsClient.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: - WorkflowsAsyncClient: The constructed client. - """ - return WorkflowsClient.from_service_account_info.__func__(WorkflowsAsyncClient, 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: - WorkflowsAsyncClient: The constructed client. - """ - return WorkflowsClient.from_service_account_file.__func__(WorkflowsAsyncClient, 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 WorkflowsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> WorkflowsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkflowsTransport: 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 = WorkflowsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, WorkflowsTransport, Callable[..., WorkflowsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workflows 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,WorkflowsTransport,Callable[..., WorkflowsTransport]]]): - 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 WorkflowsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WorkflowsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_workflows(self, - request: Optional[Union[workflows.ListWorkflowsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkflowsAsyncPager: - r"""Lists workflows in a given project and location. - The default order is not specified. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1 - - async def sample_list_workflows(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1.ListWorkflowsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workflows(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1.types.ListWorkflowsRequest, dict]]): - The request object. Request for the - [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] - method. - parent (:class:`str`): - Required. Project and location from - which the workflows should be listed. - Format: - projects/{project}/locations/{location} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows_v1.services.workflows.pagers.ListWorkflowsAsyncPager: - Response for the - [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] - 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, workflows.ListWorkflowsRequest): - request = workflows.ListWorkflowsRequest(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_workflows] - - # Certain fields should be provided within 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.ListWorkflowsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_workflow(self, - request: Optional[Union[workflows.GetWorkflowRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workflows.Workflow: - r"""Gets details of a single workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1 - - async def sample_get_workflow(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1.GetWorkflowRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workflow(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1.types.GetWorkflowRequest, dict]]): - The request object. Request for the - [GetWorkflow][google.cloud.workflows.v1.Workflows.GetWorkflow] - method. - name (:class:`str`): - Required. Name of the workflow for - which information should be retrieved. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows_v1.types.Workflow: - Workflow program to be executed by - Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflows.GetWorkflowRequest): - request = workflows.GetWorkflowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workflow] - - # Certain fields should be provided within 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_workflow(self, - request: Optional[Union[workflows.CreateWorkflowRequest, dict]] = None, - *, - parent: Optional[str] = None, - workflow: Optional[workflows.Workflow] = None, - workflow_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workflow. If a workflow with the specified name - already exists in the specified project and location, the long - running operation returns a - [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] 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.cloud import workflows_v1 - - async def sample_create_workflow(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - workflow = workflows_v1.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1.CreateWorkflowRequest( - parent="parent_value", - workflow=workflow, - workflow_id="workflow_id_value", - ) - - # Make the request - operation = client.create_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1.types.CreateWorkflowRequest, dict]]): - The request object. Request for the - [CreateWorkflow][google.cloud.workflows.v1.Workflows.CreateWorkflow] - method. - parent (:class:`str`): - Required. Project and location in - which the workflow should be created. - Format: - projects/{project}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workflow (:class:`google.cloud.workflows_v1.types.Workflow`): - Required. Workflow to be created. - This corresponds to the ``workflow`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workflow_id (:class:`str`): - Required. The ID of the workflow to be created. It has - to fulfill the following requirements: - - - Must contain only letters, numbers, underscores and - hyphens. - - Must start with a letter. - - Must be between 1-64 characters. - - Must end with a number or a letter. - - Must be unique within the customer project and - location. - - This corresponds to the ``workflow_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workflows_v1.types.Workflow` - Workflow program to be executed by Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflow, workflow_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, workflows.CreateWorkflowRequest): - request = workflows.CreateWorkflowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workflow is not None: - request.workflow = workflow - if workflow_id is not None: - request.workflow_id = workflow_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_workflow] - - # Certain fields should be provided within 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, - workflows.Workflow, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workflow(self, - request: Optional[Union[workflows.DeleteWorkflowRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a workflow with the specified name. - This method also cancels and deletes all running - executions of the workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1 - - async def sample_delete_workflow(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1.DeleteWorkflowRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1.types.DeleteWorkflowRequest, dict]]): - The request object. Request for the - [DeleteWorkflow][google.cloud.workflows.v1.Workflows.DeleteWorkflow] - method. - name (:class:`str`): - Required. Name of the workflow to be - deleted. Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflows.DeleteWorkflowRequest): - request = workflows.DeleteWorkflowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workflow] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workflow(self, - request: Optional[Union[workflows.UpdateWorkflowRequest, dict]] = None, - *, - workflow: Optional[workflows.Workflow] = 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, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an existing workflow. - Running this method has no impact on already running - executions of the workflow. A new revision of the - workflow might be created as a result of a successful - update operation. In that case, the new revision is used - in new workflow executions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1 - - async def sample_update_workflow(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - workflow = workflows_v1.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1.UpdateWorkflowRequest( - workflow=workflow, - ) - - # Make the request - operation = client.update_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1.types.UpdateWorkflowRequest, dict]]): - The request object. Request for the - [UpdateWorkflow][google.cloud.workflows.v1.Workflows.UpdateWorkflow] - method. - workflow (:class:`google.cloud.workflows_v1.types.Workflow`): - Required. Workflow to be updated. - This corresponds to the ``workflow`` 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 to be updated. If not - present, the entire workflow will 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workflows_v1.types.Workflow` - Workflow program to be executed by Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workflow, 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, workflows.UpdateWorkflowRequest): - request = workflows.UpdateWorkflowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workflow is not None: - request.workflow = workflow - 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_workflow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workflow.name", request.workflow.name), - )), - ) - - # 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, - workflows.Workflow, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # 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.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_operations] - - # Certain fields should be provided within 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_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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # 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.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.delete_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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location 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 = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_location] - - # Certain fields should be provided within 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_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # 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 = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_locations] - - # Certain fields should be provided within 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) -> "WorkflowsAsyncClient": - 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__ = ( - "WorkflowsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/client.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/client.py deleted file mode 100644 index 8ecc9e6ba839..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/client.py +++ /dev/null @@ -1,1505 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.workflows_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 - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workflows_v1.services.workflows import pagers -from google.cloud.workflows_v1.types import workflows -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WorkflowsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WorkflowsGrpcTransport -from .transports.grpc_asyncio import WorkflowsGrpcAsyncIOTransport -from .transports.rest import WorkflowsRestTransport - - -class WorkflowsClientMeta(type): - """Metaclass for the Workflows 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[WorkflowsTransport]] - _transport_registry["grpc"] = WorkflowsGrpcTransport - _transport_registry["grpc_asyncio"] = WorkflowsGrpcAsyncIOTransport - _transport_registry["rest"] = WorkflowsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[WorkflowsTransport]: - """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 WorkflowsClient(metaclass=WorkflowsClientMeta): - """Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - """ - - @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 = "workflows.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "workflows.{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: - WorkflowsClient: 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: - WorkflowsClient: 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) -> WorkflowsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkflowsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def crypto_key_path(project: str,location: str,keyRing: str,cryptoKey: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}".format(project=project, location=location, keyRing=keyRing, cryptoKey=cryptoKey, ) - - @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: - """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workflow_path(project: str,location: str,workflow: str,) -> str: - """Returns a fully-qualified workflow string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - - @staticmethod - def parse_workflow_path(path: str) -> Dict[str,str]: - """Parses a workflow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = WorkflowsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = WorkflowsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = WorkflowsClient._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 = WorkflowsClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = WorkflowsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - WorkflowsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, WorkflowsTransport, Callable[..., WorkflowsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workflows client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,WorkflowsTransport,Callable[..., WorkflowsTransport]]]): - 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 WorkflowsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WorkflowsClient._read_environment_variables() - self._client_cert_source = WorkflowsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = WorkflowsClient._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 - - 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, WorkflowsTransport) - if transport_provided: - # transport is a WorkflowsTransport 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(WorkflowsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - WorkflowsClient._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[WorkflowsTransport], Callable[..., WorkflowsTransport]] = ( - WorkflowsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., WorkflowsTransport], 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, - ) - - def list_workflows(self, - request: Optional[Union[workflows.ListWorkflowsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkflowsPager: - r"""Lists workflows in a given project and location. - The default order is not specified. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1 - - def sample_list_workflows(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1.ListWorkflowsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workflows(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workflows_v1.types.ListWorkflowsRequest, dict]): - The request object. Request for the - [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] - method. - parent (str): - Required. Project and location from - which the workflows should be listed. - Format: - projects/{project}/locations/{location} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows_v1.services.workflows.pagers.ListWorkflowsPager: - Response for the - [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] - 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, workflows.ListWorkflowsRequest): - request = workflows.ListWorkflowsRequest(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_workflows] - - # Certain fields should be provided within 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.ListWorkflowsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_workflow(self, - request: Optional[Union[workflows.GetWorkflowRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workflows.Workflow: - r"""Gets details of a single workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1 - - def sample_get_workflow(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1.GetWorkflowRequest( - name="name_value", - ) - - # Make the request - response = client.get_workflow(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows_v1.types.GetWorkflowRequest, dict]): - The request object. Request for the - [GetWorkflow][google.cloud.workflows.v1.Workflows.GetWorkflow] - method. - name (str): - Required. Name of the workflow for - which information should be retrieved. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows_v1.types.Workflow: - Workflow program to be executed by - Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflows.GetWorkflowRequest): - request = workflows.GetWorkflowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workflow] - - # Certain fields should be provided within 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_workflow(self, - request: Optional[Union[workflows.CreateWorkflowRequest, dict]] = None, - *, - parent: Optional[str] = None, - workflow: Optional[workflows.Workflow] = None, - workflow_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workflow. If a workflow with the specified name - already exists in the specified project and location, the long - running operation returns a - [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] 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.cloud import workflows_v1 - - def sample_create_workflow(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - workflow = workflows_v1.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1.CreateWorkflowRequest( - parent="parent_value", - workflow=workflow, - workflow_id="workflow_id_value", - ) - - # Make the request - operation = client.create_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows_v1.types.CreateWorkflowRequest, dict]): - The request object. Request for the - [CreateWorkflow][google.cloud.workflows.v1.Workflows.CreateWorkflow] - method. - parent (str): - Required. Project and location in - which the workflow should be created. - Format: - projects/{project}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workflow (google.cloud.workflows_v1.types.Workflow): - Required. Workflow to be created. - This corresponds to the ``workflow`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workflow_id (str): - Required. The ID of the workflow to be created. It has - to fulfill the following requirements: - - - Must contain only letters, numbers, underscores and - hyphens. - - Must start with a letter. - - Must be between 1-64 characters. - - Must end with a number or a letter. - - Must be unique within the customer project and - location. - - This corresponds to the ``workflow_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workflows_v1.types.Workflow` - Workflow program to be executed by Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflow, workflow_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, workflows.CreateWorkflowRequest): - request = workflows.CreateWorkflowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workflow is not None: - request.workflow = workflow - if workflow_id is not None: - request.workflow_id = workflow_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workflow] - - # Certain fields should be provided within 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, - workflows.Workflow, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workflow(self, - request: Optional[Union[workflows.DeleteWorkflowRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a workflow with the specified name. - This method also cancels and deletes all running - executions of the workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1 - - def sample_delete_workflow(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1.DeleteWorkflowRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows_v1.types.DeleteWorkflowRequest, dict]): - The request object. Request for the - [DeleteWorkflow][google.cloud.workflows.v1.Workflows.DeleteWorkflow] - method. - name (str): - Required. Name of the workflow to be - deleted. Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflows.DeleteWorkflowRequest): - request = workflows.DeleteWorkflowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workflow] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workflow(self, - request: Optional[Union[workflows.UpdateWorkflowRequest, dict]] = None, - *, - workflow: Optional[workflows.Workflow] = 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, str]] = (), - ) -> operation.Operation: - r"""Updates an existing workflow. - Running this method has no impact on already running - executions of the workflow. A new revision of the - workflow might be created as a result of a successful - update operation. In that case, the new revision is used - in new workflow executions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1 - - def sample_update_workflow(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - workflow = workflows_v1.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1.UpdateWorkflowRequest( - workflow=workflow, - ) - - # Make the request - operation = client.update_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows_v1.types.UpdateWorkflowRequest, dict]): - The request object. Request for the - [UpdateWorkflow][google.cloud.workflows.v1.Workflows.UpdateWorkflow] - method. - workflow (google.cloud.workflows_v1.types.Workflow): - Required. Workflow to be updated. - This corresponds to the ``workflow`` 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 to be updated. If not - present, the entire workflow will 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workflows_v1.types.Workflow` - Workflow program to be executed by Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workflow, 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, workflows.UpdateWorkflowRequest): - request = workflows.UpdateWorkflowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workflow is not None: - request.workflow = workflow - 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_workflow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workflow.name", request.workflow.name), - )), - ) - - # 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, - workflows.Workflow, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "WorkflowsClient": - 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 list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.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. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # 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.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_operations] - - # Certain fields should be provided within 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_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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.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. - Returns: - None - """ - # 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.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.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. - Returns: - ~.location_pb2.Location: - Location 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 = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_location] - - # Certain fields should be provided within 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_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.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. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # 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 = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_locations] - - # Certain fields should be provided within 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__ = ( - "WorkflowsClient", -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/pagers.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/pagers.py deleted file mode 100644 index 06d0678baf04..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows_v1.types import workflows - - -class ListWorkflowsPager: - """A pager for iterating through ``list_workflows`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workflows_v1.types.ListWorkflowsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workflows`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkflows`` requests and continue to iterate - through the ``workflows`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workflows_v1.types.ListWorkflowsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workflows.ListWorkflowsResponse], - request: workflows.ListWorkflowsRequest, - response: workflows.ListWorkflowsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workflows_v1.types.ListWorkflowsRequest): - The initial request object. - response (google.cloud.workflows_v1.types.ListWorkflowsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workflows.ListWorkflowsRequest(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[workflows.ListWorkflowsResponse]: - 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[workflows.Workflow]: - for page in self.pages: - yield from page.workflows - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkflowsAsyncPager: - """A pager for iterating through ``list_workflows`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workflows_v1.types.ListWorkflowsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workflows`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkflows`` requests and continue to iterate - through the ``workflows`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workflows_v1.types.ListWorkflowsResponse` - attributes are available on the 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[workflows.ListWorkflowsResponse]], - request: workflows.ListWorkflowsRequest, - response: workflows.ListWorkflowsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workflows_v1.types.ListWorkflowsRequest): - The initial request object. - response (google.cloud.workflows_v1.types.ListWorkflowsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workflows.ListWorkflowsRequest(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[workflows.ListWorkflowsResponse]: - 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[workflows.Workflow]: - async def async_generator(): - async for page in self.pages: - for response in page.workflows: - 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-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/README.rst b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/README.rst deleted file mode 100644 index f8fb5a859227..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`WorkflowsTransport` is the ABC for all transports. -- public child `WorkflowsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `WorkflowsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseWorkflowsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `WorkflowsRestTransport` 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-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/__init__.py deleted file mode 100644 index 6ebe8b349db7..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/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 WorkflowsTransport -from .grpc import WorkflowsGrpcTransport -from .grpc_asyncio import WorkflowsGrpcAsyncIOTransport -from .rest import WorkflowsRestTransport -from .rest import WorkflowsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WorkflowsTransport]] -_transport_registry['grpc'] = WorkflowsGrpcTransport -_transport_registry['grpc_asyncio'] = WorkflowsGrpcAsyncIOTransport -_transport_registry['rest'] = WorkflowsRestTransport - -__all__ = ( - 'WorkflowsTransport', - 'WorkflowsGrpcTransport', - 'WorkflowsGrpcAsyncIOTransport', - 'WorkflowsRestTransport', - 'WorkflowsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/base.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/base.py deleted file mode 100644 index c21df987437e..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/base.py +++ /dev/null @@ -1,286 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows_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.cloud.location import locations_pb2 # type: ignore -from google.cloud.workflows_v1.types import workflows -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class WorkflowsTransport(abc.ABC): - """Abstract transport class for Workflows.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'workflows.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: 'workflows.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_workflows: gapic_v1.method.wrap_method( - self.list_workflows, - default_timeout=None, - client_info=client_info, - ), - self.get_workflow: gapic_v1.method.wrap_method( - self.get_workflow, - default_timeout=None, - client_info=client_info, - ), - self.create_workflow: gapic_v1.method.wrap_method( - self.create_workflow, - default_timeout=None, - client_info=client_info, - ), - self.delete_workflow: gapic_v1.method.wrap_method( - self.delete_workflow, - default_timeout=None, - client_info=client_info, - ), - self.update_workflow: gapic_v1.method.wrap_method( - self.update_workflow, - default_timeout=None, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - 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, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - 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 list_workflows(self) -> Callable[ - [workflows.ListWorkflowsRequest], - Union[ - workflows.ListWorkflowsResponse, - Awaitable[workflows.ListWorkflowsResponse] - ]]: - raise NotImplementedError() - - @property - def get_workflow(self) -> Callable[ - [workflows.GetWorkflowRequest], - Union[ - workflows.Workflow, - Awaitable[workflows.Workflow] - ]]: - raise NotImplementedError() - - @property - def create_workflow(self) -> Callable[ - [workflows.CreateWorkflowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workflow(self) -> Callable[ - [workflows.DeleteWorkflowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workflow(self) -> Callable[ - [workflows.UpdateWorkflowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'WorkflowsTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc.py deleted file mode 100644 index ed43a47b8790..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc.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 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 - -import grpc # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workflows_v1.types import workflows -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO - - -class WorkflowsGrpcTransport(WorkflowsTransport): - """gRPC backend transport for Workflows. - - Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workflows.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: 'workflows.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'workflows.googleapis.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.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_workflows(self) -> Callable[ - [workflows.ListWorkflowsRequest], - workflows.ListWorkflowsResponse]: - r"""Return a callable for the list workflows method over gRPC. - - Lists workflows in a given project and location. - The default order is not specified. - - Returns: - Callable[[~.ListWorkflowsRequest], - ~.ListWorkflowsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workflows' not in self._stubs: - self._stubs['list_workflows'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/ListWorkflows', - request_serializer=workflows.ListWorkflowsRequest.serialize, - response_deserializer=workflows.ListWorkflowsResponse.deserialize, - ) - return self._stubs['list_workflows'] - - @property - def get_workflow(self) -> Callable[ - [workflows.GetWorkflowRequest], - workflows.Workflow]: - r"""Return a callable for the get workflow method over gRPC. - - Gets details of a single workflow. - - Returns: - Callable[[~.GetWorkflowRequest], - ~.Workflow]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workflow' not in self._stubs: - self._stubs['get_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/GetWorkflow', - request_serializer=workflows.GetWorkflowRequest.serialize, - response_deserializer=workflows.Workflow.deserialize, - ) - return self._stubs['get_workflow'] - - @property - def create_workflow(self) -> Callable[ - [workflows.CreateWorkflowRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workflow method over gRPC. - - Creates a new workflow. If a workflow with the specified name - already exists in the specified project and location, the long - running operation returns a - [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error. - - Returns: - Callable[[~.CreateWorkflowRequest], - ~.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 'create_workflow' not in self._stubs: - self._stubs['create_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/CreateWorkflow', - request_serializer=workflows.CreateWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workflow'] - - @property - def delete_workflow(self) -> Callable[ - [workflows.DeleteWorkflowRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workflow method over gRPC. - - Deletes a workflow with the specified name. - This method also cancels and deletes all running - executions of the workflow. - - Returns: - Callable[[~.DeleteWorkflowRequest], - ~.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 'delete_workflow' not in self._stubs: - self._stubs['delete_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/DeleteWorkflow', - request_serializer=workflows.DeleteWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workflow'] - - @property - def update_workflow(self) -> Callable[ - [workflows.UpdateWorkflowRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workflow method over gRPC. - - Updates an existing workflow. - Running this method has no impact on already running - executions of the workflow. A new revision of the - workflow might be created as a result of a successful - update operation. In that case, the new revision is used - in new workflow executions. - - Returns: - Callable[[~.UpdateWorkflowRequest], - ~.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 'update_workflow' not in self._stubs: - self._stubs['update_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/UpdateWorkflow', - request_serializer=workflows.UpdateWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workflow'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @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.grpc_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 list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations 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 "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'WorkflowsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc_asyncio.py deleted file mode 100644 index 35ee7bb86bb5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/grpc_asyncio.py +++ /dev/null @@ -1,563 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workflows_v1.types import workflows -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO -from .grpc import WorkflowsGrpcTransport - - -class WorkflowsGrpcAsyncIOTransport(WorkflowsTransport): - """gRPC AsyncIO backend transport for Workflows. - - Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workflows.googleapis.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 = 'workflows.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: 'workflows.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_workflows(self) -> Callable[ - [workflows.ListWorkflowsRequest], - Awaitable[workflows.ListWorkflowsResponse]]: - r"""Return a callable for the list workflows method over gRPC. - - Lists workflows in a given project and location. - The default order is not specified. - - Returns: - Callable[[~.ListWorkflowsRequest], - Awaitable[~.ListWorkflowsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workflows' not in self._stubs: - self._stubs['list_workflows'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/ListWorkflows', - request_serializer=workflows.ListWorkflowsRequest.serialize, - response_deserializer=workflows.ListWorkflowsResponse.deserialize, - ) - return self._stubs['list_workflows'] - - @property - def get_workflow(self) -> Callable[ - [workflows.GetWorkflowRequest], - Awaitable[workflows.Workflow]]: - r"""Return a callable for the get workflow method over gRPC. - - Gets details of a single workflow. - - Returns: - Callable[[~.GetWorkflowRequest], - Awaitable[~.Workflow]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workflow' not in self._stubs: - self._stubs['get_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/GetWorkflow', - request_serializer=workflows.GetWorkflowRequest.serialize, - response_deserializer=workflows.Workflow.deserialize, - ) - return self._stubs['get_workflow'] - - @property - def create_workflow(self) -> Callable[ - [workflows.CreateWorkflowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workflow method over gRPC. - - Creates a new workflow. If a workflow with the specified name - already exists in the specified project and location, the long - running operation returns a - [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error. - - Returns: - Callable[[~.CreateWorkflowRequest], - 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 'create_workflow' not in self._stubs: - self._stubs['create_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/CreateWorkflow', - request_serializer=workflows.CreateWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workflow'] - - @property - def delete_workflow(self) -> Callable[ - [workflows.DeleteWorkflowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workflow method over gRPC. - - Deletes a workflow with the specified name. - This method also cancels and deletes all running - executions of the workflow. - - Returns: - Callable[[~.DeleteWorkflowRequest], - 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 'delete_workflow' not in self._stubs: - self._stubs['delete_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/DeleteWorkflow', - request_serializer=workflows.DeleteWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workflow'] - - @property - def update_workflow(self) -> Callable[ - [workflows.UpdateWorkflowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workflow method over gRPC. - - Updates an existing workflow. - Running this method has no impact on already running - executions of the workflow. A new revision of the - workflow might be created as a result of a successful - update operation. In that case, the new revision is used - in new workflow executions. - - Returns: - Callable[[~.UpdateWorkflowRequest], - 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 'update_workflow' not in self._stubs: - self._stubs['update_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1.Workflows/UpdateWorkflow', - request_serializer=workflows.UpdateWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workflow'] - - 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_workflows: self._wrap_method( - self.list_workflows, - default_timeout=None, - client_info=client_info, - ), - self.get_workflow: self._wrap_method( - self.get_workflow, - default_timeout=None, - client_info=client_info, - ), - self.create_workflow: self._wrap_method( - self.create_workflow, - default_timeout=None, - client_info=client_info, - ), - self.delete_workflow: self._wrap_method( - self.delete_workflow, - default_timeout=None, - client_info=client_info, - ), - self.update_workflow: self._wrap_method( - self.update_workflow, - default_timeout=None, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @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.grpc_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 list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations 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 "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'WorkflowsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest.py deleted file mode 100644 index 6e27a172c865..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest.py +++ /dev/null @@ -1,1224 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.workflows_v1.types import workflows -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseWorkflowsRestTransport -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 - - -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 WorkflowsRestInterceptor: - """Interceptor for Workflows. - - 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 WorkflowsRestTransport. - - .. code-block:: python - class MyCustomWorkflowsInterceptor(WorkflowsRestInterceptor): - def pre_create_workflow(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workflow(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workflow(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workflow(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workflow(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workflow(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workflows(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workflows(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workflow(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workflow(self, response): - logging.log(f"Received response: {response}") - return response - - transport = WorkflowsRestTransport(interceptor=MyCustomWorkflowsInterceptor()) - client = WorkflowsClient(transport=transport) - - - """ - def pre_create_workflow(self, request: workflows.CreateWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.CreateWorkflowRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workflow - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_create_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workflow - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_delete_workflow(self, request: workflows.DeleteWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.DeleteWorkflowRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workflow - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_delete_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workflow - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_get_workflow(self, request: workflows.GetWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.GetWorkflowRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workflow - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_get_workflow(self, response: workflows.Workflow) -> workflows.Workflow: - """Post-rpc interceptor for get_workflow - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_list_workflows(self, request: workflows.ListWorkflowsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.ListWorkflowsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workflows - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_list_workflows(self, response: workflows.ListWorkflowsResponse) -> workflows.ListWorkflowsResponse: - """Post-rpc interceptor for list_workflows - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_update_workflow(self, request: workflows.UpdateWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.UpdateWorkflowRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workflow - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_update_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workflow - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows 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 Workflows server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class WorkflowsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: WorkflowsRestInterceptor - - -class WorkflowsRestTransport(_BaseWorkflowsRestTransport): - """REST backend synchronous transport for Workflows. - - Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'workflows.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[WorkflowsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'workflows.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 WorkflowsRestInterceptor() - 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.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - '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 _CreateWorkflow(_BaseWorkflowsRestTransport._BaseCreateWorkflow, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.CreateWorkflow") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workflows.CreateWorkflowRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workflow method over HTTP. - - Args: - request (~.workflows.CreateWorkflowRequest): - The request object. Request for the - [CreateWorkflow][google.cloud.workflows.v1.Workflows.CreateWorkflow] - method. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_http_options() - request, metadata = self._interceptor.pre_create_workflow(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_transcoded_request(http_options, request) - - body = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._CreateWorkflow._get_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_create_workflow(resp) - return resp - - class _DeleteWorkflow(_BaseWorkflowsRestTransport._BaseDeleteWorkflow, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.DeleteWorkflow") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workflows.DeleteWorkflowRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workflow method over HTTP. - - Args: - request (~.workflows.DeleteWorkflowRequest): - The request object. Request for the - [DeleteWorkflow][google.cloud.workflows.v1.Workflows.DeleteWorkflow] - method. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_http_options() - request, metadata = self._interceptor.pre_delete_workflow(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._DeleteWorkflow._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, 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_delete_workflow(resp) - return resp - - class _GetWorkflow(_BaseWorkflowsRestTransport._BaseGetWorkflow, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.GetWorkflow") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workflows.GetWorkflowRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workflows.Workflow: - r"""Call the get workflow method over HTTP. - - Args: - request (~.workflows.GetWorkflowRequest): - The request object. Request for the - [GetWorkflow][google.cloud.workflows.v1.Workflows.GetWorkflow] - method. - retry (google.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. - - Returns: - ~.workflows.Workflow: - Workflow program to be executed by - Workflows. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_http_options() - request, metadata = self._interceptor.pre_get_workflow(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._GetWorkflow._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workflows.Workflow() - pb_resp = workflows.Workflow.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workflow(resp) - return resp - - class _ListWorkflows(_BaseWorkflowsRestTransport._BaseListWorkflows, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.ListWorkflows") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workflows.ListWorkflowsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workflows.ListWorkflowsResponse: - r"""Call the list workflows method over HTTP. - - Args: - request (~.workflows.ListWorkflowsRequest): - The request object. Request for the - [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] - method. - retry (google.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. - - Returns: - ~.workflows.ListWorkflowsResponse: - Response for the - [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] - method. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseListWorkflows._get_http_options() - request, metadata = self._interceptor.pre_list_workflows(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseListWorkflows._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseListWorkflows._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._ListWorkflows._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workflows.ListWorkflowsResponse() - pb_resp = workflows.ListWorkflowsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workflows(resp) - return resp - - class _UpdateWorkflow(_BaseWorkflowsRestTransport._BaseUpdateWorkflow, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.UpdateWorkflow") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workflows.UpdateWorkflowRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workflow method over HTTP. - - Args: - request (~.workflows.UpdateWorkflowRequest): - The request object. Request for the - [UpdateWorkflow][google.cloud.workflows.v1.Workflows.UpdateWorkflow] - method. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_http_options() - request, metadata = self._interceptor.pre_update_workflow(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_transcoded_request(http_options, request) - - body = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._UpdateWorkflow._get_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_update_workflow(resp) - return resp - - @property - def create_workflow(self) -> Callable[ - [workflows.CreateWorkflowRequest], - 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._CreateWorkflow(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workflow(self) -> Callable[ - [workflows.DeleteWorkflowRequest], - 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._DeleteWorkflow(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workflow(self) -> Callable[ - [workflows.GetWorkflowRequest], - workflows.Workflow]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkflow(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workflows(self) -> Callable[ - [workflows.ListWorkflowsRequest], - workflows.ListWorkflowsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkflows(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workflow(self) -> Callable[ - [workflows.UpdateWorkflowRequest], - 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._UpdateWorkflow(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseWorkflowsRestTransport._BaseGetLocation, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.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. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseWorkflowsRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseWorkflowsRestTransport._BaseListLocations, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.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. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseWorkflowsRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseWorkflowsRestTransport._BaseDeleteOperation, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(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.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.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. - """ - - http_options = _BaseWorkflowsRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseWorkflowsRestTransport._BaseGetOperation, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseWorkflowsRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._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) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseWorkflowsRestTransport._BaseListOperations, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(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.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.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. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseWorkflowsRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'WorkflowsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest_base.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest_base.py deleted file mode 100644 index 903728571d5d..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/services/workflows/transports/rest_base.py +++ /dev/null @@ -1,423 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 google.cloud.location import locations_pb2 # type: ignore -from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.workflows_v1.types import workflows -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseWorkflowsRestTransport(WorkflowsTransport): - """Base REST backend transport for Workflows. - - 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 = 'workflows.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: 'workflows.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 _BaseCreateWorkflow: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workflowId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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/*}/workflows', - 'body': 'workflow', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.CreateWorkflowRequest.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(_BaseWorkflowsRestTransport._BaseCreateWorkflow._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteWorkflow: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/workflows/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.DeleteWorkflowRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetWorkflow: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/workflows/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.GetWorkflowRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkflowsRestTransport._BaseGetWorkflow._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkflows: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/workflows', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.ListWorkflowsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkflowsRestTransport._BaseListWorkflows._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateWorkflow: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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/{workflow.name=projects/*/locations/*/workflows/*}', - 'body': 'workflow', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.UpdateWorkflowRequest.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(_BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - 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/*}', - }, - ] - 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 - - class _BaseListLocations: - 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', - }, - ] - 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 - - class _BaseDeleteOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - '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 - - 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 - - class _BaseListOperations: - 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__=( - '_BaseWorkflowsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/__init__.py deleted file mode 100644 index 99bb09e40279..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/__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 .workflows import ( - CreateWorkflowRequest, - DeleteWorkflowRequest, - GetWorkflowRequest, - ListWorkflowsRequest, - ListWorkflowsResponse, - OperationMetadata, - UpdateWorkflowRequest, - Workflow, -) - -__all__ = ( - 'CreateWorkflowRequest', - 'DeleteWorkflowRequest', - 'GetWorkflowRequest', - 'ListWorkflowsRequest', - 'ListWorkflowsResponse', - 'OperationMetadata', - 'UpdateWorkflowRequest', - 'Workflow', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/workflows.py b/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/workflows.py deleted file mode 100644 index 65ed8d6c80f9..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/google/cloud/workflows_v1/types/workflows.py +++ /dev/null @@ -1,521 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.workflows.v1', - manifest={ - 'Workflow', - 'ListWorkflowsRequest', - 'ListWorkflowsResponse', - 'GetWorkflowRequest', - 'CreateWorkflowRequest', - 'DeleteWorkflowRequest', - 'UpdateWorkflowRequest', - 'OperationMetadata', - }, -) - - -class Workflow(proto.Message): - r"""Workflow program to be executed by Workflows. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The resource name of the workflow. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - description (str): - Description of the workflow provided by the - user. Must be at most 1000 unicode characters - long. - state (google.cloud.workflows_v1.types.Workflow.State): - Output only. State of the workflow - deployment. - revision_id (str): - Output only. The revision of the workflow. A new revision of - a workflow is created as a result of updating the following - properties of a workflow: - - - [Service - account][google.cloud.workflows.v1.Workflow.service_account] - - [Workflow code to be - executed][google.cloud.workflows.v1.Workflow.source_contents] - - The format is "000001-a4d", where the first six characters - define the zero-padded revision ordinal number. They are - followed by a hyphen and three hexadecimal random - characters. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp for when the - workflow was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp for when the - workflow was last updated. - revision_create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp for the latest - revision of the workflow's creation. - labels (MutableMapping[str, str]): - Labels associated with this workflow. - Labels can contain at most 64 entries. Keys and - values can be no longer than 63 characters and - can only contain lowercase letters, numeric - characters, underscores, and dashes. Label keys - must start with a letter. International - characters are allowed. - service_account (str): - The service account associated with the latest workflow - version. This service account represents the identity of the - workflow and determines what permissions the workflow has. - Format: projects/{project}/serviceAccounts/{account} or - {account} - - Using ``-`` as a wildcard for the ``{project}`` or not - providing one at all will infer the project from the - account. The ``{account}`` value can be the ``email`` - address or the ``unique_id`` of the service account. - - If not provided, workflow will use the project's default - service account. Modifying this field for an existing - workflow results in a new workflow revision. - source_contents (str): - Workflow code to be executed. The size limit - is 128KB. - - This field is a member of `oneof`_ ``source_code``. - crypto_key_name (str): - Optional. The resource name of a KMS crypto key used to - encrypt or decrypt the data associated with the workflow. - - Format: - projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey} - - Using ``-`` as a wildcard for the ``{project}`` or not - providing one at all will infer the project from the - account. - - If not provided, data associated with the workflow will not - be CMEK-encrypted. - state_error (google.cloud.workflows_v1.types.Workflow.StateError): - Output only. Error regarding the state of the - workflow. For example, this field will have - error details if the execution data is - unavailable due to revoked KMS key permissions. - call_log_level (google.cloud.workflows_v1.types.Workflow.CallLogLevel): - Optional. Describes the level of platform - logging to apply to calls and call responses - during executions of this workflow. If both the - workflow and the execution specify a logging - level, the execution level takes precedence. - user_env_vars (MutableMapping[str, str]): - Optional. User-defined environment variables - associated with this workflow revision. This map - has a maximum length of 20. Each string can take - up to 40KiB. Keys cannot be empty strings and - cannot start with “GOOGLE” or “WORKFLOWS". - """ - class State(proto.Enum): - r"""Describes the current state of workflow deployment. - - Values: - STATE_UNSPECIFIED (0): - Invalid state. - ACTIVE (1): - The workflow has been deployed successfully - and is serving. - UNAVAILABLE (2): - Workflow data is unavailable. See the ``state_error`` field. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - UNAVAILABLE = 2 - - class CallLogLevel(proto.Enum): - r"""Describes the level of platform logging to apply to calls and - call responses during workflow executions. - - Values: - CALL_LOG_LEVEL_UNSPECIFIED (0): - No call logging level specified. - LOG_ALL_CALLS (1): - Log all call steps within workflows, all call - returns, and all exceptions raised. - LOG_ERRORS_ONLY (2): - Log only exceptions that are raised from call - steps within workflows. - LOG_NONE (3): - Explicitly log nothing. - """ - CALL_LOG_LEVEL_UNSPECIFIED = 0 - LOG_ALL_CALLS = 1 - LOG_ERRORS_ONLY = 2 - LOG_NONE = 3 - - class StateError(proto.Message): - r"""Describes an error related to the current state of the - workflow. - - Attributes: - details (str): - Provides specifics about the error. - type_ (google.cloud.workflows_v1.types.Workflow.StateError.Type): - The type of this state error. - """ - class Type(proto.Enum): - r"""Describes the possibled types of a state error. - - Values: - TYPE_UNSPECIFIED (0): - No type specified. - KMS_ERROR (1): - Caused by an issue with KMS. - """ - TYPE_UNSPECIFIED = 0 - KMS_ERROR = 1 - - details: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'Workflow.StateError.Type' = proto.Field( - proto.ENUM, - number=2, - enum='Workflow.StateError.Type', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - state: State = proto.Field( - proto.ENUM, - number=3, - enum=State, - ) - revision_id: str = proto.Field( - proto.STRING, - number=4, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - revision_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - service_account: str = proto.Field( - proto.STRING, - number=9, - ) - source_contents: str = proto.Field( - proto.STRING, - number=10, - oneof='source_code', - ) - crypto_key_name: str = proto.Field( - proto.STRING, - number=11, - ) - state_error: StateError = proto.Field( - proto.MESSAGE, - number=12, - message=StateError, - ) - call_log_level: CallLogLevel = proto.Field( - proto.ENUM, - number=13, - enum=CallLogLevel, - ) - user_env_vars: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - - -class ListWorkflowsRequest(proto.Message): - r"""Request for the - [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] - method. - - Attributes: - parent (str): - Required. Project and location from which the - workflows should be listed. Format: - projects/{project}/locations/{location} - page_size (int): - Maximum number of workflows to return per - call. The service might return fewer than this - value even if not at the end of the collection. - If a value is not specified, a default value of - 500 is used. The maximum permitted value is 1000 - and values greater than 1000 are coerced down to - 1000. - page_token (str): - A page token, received from a previous ``ListWorkflows`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListWorkflows`` must match the call that provided the page - token. - filter (str): - Filter to restrict results to specific - workflows. - order_by (str): - Comma-separated list of fields that specify - the order of the results. Default sorting order - for a field is ascending. To specify descending - order for a field, append a "desc" suffix. - If not specified, the results are returned in an - unspecified order. - """ - - 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, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListWorkflowsResponse(proto.Message): - r"""Response for the - [ListWorkflows][google.cloud.workflows.v1.Workflows.ListWorkflows] - method. - - Attributes: - workflows (MutableSequence[google.cloud.workflows_v1.types.Workflow]): - The workflows that match the request. - 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. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workflows: MutableSequence['Workflow'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workflow', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetWorkflowRequest(proto.Message): - r"""Request for the - [GetWorkflow][google.cloud.workflows.v1.Workflows.GetWorkflow] - method. - - Attributes: - name (str): - Required. Name of the workflow for which - information should be retrieved. Format: - projects/{project}/locations/{location}/workflows/{workflow} - revision_id (str): - Optional. The revision of the workflow to retrieve. If the - revision_id is empty, the latest revision is retrieved. The - format is "000001-a4d", where the first six characters - define the zero-padded decimal revision number. They are - followed by a hyphen and three hexadecimal characters. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateWorkflowRequest(proto.Message): - r"""Request for the - [CreateWorkflow][google.cloud.workflows.v1.Workflows.CreateWorkflow] - method. - - Attributes: - parent (str): - Required. Project and location in which the - workflow should be created. Format: - projects/{project}/locations/{location} - workflow (google.cloud.workflows_v1.types.Workflow): - Required. Workflow to be created. - workflow_id (str): - Required. The ID of the workflow to be created. It has to - fulfill the following requirements: - - - Must contain only letters, numbers, underscores and - hyphens. - - Must start with a letter. - - Must be between 1-64 characters. - - Must end with a number or a letter. - - Must be unique within the customer project and location. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workflow: 'Workflow' = proto.Field( - proto.MESSAGE, - number=2, - message='Workflow', - ) - workflow_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteWorkflowRequest(proto.Message): - r"""Request for the - [DeleteWorkflow][google.cloud.workflows.v1.Workflows.DeleteWorkflow] - method. - - Attributes: - name (str): - Required. Name of the workflow to be deleted. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateWorkflowRequest(proto.Message): - r"""Request for the - [UpdateWorkflow][google.cloud.workflows.v1.Workflows.UpdateWorkflow] - method. - - Attributes: - workflow (google.cloud.workflows_v1.types.Workflow): - Required. Workflow to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - List of fields to be updated. If not present, - the entire workflow will be updated. - """ - - workflow: 'Workflow' = proto.Field( - proto.MESSAGE, - number=1, - message='Workflow', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class OperationMetadata(proto.Message): - r"""Represents the metadata of the long-running operation. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time the operation was created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time the operation finished running. - target (str): - Server-defined resource path for the target - of the operation. - verb (str): - Name of the verb executed by the operation. - api_version (str): - API version used to start the operation. - """ - - create_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, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - api_version: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workflows/v1/mypy.ini b/owl-bot-staging/google-cloud-workflows/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workflows/v1/noxfile.py b/owl-bot-staging/google-cloud-workflows/v1/noxfile.py deleted file mode 100644 index f3df2d3da03f..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows' - -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/cloud/workflows_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/cloud/workflows_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-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json deleted file mode 100644 index 56d60ff5a803..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json +++ /dev/null @@ -1,667 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.workflows.executions.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-workflows-executions", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient", - "shortName": "ExecutionsAsyncClient" - }, - "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient.cancel_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1.Executions.CancelExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1.Executions", - "shortName": "Executions" - }, - "shortName": "CancelExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1.types.CancelExecutionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1.types.Execution", - "shortName": "cancel_execution" - }, - "description": "Sample for CancelExecution", - "file": "workflowexecutions_v1_generated_executions_cancel_execution_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1_generated_Executions_CancelExecution_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": "workflowexecutions_v1_generated_executions_cancel_execution_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient", - "shortName": "ExecutionsClient" - }, - "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient.cancel_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1.Executions.CancelExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1.Executions", - "shortName": "Executions" - }, - "shortName": "CancelExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1.types.CancelExecutionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1.types.Execution", - "shortName": "cancel_execution" - }, - "description": "Sample for CancelExecution", - "file": "workflowexecutions_v1_generated_executions_cancel_execution_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1_generated_Executions_CancelExecution_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": "workflowexecutions_v1_generated_executions_cancel_execution_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient", - "shortName": "ExecutionsAsyncClient" - }, - "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient.create_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1.Executions.CreateExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1.Executions", - "shortName": "Executions" - }, - "shortName": "CreateExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1.types.CreateExecutionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "execution", - "type": "google.cloud.workflows.executions_v1.types.Execution" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1.types.Execution", - "shortName": "create_execution" - }, - "description": "Sample for CreateExecution", - "file": "workflowexecutions_v1_generated_executions_create_execution_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1_generated_Executions_CreateExecution_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": "workflowexecutions_v1_generated_executions_create_execution_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient", - "shortName": "ExecutionsClient" - }, - "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient.create_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1.Executions.CreateExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1.Executions", - "shortName": "Executions" - }, - "shortName": "CreateExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1.types.CreateExecutionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "execution", - "type": "google.cloud.workflows.executions_v1.types.Execution" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1.types.Execution", - "shortName": "create_execution" - }, - "description": "Sample for CreateExecution", - "file": "workflowexecutions_v1_generated_executions_create_execution_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1_generated_Executions_CreateExecution_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": "workflowexecutions_v1_generated_executions_create_execution_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient", - "shortName": "ExecutionsAsyncClient" - }, - "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient.get_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1.Executions.GetExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1.Executions", - "shortName": "Executions" - }, - "shortName": "GetExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1.types.GetExecutionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1.types.Execution", - "shortName": "get_execution" - }, - "description": "Sample for GetExecution", - "file": "workflowexecutions_v1_generated_executions_get_execution_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1_generated_Executions_GetExecution_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": "workflowexecutions_v1_generated_executions_get_execution_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient", - "shortName": "ExecutionsClient" - }, - "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient.get_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1.Executions.GetExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1.Executions", - "shortName": "Executions" - }, - "shortName": "GetExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1.types.GetExecutionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1.types.Execution", - "shortName": "get_execution" - }, - "description": "Sample for GetExecution", - "file": "workflowexecutions_v1_generated_executions_get_execution_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1_generated_Executions_GetExecution_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": "workflowexecutions_v1_generated_executions_get_execution_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient", - "shortName": "ExecutionsAsyncClient" - }, - "fullName": "google.cloud.workflows.executions_v1.ExecutionsAsyncClient.list_executions", - "method": { - "fullName": "google.cloud.workflows.executions.v1.Executions.ListExecutions", - "service": { - "fullName": "google.cloud.workflows.executions.v1.Executions", - "shortName": "Executions" - }, - "shortName": "ListExecutions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1.types.ListExecutionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1.services.executions.pagers.ListExecutionsAsyncPager", - "shortName": "list_executions" - }, - "description": "Sample for ListExecutions", - "file": "workflowexecutions_v1_generated_executions_list_executions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1_generated_Executions_ListExecutions_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": "workflowexecutions_v1_generated_executions_list_executions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient", - "shortName": "ExecutionsClient" - }, - "fullName": "google.cloud.workflows.executions_v1.ExecutionsClient.list_executions", - "method": { - "fullName": "google.cloud.workflows.executions.v1.Executions.ListExecutions", - "service": { - "fullName": "google.cloud.workflows.executions.v1.Executions", - "shortName": "Executions" - }, - "shortName": "ListExecutions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1.types.ListExecutionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1.services.executions.pagers.ListExecutionsPager", - "shortName": "list_executions" - }, - "description": "Sample for ListExecutions", - "file": "workflowexecutions_v1_generated_executions_list_executions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1_generated_Executions_ListExecutions_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": "workflowexecutions_v1_generated_executions_list_executions_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json deleted file mode 100644 index 5eeb3c21a076..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json +++ /dev/null @@ -1,844 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.workflows.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-workflows", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.create_workflow", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.CreateWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "CreateWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.CreateWorkflowRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workflow", - "type": "google.cloud.workflows_v1.types.Workflow" - }, - { - "name": "workflow_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workflow" - }, - "description": "Sample for CreateWorkflow", - "file": "workflows_v1_generated_workflows_create_workflow_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_CreateWorkflow_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1_generated_workflows_create_workflow_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsClient.create_workflow", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.CreateWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "CreateWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.CreateWorkflowRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workflow", - "type": "google.cloud.workflows_v1.types.Workflow" - }, - { - "name": "workflow_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workflow" - }, - "description": "Sample for CreateWorkflow", - "file": "workflows_v1_generated_workflows_create_workflow_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_CreateWorkflow_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1_generated_workflows_create_workflow_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.delete_workflow", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.DeleteWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "DeleteWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.DeleteWorkflowRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_workflow" - }, - "description": "Sample for DeleteWorkflow", - "file": "workflows_v1_generated_workflows_delete_workflow_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_DeleteWorkflow_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1_generated_workflows_delete_workflow_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsClient.delete_workflow", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.DeleteWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "DeleteWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.DeleteWorkflowRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_workflow" - }, - "description": "Sample for DeleteWorkflow", - "file": "workflows_v1_generated_workflows_delete_workflow_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_DeleteWorkflow_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1_generated_workflows_delete_workflow_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.get_workflow", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.GetWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "GetWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.GetWorkflowRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows_v1.types.Workflow", - "shortName": "get_workflow" - }, - "description": "Sample for GetWorkflow", - "file": "workflows_v1_generated_workflows_get_workflow_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_GetWorkflow_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": "workflows_v1_generated_workflows_get_workflow_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsClient.get_workflow", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.GetWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "GetWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.GetWorkflowRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows_v1.types.Workflow", - "shortName": "get_workflow" - }, - "description": "Sample for GetWorkflow", - "file": "workflows_v1_generated_workflows_get_workflow_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_GetWorkflow_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": "workflows_v1_generated_workflows_get_workflow_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.list_workflows", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.ListWorkflows", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "ListWorkflows" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.ListWorkflowsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows_v1.services.workflows.pagers.ListWorkflowsAsyncPager", - "shortName": "list_workflows" - }, - "description": "Sample for ListWorkflows", - "file": "workflows_v1_generated_workflows_list_workflows_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_ListWorkflows_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": "workflows_v1_generated_workflows_list_workflows_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsClient.list_workflows", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.ListWorkflows", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "ListWorkflows" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.ListWorkflowsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows_v1.services.workflows.pagers.ListWorkflowsPager", - "shortName": "list_workflows" - }, - "description": "Sample for ListWorkflows", - "file": "workflows_v1_generated_workflows_list_workflows_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_ListWorkflows_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": "workflows_v1_generated_workflows_list_workflows_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsAsyncClient.update_workflow", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.UpdateWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "UpdateWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.UpdateWorkflowRequest" - }, - { - "name": "workflow", - "type": "google.cloud.workflows_v1.types.Workflow" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_workflow" - }, - "description": "Sample for UpdateWorkflow", - "file": "workflows_v1_generated_workflows_update_workflow_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_UpdateWorkflow_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1_generated_workflows_update_workflow_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1.WorkflowsClient.update_workflow", - "method": { - "fullName": "google.cloud.workflows.v1.Workflows.UpdateWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1.Workflows", - "shortName": "Workflows" - }, - "shortName": "UpdateWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1.types.UpdateWorkflowRequest" - }, - { - "name": "workflow", - "type": "google.cloud.workflows_v1.types.Workflow" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_workflow" - }, - "description": "Sample for UpdateWorkflow", - "file": "workflows_v1_generated_workflows_update_workflow_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1_generated_Workflows_UpdateWorkflow_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1_generated_workflows_update_workflow_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_async.py deleted file mode 100644 index 70726dd616f3..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_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 CancelExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1_generated_Executions_CancelExecution_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1 - - -async def sample_cancel_execution(): - # Create a client - client = executions_v1.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1.CancelExecutionRequest( - name="name_value", - ) - - # Make the request - response = await client.cancel_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1_generated_Executions_CancelExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_sync.py deleted file mode 100644 index 44a8e8b3265c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_cancel_execution_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 CancelExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1_generated_Executions_CancelExecution_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1 - - -def sample_cancel_execution(): - # Create a client - client = executions_v1.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1.CancelExecutionRequest( - name="name_value", - ) - - # Make the request - response = client.cancel_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1_generated_Executions_CancelExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_async.py deleted file mode 100644 index e95cb22413cb..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_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 CreateExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1_generated_Executions_CreateExecution_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1 - - -async def sample_create_execution(): - # Create a client - client = executions_v1.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1.CreateExecutionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1_generated_Executions_CreateExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_sync.py deleted file mode 100644 index 684ddb237758..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_create_execution_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 CreateExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1_generated_Executions_CreateExecution_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1 - - -def sample_create_execution(): - # Create a client - client = executions_v1.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1.CreateExecutionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1_generated_Executions_CreateExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_async.py deleted file mode 100644 index adb49fe0566e..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_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 GetExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1_generated_Executions_GetExecution_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1 - - -async def sample_get_execution(): - # Create a client - client = executions_v1.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1.GetExecutionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1_generated_Executions_GetExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_sync.py deleted file mode 100644 index 37918ba4ecad..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_get_execution_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 GetExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1_generated_Executions_GetExecution_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1 - - -def sample_get_execution(): - # Create a client - client = executions_v1.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1.GetExecutionRequest( - name="name_value", - ) - - # Make the request - response = client.get_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1_generated_Executions_GetExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_async.py deleted file mode 100644 index 5bb5f579dc64..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_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 ListExecutions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1_generated_Executions_ListExecutions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1 - - -async def sample_list_executions(): - # Create a client - client = executions_v1.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1.ListExecutionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_executions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workflowexecutions_v1_generated_Executions_ListExecutions_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_sync.py deleted file mode 100644 index aef66f516ec6..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflowexecutions_v1_generated_executions_list_executions_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 ListExecutions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1_generated_Executions_ListExecutions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1 - - -def sample_list_executions(): - # Create a client - client = executions_v1.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1.ListExecutionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_executions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workflowexecutions_v1_generated_Executions_ListExecutions_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_async.py deleted file mode 100644 index 69925ef10858..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_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 CreateWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_CreateWorkflow_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -async def sample_create_workflow(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - workflow = workflows_v1.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1.CreateWorkflowRequest( - parent="parent_value", - workflow=workflow, - workflow_id="workflow_id_value", - ) - - # Make the request - operation = client.create_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workflows_v1_generated_Workflows_CreateWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_sync.py deleted file mode 100644 index 0c1375b6afcb..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_create_workflow_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 CreateWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_CreateWorkflow_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -def sample_create_workflow(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - workflow = workflows_v1.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1.CreateWorkflowRequest( - parent="parent_value", - workflow=workflow, - workflow_id="workflow_id_value", - ) - - # Make the request - operation = client.create_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workflows_v1_generated_Workflows_CreateWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_async.py deleted file mode 100644 index dbf035cdd5ef..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_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 DeleteWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_DeleteWorkflow_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -async def sample_delete_workflow(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1.DeleteWorkflowRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workflows_v1_generated_Workflows_DeleteWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_sync.py deleted file mode 100644 index 05ec4c2ee70d..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_delete_workflow_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 DeleteWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_DeleteWorkflow_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -def sample_delete_workflow(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1.DeleteWorkflowRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workflows_v1_generated_Workflows_DeleteWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_async.py deleted file mode 100644 index 27366a2d667a..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_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 GetWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_GetWorkflow_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -async def sample_get_workflow(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1.GetWorkflowRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workflow(request=request) - - # Handle the response - print(response) - -# [END workflows_v1_generated_Workflows_GetWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_sync.py deleted file mode 100644 index 0b61ebe8dafe..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_get_workflow_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 GetWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_GetWorkflow_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -def sample_get_workflow(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1.GetWorkflowRequest( - name="name_value", - ) - - # Make the request - response = client.get_workflow(request=request) - - # Handle the response - print(response) - -# [END workflows_v1_generated_Workflows_GetWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_async.py deleted file mode 100644 index 63dbaf332e23..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_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 ListWorkflows -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_ListWorkflows_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -async def sample_list_workflows(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1.ListWorkflowsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workflows(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workflows_v1_generated_Workflows_ListWorkflows_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_sync.py deleted file mode 100644 index 90302cc27677..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_list_workflows_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 ListWorkflows -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_ListWorkflows_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -def sample_list_workflows(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1.ListWorkflowsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workflows(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workflows_v1_generated_Workflows_ListWorkflows_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_async.py deleted file mode 100644 index 8710eec78578..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_UpdateWorkflow_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -async def sample_update_workflow(): - # Create a client - client = workflows_v1.WorkflowsAsyncClient() - - # Initialize request argument(s) - workflow = workflows_v1.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1.UpdateWorkflowRequest( - workflow=workflow, - ) - - # Make the request - operation = client.update_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workflows_v1_generated_Workflows_UpdateWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_sync.py deleted file mode 100644 index 7c5223fc3dd5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/samples/generated_samples/workflows_v1_generated_workflows_update_workflow_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1_generated_Workflows_UpdateWorkflow_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1 - - -def sample_update_workflow(): - # Create a client - client = workflows_v1.WorkflowsClient() - - # Initialize request argument(s) - workflow = workflows_v1.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1.UpdateWorkflowRequest( - workflow=workflow, - ) - - # Make the request - operation = client.update_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workflows_v1_generated_Workflows_UpdateWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_executions_v1_keywords.py b/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_executions_v1_keywords.py deleted file mode 100644 index 5bce5db0132c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_executions_v1_keywords.py +++ /dev/null @@ -1,179 +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 executionsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'cancel_execution': ('name', ), - 'create_execution': ('parent', 'execution', ), - 'get_execution': ('name', 'view', ), - 'list_executions': ('parent', 'page_size', 'page_token', 'view', 'filter', 'order_by', ), - } - - 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=executionsCallTransformer(), -): - """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 executions 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-cloud-workflows/v1/scripts/fixup_workflows_v1_keywords.py b/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_workflows_v1_keywords.py deleted file mode 100644 index 3c1bc914fff8..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/scripts/fixup_workflows_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 workflowsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_workflow': ('parent', 'workflow', 'workflow_id', ), - 'delete_workflow': ('name', ), - 'get_workflow': ('name', 'revision_id', ), - 'list_workflows': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'update_workflow': ('workflow', '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=workflowsCallTransformer(), -): - """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 workflows 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-cloud-workflows/v1/setup.py b/owl-bot-staging/google-cloud-workflows/v1/setup.py deleted file mode 100644 index 85ca80f0b4ea..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows' - - -description = "Google Cloud Workflows API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/workflows/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-cloud-workflows" - -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-cloud-workflows/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/tests/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1/tests/unit/gapic/executions_v1/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_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-cloud-workflows/v1/tests/unit/gapic/executions_v1/test_executions.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/test_executions.py deleted file mode 100644 index ee1bf4b2cc95..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/executions_v1/test_executions.py +++ /dev/null @@ -1,3165 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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.cloud.workflows.executions_v1.services.executions import ExecutionsAsyncClient -from google.cloud.workflows.executions_v1.services.executions import ExecutionsClient -from google.cloud.workflows.executions_v1.services.executions import pagers -from google.cloud.workflows.executions_v1.services.executions import transports -from google.cloud.workflows.executions_v1.types import executions -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_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 ExecutionsClient._get_default_mtls_endpoint(None) is None - assert ExecutionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ExecutionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ExecutionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ExecutionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ExecutionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ExecutionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ExecutionsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ExecutionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ExecutionsClient._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 ExecutionsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ExecutionsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ExecutionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ExecutionsClient._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 ExecutionsClient._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 ExecutionsClient._get_client_cert_source(None, False) is None - assert ExecutionsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ExecutionsClient._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 ExecutionsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ExecutionsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ExecutionsClient._DEFAULT_UNIVERSE - default_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ExecutionsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ExecutionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT - assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "always") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT - assert ExecutionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT - assert ExecutionsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ExecutionsClient._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 ExecutionsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ExecutionsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ExecutionsClient._get_universe_domain(None, None) == ExecutionsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ExecutionsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ExecutionsClient, "grpc"), - (ExecutionsAsyncClient, "grpc_asyncio"), -]) -def test_executions_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 == ( - 'workflowexecutions.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ExecutionsGrpcTransport, "grpc"), - (transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_executions_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", [ - (ExecutionsClient, "grpc"), - (ExecutionsAsyncClient, "grpc_asyncio"), -]) -def test_executions_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 == ( - 'workflowexecutions.googleapis.com:443' - ) - - -def test_executions_client_get_transport_class(): - transport = ExecutionsClient.get_transport_class() - available_transports = [ - transports.ExecutionsGrpcTransport, - ] - assert transport in available_transports - - transport = ExecutionsClient.get_transport_class("grpc") - assert transport == transports.ExecutionsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) -def test_executions_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(ExecutionsClient, '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(ExecutionsClient, '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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", "true"), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", "false"), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_executions_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", [ - ExecutionsClient, ExecutionsAsyncClient -]) -@mock.patch.object(ExecutionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExecutionsAsyncClient)) -def test_executions_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", [ - ExecutionsClient, ExecutionsAsyncClient -]) -@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) -def test_executions_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ExecutionsClient._DEFAULT_UNIVERSE - default_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ExecutionsClient._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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_executions_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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", grpc_helpers), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_executions_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_executions_client_client_options_from_dict(): - with mock.patch('google.cloud.workflows.executions_v1.services.executions.transports.ExecutionsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ExecutionsClient( - 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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", grpc_helpers), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_executions_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( - "workflowexecutions.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="workflowexecutions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - executions.ListExecutionsRequest, - dict, -]) -def test_list_executions(request_type, transport: str = 'grpc'): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.ListExecutionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = executions.ListExecutionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExecutionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_executions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = executions.ListExecutionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_executions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == executions.ListExecutionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_executions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_executions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_executions] = mock_rpc - request = {} - client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_executions(request) - - # Establish that a new wrapper 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_executions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_executions in client._client._transport._wrapped_methods - - # 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_executions] = mock_rpc - - request = {} - await client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_executions(request) - - # Establish that a new wrapper 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_executions_async(transport: str = 'grpc_asyncio', request_type=executions.ListExecutionsRequest): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = executions.ListExecutionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExecutionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_executions_async_from_dict(): - await test_list_executions_async(request_type=dict) - -def test_list_executions_field_headers(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.ListExecutionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - call.return_value = executions.ListExecutionsResponse() - client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_executions_field_headers_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.ListExecutionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse()) - await client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_executions_flattened(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.ListExecutionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_executions( - 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_executions_flattened_error(): - client = ExecutionsClient( - credentials=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_executions( - executions.ListExecutionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_executions_flattened_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.ListExecutionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_executions( - 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_executions_flattened_error_async(): - client = ExecutionsAsyncClient( - credentials=async_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_executions( - executions.ListExecutionsRequest(), - parent='parent_value', - ) - - -def test_list_executions_pager(transport_name: str = "grpc"): - client = ExecutionsClient( - 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_executions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - executions.Execution(), - ], - next_page_token='abc', - ), - executions.ListExecutionsResponse( - executions=[], - next_page_token='def', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - ], - next_page_token='ghi', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_executions(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, executions.Execution) - for i in results) -def test_list_executions_pages(transport_name: str = "grpc"): - client = ExecutionsClient( - 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_executions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - executions.Execution(), - ], - next_page_token='abc', - ), - executions.ListExecutionsResponse( - executions=[], - next_page_token='def', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - ], - next_page_token='ghi', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - ], - ), - RuntimeError, - ) - pages = list(client.list_executions(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_executions_async_pager(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - executions.Execution(), - ], - next_page_token='abc', - ), - executions.ListExecutionsResponse( - executions=[], - next_page_token='def', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - ], - next_page_token='ghi', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_executions(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, executions.Execution) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_executions_async_pages(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - executions.Execution(), - ], - next_page_token='abc', - ), - executions.ListExecutionsResponse( - executions=[], - next_page_token='def', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - ], - next_page_token='ghi', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - ], - ), - 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_executions(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", [ - executions.CreateExecutionRequest, - dict, -]) -def test_create_execution(request_type, transport: str = 'grpc'): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, - ) - response = client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = executions.CreateExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS - - -def test_create_execution_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = executions.CreateExecutionRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_execution(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == executions.CreateExecutionRequest( - parent='parent_value', - ) - -def test_create_execution_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_execution in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_execution] = mock_rpc - request = {} - client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_execution(request) - - # Establish that a new wrapper 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_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_execution in client._client._transport._wrapped_methods - - # 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_execution] = mock_rpc - - request = {} - await client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_execution(request) - - # Establish that a new wrapper 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_execution_async(transport: str = 'grpc_asyncio', request_type=executions.CreateExecutionRequest): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, - )) - response = await client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = executions.CreateExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS - - -@pytest.mark.asyncio -async def test_create_execution_async_from_dict(): - await test_create_execution_async(request_type=dict) - -def test_create_execution_field_headers(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.CreateExecutionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_execution_field_headers_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.CreateExecutionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - await client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_execution_flattened(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_execution( - parent='parent_value', - execution=executions.Execution(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].execution - mock_val = executions.Execution(name='name_value') - assert arg == mock_val - - -def test_create_execution_flattened_error(): - client = ExecutionsClient( - credentials=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_execution( - executions.CreateExecutionRequest(), - parent='parent_value', - execution=executions.Execution(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_execution_flattened_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_execution( - parent='parent_value', - execution=executions.Execution(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].execution - mock_val = executions.Execution(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_execution_flattened_error_async(): - client = ExecutionsAsyncClient( - credentials=async_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_execution( - executions.CreateExecutionRequest(), - parent='parent_value', - execution=executions.Execution(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - executions.GetExecutionRequest, - dict, -]) -def test_get_execution(request_type, transport: str = 'grpc'): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, - ) - response = client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = executions.GetExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS - - -def test_get_execution_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = executions.GetExecutionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_execution(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == executions.GetExecutionRequest( - name='name_value', - ) - -def test_get_execution_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_execution in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_execution] = mock_rpc - request = {} - client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_execution(request) - - # Establish that a new wrapper 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_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_execution in client._client._transport._wrapped_methods - - # 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_execution] = mock_rpc - - request = {} - await client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_execution(request) - - # Establish that a new wrapper 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_execution_async(transport: str = 'grpc_asyncio', request_type=executions.GetExecutionRequest): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, - )) - response = await client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = executions.GetExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS - - -@pytest.mark.asyncio -async def test_get_execution_async_from_dict(): - await test_get_execution_async(request_type=dict) - -def test_get_execution_field_headers(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.GetExecutionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_execution_field_headers_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.GetExecutionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - await client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_execution_flattened(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_execution( - 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_execution_flattened_error(): - client = ExecutionsClient( - credentials=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_execution( - executions.GetExecutionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_execution_flattened_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_execution( - 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_execution_flattened_error_async(): - client = ExecutionsAsyncClient( - credentials=async_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_execution( - executions.GetExecutionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - executions.CancelExecutionRequest, - dict, -]) -def test_cancel_execution(request_type, transport: str = 'grpc'): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, - ) - response = client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = executions.CancelExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS - - -def test_cancel_execution_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = executions.CancelExecutionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.cancel_execution(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == executions.CancelExecutionRequest( - name='name_value', - ) - -def test_cancel_execution_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.cancel_execution in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.cancel_execution] = mock_rpc - request = {} - client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.cancel_execution(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_cancel_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.cancel_execution in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.cancel_execution] = mock_rpc - - request = {} - await client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.cancel_execution(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_cancel_execution_async(transport: str = 'grpc_asyncio', request_type=executions.CancelExecutionRequest): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, - )) - response = await client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = executions.CancelExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - assert response.call_log_level == executions.Execution.CallLogLevel.LOG_ALL_CALLS - - -@pytest.mark.asyncio -async def test_cancel_execution_async_from_dict(): - await test_cancel_execution_async(request_type=dict) - -def test_cancel_execution_field_headers(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.CancelExecutionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_cancel_execution_field_headers_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.CancelExecutionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - await client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_cancel_execution_flattened(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.cancel_execution( - 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_cancel_execution_flattened_error(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.cancel_execution( - executions.CancelExecutionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_cancel_execution_flattened_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.cancel_execution( - 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_cancel_execution_flattened_error_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.cancel_execution( - executions.CancelExecutionRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExecutionsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ExecutionsClient( - 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 = ExecutionsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExecutionsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ExecutionsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ExecutionsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ExecutionsGrpcTransport, - transports.ExecutionsGrpcAsyncIOTransport, -]) -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 = ExecutionsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ExecutionsClient( - 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_executions_empty_call_grpc(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - call.return_value = executions.ListExecutionsResponse() - client.list_executions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.ListExecutionsRequest() - - assert args[0] == request_msg - - -# This 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_execution_empty_call_grpc(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.create_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.CreateExecutionRequest() - - assert args[0] == request_msg - - -# This 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_execution_empty_call_grpc(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.get_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.GetExecutionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_cancel_execution_empty_call_grpc(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.cancel_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.CancelExecutionRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ExecutionsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ExecutionsAsyncClient( - 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_executions_empty_call_grpc_asyncio(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse( - next_page_token='next_page_token_value', - )) - await client.list_executions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.ListExecutionsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_execution_empty_call_grpc_asyncio(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, - )) - await client.create_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.CreateExecutionRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_execution_empty_call_grpc_asyncio(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, - )) - await client.get_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.GetExecutionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_cancel_execution_empty_call_grpc_asyncio(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - call_log_level=executions.Execution.CallLogLevel.LOG_ALL_CALLS, - )) - await client.cancel_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.CancelExecutionRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ExecutionsGrpcTransport, - ) - -def test_executions_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ExecutionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_executions_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.workflows.executions_v1.services.executions.transports.ExecutionsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ExecutionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_executions', - 'create_execution', - 'get_execution', - 'cancel_execution', - ) - 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_executions_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workflows.executions_v1.services.executions.transports.ExecutionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExecutionsTransport( - 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_executions_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workflows.executions_v1.services.executions.transports.ExecutionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExecutionsTransport() - adc.assert_called_once() - - -def test_executions_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) - ExecutionsClient() - 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.ExecutionsGrpcTransport, - transports.ExecutionsGrpcAsyncIOTransport, - ], -) -def test_executions_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.ExecutionsGrpcTransport, - transports.ExecutionsGrpcAsyncIOTransport, - ], -) -def test_executions_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.ExecutionsGrpcTransport, grpc_helpers), - (transports.ExecutionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_executions_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( - "workflowexecutions.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="workflowexecutions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) -def test_executions_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_executions_host_no_port(transport_name): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workflowexecutions.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workflowexecutions.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_executions_host_with_port(transport_name): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workflowexecutions.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workflowexecutions.googleapis.com:8000' - ) - -def test_executions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ExecutionsGrpcTransport( - 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_executions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ExecutionsGrpcAsyncIOTransport( - 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.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) -def test_executions_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.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) -def test_executions_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_execution_path(): - project = "squid" - location = "clam" - workflow = "whelk" - execution = "octopus" - expected = "projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}".format(project=project, location=location, workflow=workflow, execution=execution, ) - actual = ExecutionsClient.execution_path(project, location, workflow, execution) - assert expected == actual - - -def test_parse_execution_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "workflow": "cuttlefish", - "execution": "mussel", - } - path = ExecutionsClient.execution_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_execution_path(path) - assert expected == actual - -def test_workflow_path(): - project = "winkle" - location = "nautilus" - workflow = "scallop" - expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - actual = ExecutionsClient.workflow_path(project, location, workflow) - assert expected == actual - - -def test_parse_workflow_path(): - expected = { - "project": "abalone", - "location": "squid", - "workflow": "clam", - } - path = ExecutionsClient.workflow_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_workflow_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ExecutionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ExecutionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ExecutionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ExecutionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ExecutionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ExecutionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ExecutionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ExecutionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.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 = ExecutionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ExecutionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.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.ExecutionsTransport, '_prep_wrapped_messages') as prep: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ExecutionsTransport, '_prep_wrapped_messages') as prep: - transport_class = ExecutionsClient.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 = ExecutionsClient( - 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 = ExecutionsAsyncClient( - 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_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = ExecutionsClient( - 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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport), -]) -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-cloud-workflows/v1/tests/unit/gapic/workflows_v1/__init__.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_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-cloud-workflows/v1/tests/unit/gapic/workflows_v1/test_workflows.py b/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/test_workflows.py deleted file mode 100644 index ec2c9cd03db2..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1/tests/unit/gapic/workflows_v1/test_workflows.py +++ /dev/null @@ -1,6232 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.location import locations_pb2 -from google.cloud.workflows_v1.services.workflows import WorkflowsAsyncClient -from google.cloud.workflows_v1.services.workflows import WorkflowsClient -from google.cloud.workflows_v1.services.workflows import pagers -from google.cloud.workflows_v1.services.workflows import transports -from google.cloud.workflows_v1.types import workflows -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -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 WorkflowsClient._get_default_mtls_endpoint(None) is None - assert WorkflowsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WorkflowsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WorkflowsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WorkflowsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WorkflowsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert WorkflowsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert WorkflowsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert WorkflowsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - WorkflowsClient._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 WorkflowsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert WorkflowsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert WorkflowsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - WorkflowsClient._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 WorkflowsClient._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 WorkflowsClient._get_client_cert_source(None, False) is None - assert WorkflowsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert WorkflowsClient._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 WorkflowsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert WorkflowsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = WorkflowsClient._DEFAULT_UNIVERSE - default_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert WorkflowsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert WorkflowsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT - assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "always") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT - assert WorkflowsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT - assert WorkflowsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - WorkflowsClient._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 WorkflowsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert WorkflowsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert WorkflowsClient._get_universe_domain(None, None) == WorkflowsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - WorkflowsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (WorkflowsClient, "grpc"), - (WorkflowsAsyncClient, "grpc_asyncio"), - (WorkflowsClient, "rest"), -]) -def test_workflows_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 == ( - 'workflows.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workflows.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WorkflowsGrpcTransport, "grpc"), - (transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.WorkflowsRestTransport, "rest"), -]) -def test_workflows_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", [ - (WorkflowsClient, "grpc"), - (WorkflowsAsyncClient, "grpc_asyncio"), - (WorkflowsClient, "rest"), -]) -def test_workflows_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 == ( - 'workflows.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workflows.googleapis.com' - ) - - -def test_workflows_client_get_transport_class(): - transport = WorkflowsClient.get_transport_class() - available_transports = [ - transports.WorkflowsGrpcTransport, - transports.WorkflowsRestTransport, - ] - assert transport in available_transports - - transport = WorkflowsClient.get_transport_class("grpc") - assert transport == transports.WorkflowsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), -]) -@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) -def test_workflows_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(WorkflowsClient, '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(WorkflowsClient, '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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", "true"), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", "false"), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest", "true"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest", "false"), -]) -@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_workflows_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", [ - WorkflowsClient, WorkflowsAsyncClient -]) -@mock.patch.object(WorkflowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkflowsAsyncClient)) -def test_workflows_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", [ - WorkflowsClient, WorkflowsAsyncClient -]) -@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) -def test_workflows_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = WorkflowsClient._DEFAULT_UNIVERSE - default_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WorkflowsClient._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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), -]) -def test_workflows_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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", grpc_helpers), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest", None), -]) -def test_workflows_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_workflows_client_client_options_from_dict(): - with mock.patch('google.cloud.workflows_v1.services.workflows.transports.WorkflowsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WorkflowsClient( - 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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", grpc_helpers), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_workflows_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( - "workflows.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="workflows.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - workflows.ListWorkflowsRequest, - dict, -]) -def test_list_workflows(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.ListWorkflowsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.ListWorkflowsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkflowsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workflows_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.ListWorkflowsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workflows(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.ListWorkflowsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_workflows_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflows in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflows] = mock_rpc - request = {} - client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workflows(request) - - # Establish that a new wrapper 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_workflows_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflows in client._client._transport._wrapped_methods - - # 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_workflows] = mock_rpc - - request = {} - await client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workflows(request) - - # Establish that a new wrapper 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_workflows_async(transport: str = 'grpc_asyncio', request_type=workflows.ListWorkflowsRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.ListWorkflowsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkflowsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workflows_async_from_dict(): - await test_list_workflows_async(request_type=dict) - -def test_list_workflows_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.ListWorkflowsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - call.return_value = workflows.ListWorkflowsResponse() - client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflows_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.ListWorkflowsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse()) - await client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflows_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.ListWorkflowsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workflows( - 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_workflows_flattened_error(): - client = WorkflowsClient( - credentials=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_workflows( - workflows.ListWorkflowsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workflows_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.ListWorkflowsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workflows( - 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_workflows_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflows( - workflows.ListWorkflowsRequest(), - parent='parent_value', - ) - - -def test_list_workflows_pager(transport_name: str = "grpc"): - client = WorkflowsClient( - 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_workflows), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workflows(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, workflows.Workflow) - for i in results) -def test_list_workflows_pages(transport_name: str = "grpc"): - client = WorkflowsClient( - 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_workflows), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workflows(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_workflows_async_pager(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workflows(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, workflows.Workflow) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workflows_async_pages(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - 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_workflows(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", [ - workflows.GetWorkflowRequest, - dict, -]) -def test_get_workflow(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.Workflow( - name='name_value', - description='description_value', - state=workflows.Workflow.State.ACTIVE, - revision_id='revision_id_value', - service_account='service_account_value', - crypto_key_name='crypto_key_name_value', - call_log_level=workflows.Workflow.CallLogLevel.LOG_ALL_CALLS, - source_contents='source_contents_value', - ) - response = client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.GetWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workflows.Workflow) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == workflows.Workflow.State.ACTIVE - assert response.revision_id == 'revision_id_value' - assert response.service_account == 'service_account_value' - assert response.crypto_key_name == 'crypto_key_name_value' - assert response.call_log_level == workflows.Workflow.CallLogLevel.LOG_ALL_CALLS - - -def test_get_workflow_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.GetWorkflowRequest( - name='name_value', - revision_id='revision_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_workflow(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.GetWorkflowRequest( - name='name_value', - revision_id='revision_id_value', - ) - -def test_get_workflow_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workflow] = mock_rpc - request = {} - client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workflow(request) - - # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflow in client._client._transport._wrapped_methods - - # 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_workflow] = mock_rpc - - request = {} - await client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_workflow(request) - - # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.GetWorkflowRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow( - name='name_value', - description='description_value', - state=workflows.Workflow.State.ACTIVE, - revision_id='revision_id_value', - service_account='service_account_value', - crypto_key_name='crypto_key_name_value', - call_log_level=workflows.Workflow.CallLogLevel.LOG_ALL_CALLS, - )) - response = await client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.GetWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workflows.Workflow) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == workflows.Workflow.State.ACTIVE - assert response.revision_id == 'revision_id_value' - assert response.service_account == 'service_account_value' - assert response.crypto_key_name == 'crypto_key_name_value' - assert response.call_log_level == workflows.Workflow.CallLogLevel.LOG_ALL_CALLS - - -@pytest.mark.asyncio -async def test_get_workflow_async_from_dict(): - await test_get_workflow_async(request_type=dict) - -def test_get_workflow_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.GetWorkflowRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - call.return_value = workflows.Workflow() - client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.GetWorkflowRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow()) - await client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.Workflow() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workflow( - 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_workflow_flattened_error(): - client = WorkflowsClient( - credentials=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_workflow( - workflows.GetWorkflowRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workflow_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.Workflow() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workflow( - 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_workflow_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflow( - workflows.GetWorkflowRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workflows.CreateWorkflowRequest, - dict, -]) -def test_create_workflow(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.CreateWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workflow_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.CreateWorkflowRequest( - parent='parent_value', - workflow_id='workflow_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_workflow(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.CreateWorkflowRequest( - parent='parent_value', - workflow_id='workflow_id_value', - ) - -def test_create_workflow_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - request = {} - client.create_workflow(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.create_workflow(request) - - # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflow in client._client._transport._wrapped_methods - - # 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_workflow] = mock_rpc - - request = {} - await client.create_workflow(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.create_workflow(request) - - # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.CreateWorkflowRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__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.create_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.CreateWorkflowRequest() - 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_create_workflow_async_from_dict(): - await test_create_workflow_async(request_type=dict) - -def test_create_workflow_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.CreateWorkflowRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.CreateWorkflowRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_workflow( - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_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].workflow - mock_val = workflows.Workflow(name='name_value') - assert arg == mock_val - arg = args[0].workflow_id - mock_val = 'workflow_id_value' - assert arg == mock_val - - -def test_create_workflow_flattened_error(): - client = WorkflowsClient( - credentials=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_workflow( - workflows.CreateWorkflowRequest(), - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workflow_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_workflow( - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_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].workflow - mock_val = workflows.Workflow(name='name_value') - assert arg == mock_val - arg = args[0].workflow_id - mock_val = 'workflow_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workflow_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflow( - workflows.CreateWorkflowRequest(), - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workflows.DeleteWorkflowRequest, - dict, -]) -def test_delete_workflow(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.DeleteWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workflow_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.DeleteWorkflowRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_workflow(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.DeleteWorkflowRequest( - name='name_value', - ) - -def test_delete_workflow_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - request = {} - client.delete_workflow(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.delete_workflow(request) - - # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflow in client._client._transport._wrapped_methods - - # 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_workflow] = mock_rpc - - request = {} - await client.delete_workflow(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.delete_workflow(request) - - # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.DeleteWorkflowRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__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.delete_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.DeleteWorkflowRequest() - 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_delete_workflow_async_from_dict(): - await test_delete_workflow_async(request_type=dict) - -def test_delete_workflow_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.DeleteWorkflowRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.DeleteWorkflowRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_workflow( - 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_workflow_flattened_error(): - client = WorkflowsClient( - credentials=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_workflow( - workflows.DeleteWorkflowRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workflow_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_workflow( - 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_workflow_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflow( - workflows.DeleteWorkflowRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workflows.UpdateWorkflowRequest, - dict, -]) -def test_update_workflow(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.UpdateWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workflow_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.UpdateWorkflowRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_workflow(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.UpdateWorkflowRequest( - ) - -def test_update_workflow_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - request = {} - client.update_workflow(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.update_workflow(request) - - # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflow in client._client._transport._wrapped_methods - - # 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_workflow] = mock_rpc - - request = {} - await client.update_workflow(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.update_workflow(request) - - # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.UpdateWorkflowRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__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.update_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.UpdateWorkflowRequest() - 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_update_workflow_async_from_dict(): - await test_update_workflow_async(request_type=dict) - -def test_update_workflow_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.UpdateWorkflowRequest() - - request.workflow.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workflow.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workflow_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.UpdateWorkflowRequest() - - request.workflow.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workflow.name=name_value', - ) in kw['metadata'] - - -def test_update_workflow_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_workflow( - workflow=workflows.Workflow(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].workflow - mock_val = workflows.Workflow(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_workflow_flattened_error(): - client = WorkflowsClient( - credentials=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_workflow( - workflows.UpdateWorkflowRequest(), - workflow=workflows.Workflow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workflow_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_workflow( - workflow=workflows.Workflow(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].workflow - mock_val = workflows.Workflow(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_workflow_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflow( - workflows.UpdateWorkflowRequest(), - workflow=workflows.Workflow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_workflows_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflows in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflows] = mock_rpc - - request = {} - client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workflows(request) - - # Establish 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_workflows_rest_required_fields(request_type=workflows.ListWorkflowsRequest): - transport_class = transports.WorkflowsRestTransport - - 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_workflows._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_workflows._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "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 = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workflows.ListWorkflowsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workflows.ListWorkflowsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_workflows(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workflows_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workflows._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workflows_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workflows.ListWorkflowsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/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 = workflows.ListWorkflowsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_workflows(**mock_args) - - # Establish that the underlying call 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/*/locations/*}/workflows" % client.transport._host, args[1]) - - -def test_list_workflows_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflows( - workflows.ListWorkflowsRequest(), - parent='parent_value', - ) - - -def test_list_workflows_rest_pager(transport: str = 'rest'): - client = WorkflowsClient( - 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 = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workflows.ListWorkflowsResponse.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/locations/sample2'} - - pager = client.list_workflows(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workflows.Workflow) - for i in results) - - pages = list(client.list_workflows(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_workflow_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workflow] = mock_rpc - - request = {} - client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workflow(request) - - # Establish 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_workflow_rest_required_fields(request_type=workflows.GetWorkflowRequest): - transport_class = transports.WorkflowsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workflow._get_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_workflow._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("revision_id", )) - jsonified_request.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 = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workflows.Workflow() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workflows.Workflow.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_workflow(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workflow_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workflow._get_unset_required_fields({}) - assert set(unset_fields) == (set(("revisionId", )) & set(("name", ))) - - -def test_get_workflow_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workflows.Workflow() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workflows/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 = workflows.Workflow.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_workflow(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workflows/*}" % client.transport._host, args[1]) - - -def test_get_workflow_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflow( - workflows.GetWorkflowRequest(), - name='name_value', - ) - - -def test_create_workflow_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - - request = {} - client.create_workflow(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.create_workflow(request) - - # Establish 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_workflow_rest_required_fields(request_type=workflows.CreateWorkflowRequest): - transport_class = transports.WorkflowsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workflow_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 "workflowId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workflow._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workflowId" in jsonified_request - assert jsonified_request["workflowId"] == request_init["workflow_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workflowId"] = 'workflow_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workflow._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("workflow_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 "workflowId" in jsonified_request - assert jsonified_request["workflowId"] == 'workflow_id_value' - - client = WorkflowsClient( - 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 - - response = client.create_workflow(request) - - expected_params = [ - ( - "workflowId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workflow_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workflow._get_unset_required_fields({}) - assert set(unset_fields) == (set(("workflowId", )) & set(("parent", "workflow", "workflowId", ))) - - -def test_create_workflow_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_id_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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workflow(**mock_args) - - # Establish that the underlying call 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/*/locations/*}/workflows" % client.transport._host, args[1]) - - -def test_create_workflow_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflow( - workflows.CreateWorkflowRequest(), - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_id_value', - ) - - -def test_delete_workflow_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - - request = {} - client.delete_workflow(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.delete_workflow(request) - - # Establish 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_workflow_rest_required_fields(request_type=workflows.DeleteWorkflowRequest): - transport_class = transports.WorkflowsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workflow._get_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_workflow._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkflowsClient( - 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': "delete", - '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 - - response = client.delete_workflow(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workflow_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workflow._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_workflow_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workflows/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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workflow(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workflows/*}" % client.transport._host, args[1]) - - -def test_delete_workflow_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflow( - workflows.DeleteWorkflowRequest(), - name='name_value', - ) - - -def test_update_workflow_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - - request = {} - client.update_workflow(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.update_workflow(request) - - # Establish 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_workflow_rest_required_fields(request_type=workflows.UpdateWorkflowRequest): - transport_class = transports.WorkflowsRestTransport - - 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_workflow._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_workflow._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 = WorkflowsClient( - 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': "patch", - '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 - - response = client.update_workflow(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workflow_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workflow._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("workflow", ))) - - -def test_update_workflow_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - workflow=workflows.Workflow(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_workflow(**mock_args) - - # Establish that the underlying call 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/{workflow.name=projects/*/locations/*/workflows/*}" % client.transport._host, args[1]) - - -def test_update_workflow_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflow( - workflows.UpdateWorkflowRequest(), - workflow=workflows.Workflow(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.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkflowsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WorkflowsClient( - 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 = WorkflowsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkflowsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WorkflowsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WorkflowsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WorkflowsGrpcTransport, - transports.WorkflowsGrpcAsyncIOTransport, - transports.WorkflowsRestTransport, -]) -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 = WorkflowsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = WorkflowsClient( - 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_workflows_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - call.return_value = workflows.ListWorkflowsResponse() - client.list_workflows(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.ListWorkflowsRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - call.return_value = workflows.Workflow() - client.get_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.GetWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.CreateWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.DeleteWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.UpdateWorkflowRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = WorkflowsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = WorkflowsAsyncClient( - 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_workflows_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_workflows(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.ListWorkflowsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow( - name='name_value', - description='description_value', - state=workflows.Workflow.State.ACTIVE, - revision_id='revision_id_value', - service_account='service_account_value', - crypto_key_name='crypto_key_name_value', - call_log_level=workflows.Workflow.CallLogLevel.LOG_ALL_CALLS, - )) - await client.get_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.GetWorkflowRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__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.create_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.CreateWorkflowRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__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.delete_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.DeleteWorkflowRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__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.update_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.UpdateWorkflowRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = WorkflowsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_workflows_rest_bad_request(request_type=workflows.ListWorkflowsRequest): - client = WorkflowsClient( - 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 - client.list_workflows(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.ListWorkflowsRequest, - dict, -]) -def test_list_workflows_rest_call_success(request_type): - client = WorkflowsClient( - 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 = workflows.ListWorkflowsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workflows.ListWorkflowsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_workflows(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkflowsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workflows_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "post_list_workflows") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_list_workflows") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.ListWorkflowsRequest.pb(workflows.ListWorkflowsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workflows.ListWorkflowsResponse.to_json(workflows.ListWorkflowsResponse()) - req.return_value.content = return_value - - request = workflows.ListWorkflowsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workflows.ListWorkflowsResponse() - - client.list_workflows(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workflow_rest_bad_request(request_type=workflows.GetWorkflowRequest): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 - client.get_workflow(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.GetWorkflowRequest, - dict, -]) -def test_get_workflow_rest_call_success(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 = workflows.Workflow( - name='name_value', - description='description_value', - state=workflows.Workflow.State.ACTIVE, - revision_id='revision_id_value', - service_account='service_account_value', - crypto_key_name='crypto_key_name_value', - call_log_level=workflows.Workflow.CallLogLevel.LOG_ALL_CALLS, - source_contents='source_contents_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 = workflows.Workflow.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_workflow(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workflows.Workflow) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == workflows.Workflow.State.ACTIVE - assert response.revision_id == 'revision_id_value' - assert response.service_account == 'service_account_value' - assert response.crypto_key_name == 'crypto_key_name_value' - assert response.call_log_level == workflows.Workflow.CallLogLevel.LOG_ALL_CALLS - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workflow_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "post_get_workflow") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_get_workflow") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.GetWorkflowRequest.pb(workflows.GetWorkflowRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workflows.Workflow.to_json(workflows.Workflow()) - req.return_value.content = return_value - - request = workflows.GetWorkflowRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workflows.Workflow() - - client.get_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workflow_rest_bad_request(request_type=workflows.CreateWorkflowRequest): - client = WorkflowsClient( - 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 - client.create_workflow(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.CreateWorkflowRequest, - dict, -]) -def test_create_workflow_rest_call_success(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["workflow"] = {'name': 'name_value', 'description': 'description_value', 'state': 1, 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'revision_create_time': {}, 'labels': {}, 'service_account': 'service_account_value', 'source_contents': 'source_contents_value', 'crypto_key_name': 'crypto_key_name_value', 'state_error': {'details': 'details_value', 'type_': 1}, 'call_log_level': 1, 'user_env_vars': {}} - # 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 = workflows.CreateWorkflowRequest.meta.fields["workflow"] - - 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["workflow"].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["workflow"][field])): - del request_init["workflow"][field][i][subfield] - else: - del request_init["workflow"][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 = 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 - response = client.create_workflow(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_create_workflow_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_create_workflow") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_create_workflow") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.CreateWorkflowRequest.pb(workflows.CreateWorkflowRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workflows.CreateWorkflowRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workflow_rest_bad_request(request_type=workflows.DeleteWorkflowRequest): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 - client.delete_workflow(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.DeleteWorkflowRequest, - dict, -]) -def test_delete_workflow_rest_call_success(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 = 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 - response = client.delete_workflow(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_delete_workflow_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_delete_workflow") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_delete_workflow") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.DeleteWorkflowRequest.pb(workflows.DeleteWorkflowRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workflows.DeleteWorkflowRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workflow_rest_bad_request(request_type=workflows.UpdateWorkflowRequest): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/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 - client.update_workflow(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.UpdateWorkflowRequest, - dict, -]) -def test_update_workflow_rest_call_success(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/sample3'}} - request_init["workflow"] = {'name': 'projects/sample1/locations/sample2/workflows/sample3', 'description': 'description_value', 'state': 1, 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'revision_create_time': {}, 'labels': {}, 'service_account': 'service_account_value', 'source_contents': 'source_contents_value', 'crypto_key_name': 'crypto_key_name_value', 'state_error': {'details': 'details_value', 'type_': 1}, 'call_log_level': 1, 'user_env_vars': {}} - # 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 = workflows.UpdateWorkflowRequest.meta.fields["workflow"] - - 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["workflow"].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["workflow"][field])): - del request_init["workflow"][field][i][subfield] - else: - del request_init["workflow"][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 = 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 - response = client.update_workflow(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_update_workflow_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_update_workflow") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_update_workflow") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.UpdateWorkflowRequest.pb(workflows.UpdateWorkflowRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workflows.UpdateWorkflowRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # 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 - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': '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(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # 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 - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, 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 - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - 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 = locations_pb2.ListLocationsResponse() - - # 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 - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = WorkflowsClient( - 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 - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = WorkflowsClient( - 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 = 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 - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = WorkflowsClient( - 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 - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = WorkflowsClient( - 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 - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # 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 - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': '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(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # 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 - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_initialize_client_w_rest(): - client = WorkflowsClient( - 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_workflows_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - client.list_workflows(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.ListWorkflowsRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - client.get_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.GetWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - client.create_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.CreateWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - client.delete_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.DeleteWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - client.update_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.UpdateWorkflowRequest() - - assert args[0] == request_msg - - -def test_workflows_rest_lro_client(): - client = WorkflowsClient( - 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 = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WorkflowsGrpcTransport, - ) - -def test_workflows_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WorkflowsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_workflows_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.workflows_v1.services.workflows.transports.WorkflowsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WorkflowsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_workflows', - 'get_workflow', - 'create_workflow', - 'delete_workflow', - 'update_workflow', - 'get_location', - 'list_locations', - 'get_operation', - 'delete_operation', - 'list_operations', - ) - 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_workflows_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workflows_v1.services.workflows.transports.WorkflowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkflowsTransport( - 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_workflows_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workflows_v1.services.workflows.transports.WorkflowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkflowsTransport() - adc.assert_called_once() - - -def test_workflows_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) - WorkflowsClient() - 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.WorkflowsGrpcTransport, - transports.WorkflowsGrpcAsyncIOTransport, - ], -) -def test_workflows_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.WorkflowsGrpcTransport, - transports.WorkflowsGrpcAsyncIOTransport, - transports.WorkflowsRestTransport, - ], -) -def test_workflows_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.WorkflowsGrpcTransport, grpc_helpers), - (transports.WorkflowsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_workflows_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( - "workflows.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="workflows.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) -def test_workflows_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_workflows_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.WorkflowsRestTransport ( - 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_workflows_host_no_port(transport_name): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workflows.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workflows.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workflows.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_workflows_host_with_port(transport_name): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workflows.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workflows.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workflows.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_workflows_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = WorkflowsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = WorkflowsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_workflows._session - session2 = client2.transport.list_workflows._session - assert session1 != session2 - session1 = client1.transport.get_workflow._session - session2 = client2.transport.get_workflow._session - assert session1 != session2 - session1 = client1.transport.create_workflow._session - session2 = client2.transport.create_workflow._session - assert session1 != session2 - session1 = client1.transport.delete_workflow._session - session2 = client2.transport.delete_workflow._session - assert session1 != session2 - session1 = client1.transport.update_workflow._session - session2 = client2.transport.update_workflow._session - assert session1 != session2 -def test_workflows_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkflowsGrpcTransport( - 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_workflows_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkflowsGrpcAsyncIOTransport( - 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.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) -def test_workflows_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.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) -def test_workflows_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_workflows_grpc_lro_client(): - client = WorkflowsClient( - 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_workflows_grpc_lro_async_client(): - client = WorkflowsAsyncClient( - 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_crypto_key_path(): - project = "squid" - location = "clam" - keyRing = "whelk" - cryptoKey = "octopus" - expected = "projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}".format(project=project, location=location, keyRing=keyRing, cryptoKey=cryptoKey, ) - actual = WorkflowsClient.crypto_key_path(project, location, keyRing, cryptoKey) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "keyRing": "cuttlefish", - "cryptoKey": "mussel", - } - path = WorkflowsClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.parse_crypto_key_path(path) - assert expected == actual - -def test_workflow_path(): - project = "winkle" - location = "nautilus" - workflow = "scallop" - expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - actual = WorkflowsClient.workflow_path(project, location, workflow) - assert expected == actual - - -def test_parse_workflow_path(): - expected = { - "project": "abalone", - "location": "squid", - "workflow": "clam", - } - path = WorkflowsClient.workflow_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.parse_workflow_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WorkflowsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = WorkflowsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = WorkflowsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = WorkflowsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WorkflowsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = WorkflowsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = WorkflowsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = WorkflowsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.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 = WorkflowsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = WorkflowsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.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.WorkflowsTransport, '_prep_wrapped_messages') as prep: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WorkflowsTransport, '_prep_wrapped_messages') as prep: - transport_class = WorkflowsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_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 response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc_asyncio"): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_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 response is None - -def test_delete_operation_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_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_delete_operation_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_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_delete_operation_from_dict(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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 = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = WorkflowsClient( - 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 = WorkflowsAsyncClient( - 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_list_operations(transport: str = "grpc"): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the 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.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the 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.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_list_operations_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_list_operations_from_dict(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the 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, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the 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, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_list_locations_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_list_locations_from_dict(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the 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, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the 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, locations_pb2.Location) - -def test_get_location_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = WorkflowsClient( - 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 = WorkflowsAsyncClient( - 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 = WorkflowsClient( - 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 = WorkflowsClient( - 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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport), -]) -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-cloud-workflows/v1beta/.coveragerc b/owl-bot-staging/google-cloud-workflows/v1beta/.coveragerc deleted file mode 100644 index 0b3eb91ee6c6..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/workflows/__init__.py - google/cloud/workflows/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-cloud-workflows/v1beta/.flake8 b/owl-bot-staging/google-cloud-workflows/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-workflows/v1beta/MANIFEST.in deleted file mode 100644 index 80137aea1e08..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/workflows *.py -recursive-include google/cloud/workflows_v1beta *.py diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/README.rst b/owl-bot-staging/google-cloud-workflows/v1beta/README.rst deleted file mode 100644 index 9ff50ef51f9e..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Workflows 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 Cloud Workflows 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-cloud-workflows/v1beta/docs/_static/custom.css b/owl-bot-staging/google-cloud-workflows/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-workflows/v1beta/docs/conf.py deleted file mode 100644 index aa65085dd2d2..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows 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-cloud-workflows" -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 Cloud 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-cloud-workflows-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-cloud-workflows.tex", - u"google-cloud-workflows 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-cloud-workflows", - u"Google Cloud Workflows 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-cloud-workflows", - u"google-cloud-workflows Documentation", - author, - "google-cloud-workflows", - "GAPIC library for Google Cloud Workflows 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-cloud-workflows/v1beta/docs/executions_v1beta/executions.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/executions.rst deleted file mode 100644 index 8e18a7f058e0..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/executions.rst +++ /dev/null @@ -1,10 +0,0 @@ -Executions ----------------------------- - -.. automodule:: google.cloud.workflows.executions_v1beta.services.executions - :members: - :inherited-members: - -.. automodule:: google.cloud.workflows.executions_v1beta.services.executions.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/services_.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/services_.rst deleted file mode 100644 index f6ae17ade08b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Workflows Executions v1beta API -========================================================= -.. toctree:: - :maxdepth: 2 - - executions diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/types_.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/types_.rst deleted file mode 100644 index 6c92f22e378d..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/docs/executions_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Workflows Executions v1beta API -====================================================== - -.. automodule:: google.cloud.workflows.executions_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/index.rst deleted file mode 100644 index ed454475774f..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - workflows_v1beta/services_ - workflows_v1beta/types_ diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/services_.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/services_.rst deleted file mode 100644 index ad4e93dde768..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Workflows v1beta API -============================================== -.. toctree:: - :maxdepth: 2 - - workflows diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/types_.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/types_.rst deleted file mode 100644 index 0b7a8571584f..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Workflows v1beta API -=========================================== - -.. automodule:: google.cloud.workflows_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/workflows.rst b/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/workflows.rst deleted file mode 100644 index ac0a1b0d1b8f..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/docs/workflows_v1beta/workflows.rst +++ /dev/null @@ -1,10 +0,0 @@ -Workflows ---------------------------- - -.. automodule:: google.cloud.workflows_v1beta.services.workflows - :members: - :inherited-members: - -.. automodule:: google.cloud.workflows_v1beta.services.workflows.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/__init__.py deleted file mode 100644 index f90c411948b7..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/__init__.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.workflows_v1beta.services.workflows.client import WorkflowsClient -from google.cloud.workflows_v1beta.services.workflows.async_client import WorkflowsAsyncClient - -from google.cloud.workflows_v1beta.types.workflows import CreateWorkflowRequest -from google.cloud.workflows_v1beta.types.workflows import DeleteWorkflowRequest -from google.cloud.workflows_v1beta.types.workflows import GetWorkflowRequest -from google.cloud.workflows_v1beta.types.workflows import ListWorkflowsRequest -from google.cloud.workflows_v1beta.types.workflows import ListWorkflowsResponse -from google.cloud.workflows_v1beta.types.workflows import OperationMetadata -from google.cloud.workflows_v1beta.types.workflows import UpdateWorkflowRequest -from google.cloud.workflows_v1beta.types.workflows import Workflow - -__all__ = ('WorkflowsClient', - 'WorkflowsAsyncClient', - 'CreateWorkflowRequest', - 'DeleteWorkflowRequest', - 'GetWorkflowRequest', - 'ListWorkflowsRequest', - 'ListWorkflowsResponse', - 'OperationMetadata', - 'UpdateWorkflowRequest', - 'Workflow', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/__init__.py deleted file mode 100644 index 8475b13abaf8..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows.executions import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.workflows.executions_v1beta.services.executions.client import ExecutionsClient -from google.cloud.workflows.executions_v1beta.services.executions.async_client import ExecutionsAsyncClient - -from google.cloud.workflows.executions_v1beta.types.executions import CancelExecutionRequest -from google.cloud.workflows.executions_v1beta.types.executions import CreateExecutionRequest -from google.cloud.workflows.executions_v1beta.types.executions import Execution -from google.cloud.workflows.executions_v1beta.types.executions import GetExecutionRequest -from google.cloud.workflows.executions_v1beta.types.executions import ListExecutionsRequest -from google.cloud.workflows.executions_v1beta.types.executions import ListExecutionsResponse -from google.cloud.workflows.executions_v1beta.types.executions import ExecutionView - -__all__ = ('ExecutionsClient', - 'ExecutionsAsyncClient', - 'CancelExecutionRequest', - 'CreateExecutionRequest', - 'Execution', - 'GetExecutionRequest', - 'ListExecutionsRequest', - 'ListExecutionsResponse', - 'ExecutionView', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/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-cloud-workflows/v1beta/google/cloud/workflows/executions/py.typed b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/py.typed deleted file mode 100644 index ff4d7c1ed09d..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workflows-executions package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/__init__.py deleted file mode 100644 index 8077643c3e6c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/__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 google.cloud.workflows.executions_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.executions import ExecutionsClient -from .services.executions import ExecutionsAsyncClient - -from .types.executions import CancelExecutionRequest -from .types.executions import CreateExecutionRequest -from .types.executions import Execution -from .types.executions import GetExecutionRequest -from .types.executions import ListExecutionsRequest -from .types.executions import ListExecutionsResponse -from .types.executions import ExecutionView - -__all__ = ( - 'ExecutionsAsyncClient', -'CancelExecutionRequest', -'CreateExecutionRequest', -'Execution', -'ExecutionView', -'ExecutionsClient', -'GetExecutionRequest', -'ListExecutionsRequest', -'ListExecutionsResponse', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_metadata.json deleted file mode 100644 index dec2db0f9bb3..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_metadata.json +++ /dev/null @@ -1,63 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.workflows.executions_v1beta", - "protoPackage": "google.cloud.workflows.executions.v1beta", - "schema": "1.0", - "services": { - "Executions": { - "clients": { - "grpc": { - "libraryClient": "ExecutionsClient", - "rpcs": { - "CancelExecution": { - "methods": [ - "cancel_execution" - ] - }, - "CreateExecution": { - "methods": [ - "create_execution" - ] - }, - "GetExecution": { - "methods": [ - "get_execution" - ] - }, - "ListExecutions": { - "methods": [ - "list_executions" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ExecutionsAsyncClient", - "rpcs": { - "CancelExecution": { - "methods": [ - "cancel_execution" - ] - }, - "CreateExecution": { - "methods": [ - "create_execution" - ] - }, - "GetExecution": { - "methods": [ - "get_execution" - ] - }, - "ListExecutions": { - "methods": [ - "list_executions" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_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-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/py.typed b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/py.typed deleted file mode 100644 index ff4d7c1ed09d..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workflows-executions package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_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-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/__init__.py deleted file mode 100644 index 9295dd9a3cb5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/__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 ExecutionsClient -from .async_client import ExecutionsAsyncClient - -__all__ = ( - 'ExecutionsClient', - 'ExecutionsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/async_client.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/async_client.py deleted file mode 100644 index 752b78064e72..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/async_client.py +++ /dev/null @@ -1,699 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.workflows.executions_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.cloud.workflows.executions_v1beta.services.executions import pagers -from google.cloud.workflows.executions_v1beta.types import executions -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ExecutionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ExecutionsGrpcAsyncIOTransport -from .client import ExecutionsClient - - -class ExecutionsAsyncClient: - """Executions is used to start and manage running instances of - [Workflows][google.cloud.workflows.v1beta.Workflow] called - executions. - """ - - _client: ExecutionsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ExecutionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ExecutionsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ExecutionsClient._DEFAULT_UNIVERSE - - execution_path = staticmethod(ExecutionsClient.execution_path) - parse_execution_path = staticmethod(ExecutionsClient.parse_execution_path) - workflow_path = staticmethod(ExecutionsClient.workflow_path) - parse_workflow_path = staticmethod(ExecutionsClient.parse_workflow_path) - common_billing_account_path = staticmethod(ExecutionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ExecutionsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ExecutionsClient.common_folder_path) - parse_common_folder_path = staticmethod(ExecutionsClient.parse_common_folder_path) - common_organization_path = staticmethod(ExecutionsClient.common_organization_path) - parse_common_organization_path = staticmethod(ExecutionsClient.parse_common_organization_path) - common_project_path = staticmethod(ExecutionsClient.common_project_path) - parse_common_project_path = staticmethod(ExecutionsClient.parse_common_project_path) - common_location_path = staticmethod(ExecutionsClient.common_location_path) - parse_common_location_path = staticmethod(ExecutionsClient.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: - ExecutionsAsyncClient: The constructed client. - """ - return ExecutionsClient.from_service_account_info.__func__(ExecutionsAsyncClient, 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: - ExecutionsAsyncClient: The constructed client. - """ - return ExecutionsClient.from_service_account_file.__func__(ExecutionsAsyncClient, 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 ExecutionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ExecutionsTransport: - """Returns the transport used by the client instance. - - Returns: - ExecutionsTransport: 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 = ExecutionsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ExecutionsTransport, Callable[..., ExecutionsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the executions 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,ExecutionsTransport,Callable[..., ExecutionsTransport]]]): - 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 ExecutionsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = ExecutionsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_executions(self, - request: Optional[Union[executions.ListExecutionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExecutionsAsyncPager: - r"""Returns a list of executions which belong to the - workflow with the given name. The method returns - executions of all workflow revisions. Returned - executions are ordered by their start time (newest - first). - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1beta - - async def sample_list_executions(): - # Create a client - client = executions_v1beta.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1beta.ListExecutionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_executions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest, dict]]): - The request object. Request for the - [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] - method. - parent (:class:`str`): - Required. Name of the workflow for - which the executions should be listed. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1beta.services.executions.pagers.ListExecutionsAsyncPager: - Response for the - [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] - 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, executions.ListExecutionsRequest): - request = executions.ListExecutionsRequest(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_executions] - - # Certain fields should be provided within 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.ListExecutionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_execution(self, - request: Optional[Union[executions.CreateExecutionRequest, dict]] = None, - *, - parent: Optional[str] = None, - execution: Optional[executions.Execution] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Creates a new execution using the latest revision of - the given workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1beta - - async def sample_create_execution(): - # Create a client - client = executions_v1beta.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1beta.CreateExecutionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows.executions_v1beta.types.CreateExecutionRequest, dict]]): - The request object. Request for the - [CreateExecution][google.cloud.workflows.executions.v1beta.Executions.CreateExecution] - method. - parent (:class:`str`): - Required. Name of the workflow for - which an execution should be created. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - The latest revision of the workflow will - be used. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - execution (:class:`google.cloud.workflows.executions_v1beta.types.Execution`): - Required. Execution to be created. - This corresponds to the ``execution`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_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. - - Returns: - google.cloud.workflows.executions_v1beta.types.Execution: - A running instance of a - [Workflow][google.cloud.workflows.v1beta.Workflow]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, execution]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, executions.CreateExecutionRequest): - request = executions.CreateExecutionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if execution is not None: - request.execution = execution - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_execution] - - # Certain fields should be provided within 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_execution(self, - request: Optional[Union[executions.GetExecutionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Returns an execution of the given name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1beta - - async def sample_get_execution(): - # Create a client - client = executions_v1beta.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1beta.GetExecutionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows.executions_v1beta.types.GetExecutionRequest, dict]]): - The request object. Request for the - [GetExecution][google.cloud.workflows.executions.v1beta.Executions.GetExecution] - method. - name (:class:`str`): - Required. Name of the execution to be - retrieved. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1beta.types.Execution: - A running instance of a - [Workflow][google.cloud.workflows.v1beta.Workflow]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, executions.GetExecutionRequest): - request = executions.GetExecutionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_execution] - - # Certain fields should be provided within 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 cancel_execution(self, - request: Optional[Union[executions.CancelExecutionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Cancels an execution of the given name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1beta - - async def sample_cancel_execution(): - # Create a client - client = executions_v1beta.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1beta.CancelExecutionRequest( - name="name_value", - ) - - # Make the request - response = await client.cancel_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows.executions_v1beta.types.CancelExecutionRequest, dict]]): - The request object. Request for the - [CancelExecution][google.cloud.workflows.executions.v1beta.Executions.CancelExecution] - method. - name (:class:`str`): - Required. Name of the execution to be - cancelled. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1beta.types.Execution: - A running instance of a - [Workflow][google.cloud.workflows.v1beta.Workflow]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, executions.CancelExecutionRequest): - request = executions.CancelExecutionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.cancel_execution] - - # Certain fields should be provided within 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) -> "ExecutionsAsyncClient": - 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__ = ( - "ExecutionsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/client.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/client.py deleted file mode 100644 index bf859f10dbb9..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/client.py +++ /dev/null @@ -1,1059 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.workflows.executions_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 - -from google.cloud.workflows.executions_v1beta.services.executions import pagers -from google.cloud.workflows.executions_v1beta.types import executions -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ExecutionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ExecutionsGrpcTransport -from .transports.grpc_asyncio import ExecutionsGrpcAsyncIOTransport - - -class ExecutionsClientMeta(type): - """Metaclass for the Executions 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[ExecutionsTransport]] - _transport_registry["grpc"] = ExecutionsGrpcTransport - _transport_registry["grpc_asyncio"] = ExecutionsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ExecutionsTransport]: - """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 ExecutionsClient(metaclass=ExecutionsClientMeta): - """Executions is used to start and manage running instances of - [Workflows][google.cloud.workflows.v1beta.Workflow] called - executions. - """ - - @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 = "workflowexecutions.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "workflowexecutions.{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: - ExecutionsClient: 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: - ExecutionsClient: 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) -> ExecutionsTransport: - """Returns the transport used by the client instance. - - Returns: - ExecutionsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def execution_path(project: str,location: str,workflow: str,execution: str,) -> str: - """Returns a fully-qualified execution string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}".format(project=project, location=location, workflow=workflow, execution=execution, ) - - @staticmethod - def parse_execution_path(path: str) -> Dict[str,str]: - """Parses a execution path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)/executions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workflow_path(project: str,location: str,workflow: str,) -> str: - """Returns a fully-qualified workflow string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - - @staticmethod - def parse_workflow_path(path: str) -> Dict[str,str]: - """Parses a workflow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = ExecutionsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ExecutionsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ExecutionsClient._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 = ExecutionsClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ExecutionsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - ExecutionsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, ExecutionsTransport, Callable[..., ExecutionsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the executions client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,ExecutionsTransport,Callable[..., ExecutionsTransport]]]): - 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 ExecutionsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = ExecutionsClient._read_environment_variables() - self._client_cert_source = ExecutionsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ExecutionsClient._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 - - 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, ExecutionsTransport) - if transport_provided: - # transport is a ExecutionsTransport 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(ExecutionsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ExecutionsClient._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[ExecutionsTransport], Callable[..., ExecutionsTransport]] = ( - ExecutionsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ExecutionsTransport], 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, - ) - - def list_executions(self, - request: Optional[Union[executions.ListExecutionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExecutionsPager: - r"""Returns a list of executions which belong to the - workflow with the given name. The method returns - executions of all workflow revisions. Returned - executions are ordered by their start time (newest - first). - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1beta - - def sample_list_executions(): - # Create a client - client = executions_v1beta.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1beta.ListExecutionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_executions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest, dict]): - The request object. Request for the - [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] - method. - parent (str): - Required. Name of the workflow for - which the executions should be listed. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1beta.services.executions.pagers.ListExecutionsPager: - Response for the - [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] - 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, executions.ListExecutionsRequest): - request = executions.ListExecutionsRequest(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_executions] - - # Certain fields should be provided within 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.ListExecutionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_execution(self, - request: Optional[Union[executions.CreateExecutionRequest, dict]] = None, - *, - parent: Optional[str] = None, - execution: Optional[executions.Execution] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Creates a new execution using the latest revision of - the given workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1beta - - def sample_create_execution(): - # Create a client - client = executions_v1beta.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1beta.CreateExecutionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows.executions_v1beta.types.CreateExecutionRequest, dict]): - The request object. Request for the - [CreateExecution][google.cloud.workflows.executions.v1beta.Executions.CreateExecution] - method. - parent (str): - Required. Name of the workflow for - which an execution should be created. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - The latest revision of the workflow will - be used. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - execution (google.cloud.workflows.executions_v1beta.types.Execution): - Required. Execution to be created. - This corresponds to the ``execution`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.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. - - Returns: - google.cloud.workflows.executions_v1beta.types.Execution: - A running instance of a - [Workflow][google.cloud.workflows.v1beta.Workflow]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, execution]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, executions.CreateExecutionRequest): - request = executions.CreateExecutionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if execution is not None: - request.execution = execution - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_execution] - - # Certain fields should be provided within 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_execution(self, - request: Optional[Union[executions.GetExecutionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Returns an execution of the given name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1beta - - def sample_get_execution(): - # Create a client - client = executions_v1beta.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1beta.GetExecutionRequest( - name="name_value", - ) - - # Make the request - response = client.get_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows.executions_v1beta.types.GetExecutionRequest, dict]): - The request object. Request for the - [GetExecution][google.cloud.workflows.executions.v1beta.Executions.GetExecution] - method. - name (str): - Required. Name of the execution to be - retrieved. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1beta.types.Execution: - A running instance of a - [Workflow][google.cloud.workflows.v1beta.Workflow]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, executions.GetExecutionRequest): - request = executions.GetExecutionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_execution] - - # Certain fields should be provided within 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 cancel_execution(self, - request: Optional[Union[executions.CancelExecutionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> executions.Execution: - r"""Cancels an execution of the given name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud.workflows import executions_v1beta - - def sample_cancel_execution(): - # Create a client - client = executions_v1beta.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1beta.CancelExecutionRequest( - name="name_value", - ) - - # Make the request - response = client.cancel_execution(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows.executions_v1beta.types.CancelExecutionRequest, dict]): - The request object. Request for the - [CancelExecution][google.cloud.workflows.executions.v1beta.Executions.CancelExecution] - method. - name (str): - Required. Name of the execution to be - cancelled. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows.executions_v1beta.types.Execution: - A running instance of a - [Workflow][google.cloud.workflows.v1beta.Workflow]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, executions.CancelExecutionRequest): - request = executions.CancelExecutionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.cancel_execution] - - # Certain fields should be provided within 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) -> "ExecutionsClient": - 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__ = ( - "ExecutionsClient", -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/pagers.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/pagers.py deleted file mode 100644 index e9a2ed7aba20..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows.executions_v1beta.types import executions - - -class ListExecutionsPager: - """A pager for iterating through ``list_executions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``executions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListExecutions`` requests and continue to iterate - through the ``executions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., executions.ListExecutionsResponse], - request: executions.ListExecutionsRequest, - response: executions.ListExecutionsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest): - The initial request object. - response (google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = executions.ListExecutionsRequest(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[executions.ListExecutionsResponse]: - 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[executions.Execution]: - for page in self.pages: - yield from page.executions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListExecutionsAsyncPager: - """A pager for iterating through ``list_executions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``executions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListExecutions`` requests and continue to iterate - through the ``executions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse` - attributes are available on the 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[executions.ListExecutionsResponse]], - request: executions.ListExecutionsRequest, - response: executions.ListExecutionsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest): - The initial request object. - response (google.cloud.workflows.executions_v1beta.types.ListExecutionsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = executions.ListExecutionsRequest(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[executions.ListExecutionsResponse]: - 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[executions.Execution]: - async def async_generator(): - async for page in self.pages: - for response in page.executions: - 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-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/README.rst b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/README.rst deleted file mode 100644 index 6555db202c9c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ExecutionsTransport` is the ABC for all transports. -- public child `ExecutionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ExecutionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseExecutionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ExecutionsRestTransport` 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-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/__init__.py deleted file mode 100644 index fbf990808f62..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 ExecutionsTransport -from .grpc import ExecutionsGrpcTransport -from .grpc_asyncio import ExecutionsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ExecutionsTransport]] -_transport_registry['grpc'] = ExecutionsGrpcTransport -_transport_registry['grpc_asyncio'] = ExecutionsGrpcAsyncIOTransport - -__all__ = ( - 'ExecutionsTransport', - 'ExecutionsGrpcTransport', - 'ExecutionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/base.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/base.py deleted file mode 100644 index 13fb59eb4d07..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/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.cloud.workflows.executions_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.cloud.workflows.executions_v1beta.types import executions - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ExecutionsTransport(abc.ABC): - """Abstract transport class for Executions.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_executions: gapic_v1.method.wrap_method( - self.list_executions, - default_timeout=None, - client_info=client_info, - ), - self.create_execution: gapic_v1.method.wrap_method( - self.create_execution, - default_timeout=None, - client_info=client_info, - ), - self.get_execution: gapic_v1.method.wrap_method( - self.get_execution, - default_timeout=None, - client_info=client_info, - ), - self.cancel_execution: gapic_v1.method.wrap_method( - self.cancel_execution, - 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_executions(self) -> Callable[ - [executions.ListExecutionsRequest], - Union[ - executions.ListExecutionsResponse, - Awaitable[executions.ListExecutionsResponse] - ]]: - raise NotImplementedError() - - @property - def create_execution(self) -> Callable[ - [executions.CreateExecutionRequest], - Union[ - executions.Execution, - Awaitable[executions.Execution] - ]]: - raise NotImplementedError() - - @property - def get_execution(self) -> Callable[ - [executions.GetExecutionRequest], - Union[ - executions.Execution, - Awaitable[executions.Execution] - ]]: - raise NotImplementedError() - - @property - def cancel_execution(self) -> Callable[ - [executions.CancelExecutionRequest], - Union[ - executions.Execution, - Awaitable[executions.Execution] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ExecutionsTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc.py deleted file mode 100644 index 6229e44d3912..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc.py +++ /dev/null @@ -1,355 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.cloud.workflows.executions_v1beta.types import executions -from .base import ExecutionsTransport, DEFAULT_CLIENT_INFO - - -class ExecutionsGrpcTransport(ExecutionsTransport): - """gRPC backend transport for Executions. - - Executions is used to start and manage running instances of - [Workflows][google.cloud.workflows.v1beta.Workflow] called - executions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'workflowexecutions.googleapis.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_executions(self) -> Callable[ - [executions.ListExecutionsRequest], - executions.ListExecutionsResponse]: - r"""Return a callable for the list executions method over gRPC. - - Returns a list of executions which belong to the - workflow with the given name. The method returns - executions of all workflow revisions. Returned - executions are ordered by their start time (newest - first). - - Returns: - Callable[[~.ListExecutionsRequest], - ~.ListExecutionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_executions' not in self._stubs: - self._stubs['list_executions'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1beta.Executions/ListExecutions', - request_serializer=executions.ListExecutionsRequest.serialize, - response_deserializer=executions.ListExecutionsResponse.deserialize, - ) - return self._stubs['list_executions'] - - @property - def create_execution(self) -> Callable[ - [executions.CreateExecutionRequest], - executions.Execution]: - r"""Return a callable for the create execution method over gRPC. - - Creates a new execution using the latest revision of - the given workflow. - - Returns: - Callable[[~.CreateExecutionRequest], - ~.Execution]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_execution' not in self._stubs: - self._stubs['create_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1beta.Executions/CreateExecution', - request_serializer=executions.CreateExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['create_execution'] - - @property - def get_execution(self) -> Callable[ - [executions.GetExecutionRequest], - executions.Execution]: - r"""Return a callable for the get execution method over gRPC. - - Returns an execution of the given name. - - Returns: - Callable[[~.GetExecutionRequest], - ~.Execution]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_execution' not in self._stubs: - self._stubs['get_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1beta.Executions/GetExecution', - request_serializer=executions.GetExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['get_execution'] - - @property - def cancel_execution(self) -> Callable[ - [executions.CancelExecutionRequest], - executions.Execution]: - r"""Return a callable for the cancel execution method over gRPC. - - Cancels an execution of the given name. - - Returns: - Callable[[~.CancelExecutionRequest], - ~.Execution]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'cancel_execution' not in self._stubs: - self._stubs['cancel_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1beta.Executions/CancelExecution', - request_serializer=executions.CancelExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['cancel_execution'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ExecutionsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc_asyncio.py deleted file mode 100644 index be8c4683b8e8..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/services/executions/transports/grpc_asyncio.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 inspect -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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.workflows.executions_v1beta.types import executions -from .base import ExecutionsTransport, DEFAULT_CLIENT_INFO -from .grpc import ExecutionsGrpcTransport - - -class ExecutionsGrpcAsyncIOTransport(ExecutionsTransport): - """gRPC AsyncIO backend transport for Executions. - - Executions is used to start and manage running instances of - [Workflows][google.cloud.workflows.v1beta.Workflow] called - executions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workflowexecutions.googleapis.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 = 'workflowexecutions.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: 'workflowexecutions.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_executions(self) -> Callable[ - [executions.ListExecutionsRequest], - Awaitable[executions.ListExecutionsResponse]]: - r"""Return a callable for the list executions method over gRPC. - - Returns a list of executions which belong to the - workflow with the given name. The method returns - executions of all workflow revisions. Returned - executions are ordered by their start time (newest - first). - - Returns: - Callable[[~.ListExecutionsRequest], - Awaitable[~.ListExecutionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_executions' not in self._stubs: - self._stubs['list_executions'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1beta.Executions/ListExecutions', - request_serializer=executions.ListExecutionsRequest.serialize, - response_deserializer=executions.ListExecutionsResponse.deserialize, - ) - return self._stubs['list_executions'] - - @property - def create_execution(self) -> Callable[ - [executions.CreateExecutionRequest], - Awaitable[executions.Execution]]: - r"""Return a callable for the create execution method over gRPC. - - Creates a new execution using the latest revision of - the given workflow. - - Returns: - Callable[[~.CreateExecutionRequest], - Awaitable[~.Execution]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_execution' not in self._stubs: - self._stubs['create_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1beta.Executions/CreateExecution', - request_serializer=executions.CreateExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['create_execution'] - - @property - def get_execution(self) -> Callable[ - [executions.GetExecutionRequest], - Awaitable[executions.Execution]]: - r"""Return a callable for the get execution method over gRPC. - - Returns an execution of the given name. - - Returns: - Callable[[~.GetExecutionRequest], - Awaitable[~.Execution]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_execution' not in self._stubs: - self._stubs['get_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1beta.Executions/GetExecution', - request_serializer=executions.GetExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['get_execution'] - - @property - def cancel_execution(self) -> Callable[ - [executions.CancelExecutionRequest], - Awaitable[executions.Execution]]: - r"""Return a callable for the cancel execution method over gRPC. - - Cancels an execution of the given name. - - Returns: - Callable[[~.CancelExecutionRequest], - Awaitable[~.Execution]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'cancel_execution' not in self._stubs: - self._stubs['cancel_execution'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.executions.v1beta.Executions/CancelExecution', - request_serializer=executions.CancelExecutionRequest.serialize, - response_deserializer=executions.Execution.deserialize, - ) - return self._stubs['cancel_execution'] - - 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_executions: self._wrap_method( - self.list_executions, - default_timeout=None, - client_info=client_info, - ), - self.create_execution: self._wrap_method( - self.create_execution, - default_timeout=None, - client_info=client_info, - ), - self.get_execution: self._wrap_method( - self.get_execution, - default_timeout=None, - client_info=client_info, - ), - self.cancel_execution: self._wrap_method( - self.cancel_execution, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'ExecutionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/__init__.py deleted file mode 100644 index 52fb1dab35df..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .executions import ( - CancelExecutionRequest, - CreateExecutionRequest, - Execution, - GetExecutionRequest, - ListExecutionsRequest, - ListExecutionsResponse, - ExecutionView, -) - -__all__ = ( - 'CancelExecutionRequest', - 'CreateExecutionRequest', - 'Execution', - 'GetExecutionRequest', - 'ListExecutionsRequest', - 'ListExecutionsResponse', - 'ExecutionView', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/executions.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/executions.py deleted file mode 100644 index d9cfd2e6eb71..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/executions_v1beta/types/executions.py +++ /dev/null @@ -1,324 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.workflows.executions.v1beta', - manifest={ - 'ExecutionView', - 'Execution', - 'ListExecutionsRequest', - 'ListExecutionsResponse', - 'CreateExecutionRequest', - 'GetExecutionRequest', - 'CancelExecutionRequest', - }, -) - - -class ExecutionView(proto.Enum): - r"""Defines possible views for execution resource. - - Values: - EXECUTION_VIEW_UNSPECIFIED (0): - The default / unset value. - BASIC (1): - Includes only basic metadata about the execution. Following - fields are returned: name, start_time, end_time, state and - workflow_revision_id. - FULL (2): - Includes all data. - """ - EXECUTION_VIEW_UNSPECIFIED = 0 - BASIC = 1 - FULL = 2 - - -class Execution(proto.Message): - r"""A running instance of a - [Workflow][google.cloud.workflows.v1beta.Workflow]. - - Attributes: - name (str): - Output only. The resource name of the - execution. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Marks the beginning of - execution. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Marks the end of execution, - successful or not. - state (google.cloud.workflows.executions_v1beta.types.Execution.State): - Output only. Current state of the execution. - argument (str): - Input parameters of the execution represented - as a JSON string. The size limit is 32KB. - result (str): - Output only. Output of the execution represented as a JSON - string. The value can only be present if the execution's - state is ``SUCCEEDED``. - error (google.cloud.workflows.executions_v1beta.types.Execution.Error): - Output only. The error which caused the execution to finish - prematurely. The value is only present if the execution's - state is ``FAILED`` or ``CANCELLED``. - workflow_revision_id (str): - Output only. Revision of the workflow this - execution is using. - """ - class State(proto.Enum): - r"""Describes the current state of the execution. More states may - be added in the future. - - Values: - STATE_UNSPECIFIED (0): - Invalid state. - ACTIVE (1): - The execution is in progress. - SUCCEEDED (2): - The execution finished successfully. - FAILED (3): - The execution failed with an error. - CANCELLED (4): - The execution was stopped intentionally. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - SUCCEEDED = 2 - FAILED = 3 - CANCELLED = 4 - - class Error(proto.Message): - r"""Error describes why the execution was abnormally terminated. - - Attributes: - payload (str): - Error payload returned by the execution, - represented as a JSON string. - context (str): - Human readable error context, helpful for - debugging purposes. - """ - - payload: str = proto.Field( - proto.STRING, - number=1, - ) - context: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - argument: str = proto.Field( - proto.STRING, - number=5, - ) - result: str = proto.Field( - proto.STRING, - number=6, - ) - error: Error = proto.Field( - proto.MESSAGE, - number=7, - message=Error, - ) - workflow_revision_id: str = proto.Field( - proto.STRING, - number=8, - ) - - -class ListExecutionsRequest(proto.Message): - r"""Request for the - [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] - method. - - Attributes: - parent (str): - Required. Name of the workflow for which the - executions should be listed. Format: - projects/{project}/locations/{location}/workflows/{workflow} - page_size (int): - Maximum number of executions to return per - call. Max supported value depends on the - selected Execution view: it's 10000 for BASIC - and 100 for FULL. The default value used if the - field is not specified is 100, regardless of the - selected view. Values greater than the max value - will be coerced down to it. - page_token (str): - A page token, received from a previous ``ListExecutions`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListExecutions`` must match the call that provided the - page token. - view (google.cloud.workflows.executions_v1beta.types.ExecutionView): - Optional. A view defining which fields should - be filled in the returned executions. The API - will default to the BASIC view. - """ - - 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, - ) - view: 'ExecutionView' = proto.Field( - proto.ENUM, - number=4, - enum='ExecutionView', - ) - - -class ListExecutionsResponse(proto.Message): - r"""Response for the - [ListExecutions][google.cloud.workflows.executions.v1beta.Executions.ListExecutions] - method. - - Attributes: - executions (MutableSequence[google.cloud.workflows.executions_v1beta.types.Execution]): - The executions which match the request. - 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 - - executions: MutableSequence['Execution'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Execution', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateExecutionRequest(proto.Message): - r"""Request for the - [CreateExecution][google.cloud.workflows.executions.v1beta.Executions.CreateExecution] - method. - - Attributes: - parent (str): - Required. Name of the workflow for which an - execution should be created. Format: - projects/{project}/locations/{location}/workflows/{workflow} - The latest revision of the workflow will be - used. - execution (google.cloud.workflows.executions_v1beta.types.Execution): - Required. Execution to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - execution: 'Execution' = proto.Field( - proto.MESSAGE, - number=2, - message='Execution', - ) - - -class GetExecutionRequest(proto.Message): - r"""Request for the - [GetExecution][google.cloud.workflows.executions.v1beta.Executions.GetExecution] - method. - - Attributes: - name (str): - Required. Name of the execution to be - retrieved. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - view (google.cloud.workflows.executions_v1beta.types.ExecutionView): - Optional. A view defining which fields should - be filled in the returned execution. The API - will default to the FULL view. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - view: 'ExecutionView' = proto.Field( - proto.ENUM, - number=2, - enum='ExecutionView', - ) - - -class CancelExecutionRequest(proto.Message): - r"""Request for the - [CancelExecution][google.cloud.workflows.executions.v1beta.Executions.CancelExecution] - method. - - Attributes: - name (str): - Required. Name of the execution to be - cancelled. Format: - - projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution} - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/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-cloud-workflows/v1beta/google/cloud/workflows/py.typed b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/py.typed deleted file mode 100644 index b753e6a6bf5b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workflows package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/__init__.py deleted file mode 100644 index 50073afcf641..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/__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 google.cloud.workflows_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.workflows import WorkflowsClient -from .services.workflows import WorkflowsAsyncClient - -from .types.workflows import CreateWorkflowRequest -from .types.workflows import DeleteWorkflowRequest -from .types.workflows import GetWorkflowRequest -from .types.workflows import ListWorkflowsRequest -from .types.workflows import ListWorkflowsResponse -from .types.workflows import OperationMetadata -from .types.workflows import UpdateWorkflowRequest -from .types.workflows import Workflow - -__all__ = ( - 'WorkflowsAsyncClient', -'CreateWorkflowRequest', -'DeleteWorkflowRequest', -'GetWorkflowRequest', -'ListWorkflowsRequest', -'ListWorkflowsResponse', -'OperationMetadata', -'UpdateWorkflowRequest', -'Workflow', -'WorkflowsClient', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_metadata.json deleted file mode 100644 index 28846823fc96..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_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.cloud.workflows_v1beta", - "protoPackage": "google.cloud.workflows.v1beta", - "schema": "1.0", - "services": { - "Workflows": { - "clients": { - "grpc": { - "libraryClient": "WorkflowsClient", - "rpcs": { - "CreateWorkflow": { - "methods": [ - "create_workflow" - ] - }, - "DeleteWorkflow": { - "methods": [ - "delete_workflow" - ] - }, - "GetWorkflow": { - "methods": [ - "get_workflow" - ] - }, - "ListWorkflows": { - "methods": [ - "list_workflows" - ] - }, - "UpdateWorkflow": { - "methods": [ - "update_workflow" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WorkflowsAsyncClient", - "rpcs": { - "CreateWorkflow": { - "methods": [ - "create_workflow" - ] - }, - "DeleteWorkflow": { - "methods": [ - "delete_workflow" - ] - }, - "GetWorkflow": { - "methods": [ - "get_workflow" - ] - }, - "ListWorkflows": { - "methods": [ - "list_workflows" - ] - }, - "UpdateWorkflow": { - "methods": [ - "update_workflow" - ] - } - } - }, - "rest": { - "libraryClient": "WorkflowsClient", - "rpcs": { - "CreateWorkflow": { - "methods": [ - "create_workflow" - ] - }, - "DeleteWorkflow": { - "methods": [ - "delete_workflow" - ] - }, - "GetWorkflow": { - "methods": [ - "get_workflow" - ] - }, - "ListWorkflows": { - "methods": [ - "list_workflows" - ] - }, - "UpdateWorkflow": { - "methods": [ - "update_workflow" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_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-cloud-workflows/v1beta/google/cloud/workflows_v1beta/py.typed b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/py.typed deleted file mode 100644 index b753e6a6bf5b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workflows package uses inline types. diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_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-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/__init__.py deleted file mode 100644 index 5c7fa07ed889..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/__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 WorkflowsClient -from .async_client import WorkflowsAsyncClient - -__all__ = ( - 'WorkflowsClient', - 'WorkflowsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/async_client.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/async_client.py deleted file mode 100644 index fcec767a099e..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/async_client.py +++ /dev/null @@ -1,894 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.workflows_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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.workflows_v1beta.services.workflows import pagers -from google.cloud.workflows_v1beta.types import workflows -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WorkflowsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WorkflowsGrpcAsyncIOTransport -from .client import WorkflowsClient - - -class WorkflowsAsyncClient: - """Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - """ - - _client: WorkflowsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = WorkflowsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WorkflowsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = WorkflowsClient._DEFAULT_UNIVERSE - - workflow_path = staticmethod(WorkflowsClient.workflow_path) - parse_workflow_path = staticmethod(WorkflowsClient.parse_workflow_path) - common_billing_account_path = staticmethod(WorkflowsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WorkflowsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WorkflowsClient.common_folder_path) - parse_common_folder_path = staticmethod(WorkflowsClient.parse_common_folder_path) - common_organization_path = staticmethod(WorkflowsClient.common_organization_path) - parse_common_organization_path = staticmethod(WorkflowsClient.parse_common_organization_path) - common_project_path = staticmethod(WorkflowsClient.common_project_path) - parse_common_project_path = staticmethod(WorkflowsClient.parse_common_project_path) - common_location_path = staticmethod(WorkflowsClient.common_location_path) - parse_common_location_path = staticmethod(WorkflowsClient.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: - WorkflowsAsyncClient: The constructed client. - """ - return WorkflowsClient.from_service_account_info.__func__(WorkflowsAsyncClient, 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: - WorkflowsAsyncClient: The constructed client. - """ - return WorkflowsClient.from_service_account_file.__func__(WorkflowsAsyncClient, 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 WorkflowsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> WorkflowsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkflowsTransport: 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 = WorkflowsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, WorkflowsTransport, Callable[..., WorkflowsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workflows 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,WorkflowsTransport,Callable[..., WorkflowsTransport]]]): - 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 WorkflowsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WorkflowsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_workflows(self, - request: Optional[Union[workflows.ListWorkflowsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkflowsAsyncPager: - r"""Lists Workflows in a given project and location. - The default order is not specified. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1beta - - async def sample_list_workflows(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1beta.ListWorkflowsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workflows(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1beta.types.ListWorkflowsRequest, dict]]): - The request object. Request for the - [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] - method. - parent (:class:`str`): - Required. Project and location from - which the workflows should be listed. - Format: - projects/{project}/locations/{location} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows_v1beta.services.workflows.pagers.ListWorkflowsAsyncPager: - Response for the - [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] - 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, workflows.ListWorkflowsRequest): - request = workflows.ListWorkflowsRequest(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_workflows] - - # Certain fields should be provided within 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.ListWorkflowsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_workflow(self, - request: Optional[Union[workflows.GetWorkflowRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workflows.Workflow: - r"""Gets details of a single Workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1beta - - async def sample_get_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1beta.GetWorkflowRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workflow(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1beta.types.GetWorkflowRequest, dict]]): - The request object. Request for the - [GetWorkflow][google.cloud.workflows.v1beta.Workflows.GetWorkflow] - method. - name (:class:`str`): - Required. Name of the workflow which - information should be retrieved. Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows_v1beta.types.Workflow: - Workflow program to be executed by - Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflows.GetWorkflowRequest): - request = workflows.GetWorkflowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workflow] - - # Certain fields should be provided within 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_workflow(self, - request: Optional[Union[workflows.CreateWorkflowRequest, dict]] = None, - *, - parent: Optional[str] = None, - workflow: Optional[workflows.Workflow] = None, - workflow_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workflow. If a workflow with the specified name - already exists in the specified project and location, the long - running operation will return - [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] 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.cloud import workflows_v1beta - - async def sample_create_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - workflow = workflows_v1beta.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1beta.CreateWorkflowRequest( - parent="parent_value", - workflow=workflow, - workflow_id="workflow_id_value", - ) - - # Make the request - operation = client.create_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1beta.types.CreateWorkflowRequest, dict]]): - The request object. Request for the - [CreateWorkflow][google.cloud.workflows.v1beta.Workflows.CreateWorkflow] - method. - parent (:class:`str`): - Required. Project and location in - which the workflow should be created. - Format: - projects/{project}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workflow (:class:`google.cloud.workflows_v1beta.types.Workflow`): - Required. Workflow to be created. - This corresponds to the ``workflow`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workflow_id (:class:`str`): - Required. The ID of the workflow to be created. It has - to fulfill the following requirements: - - - Must contain only letters, numbers, underscores and - hyphens. - - Must start with a letter. - - Must be between 1-64 characters. - - Must end with a number or a letter. - - Must be unique within the customer project and - location. - - This corresponds to the ``workflow_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workflows_v1beta.types.Workflow` - Workflow program to be executed by Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflow, workflow_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, workflows.CreateWorkflowRequest): - request = workflows.CreateWorkflowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workflow is not None: - request.workflow = workflow - if workflow_id is not None: - request.workflow_id = workflow_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_workflow] - - # Certain fields should be provided within 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, - workflows.Workflow, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workflow(self, - request: Optional[Union[workflows.DeleteWorkflowRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a workflow with the specified name. - This method also cancels and deletes all running - executions of the workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1beta - - async def sample_delete_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1beta.DeleteWorkflowRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1beta.types.DeleteWorkflowRequest, dict]]): - The request object. Request for the - [DeleteWorkflow][google.cloud.workflows.v1beta.Workflows.DeleteWorkflow] - method. - name (:class:`str`): - Required. Name of the workflow to be - deleted. Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflows.DeleteWorkflowRequest): - request = workflows.DeleteWorkflowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workflow] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workflow(self, - request: Optional[Union[workflows.UpdateWorkflowRequest, dict]] = None, - *, - workflow: Optional[workflows.Workflow] = 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, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an existing workflow. - Running this method has no impact on already running - executions of the workflow. A new revision of the - workflow may be created as a result of a successful - update operation. In that case, such revision will be - used in new workflow executions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1beta - - async def sample_update_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - workflow = workflows_v1beta.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1beta.UpdateWorkflowRequest( - workflow=workflow, - ) - - # Make the request - operation = client.update_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workflows_v1beta.types.UpdateWorkflowRequest, dict]]): - The request object. Request for the - [UpdateWorkflow][google.cloud.workflows.v1beta.Workflows.UpdateWorkflow] - method. - workflow (:class:`google.cloud.workflows_v1beta.types.Workflow`): - Required. Workflow to be updated. - This corresponds to the ``workflow`` 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 to be updated. If not - present, the entire workflow will 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workflows_v1beta.types.Workflow` - Workflow program to be executed by Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workflow, 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, workflows.UpdateWorkflowRequest): - request = workflows.UpdateWorkflowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workflow is not None: - request.workflow = workflow - 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_workflow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workflow.name", request.workflow.name), - )), - ) - - # 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, - workflows.Workflow, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "WorkflowsAsyncClient": - 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__ = ( - "WorkflowsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/client.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/client.py deleted file mode 100644 index 382b4d0beb69..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/client.py +++ /dev/null @@ -1,1246 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.workflows_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 - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.workflows_v1beta.services.workflows import pagers -from google.cloud.workflows_v1beta.types import workflows -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WorkflowsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WorkflowsGrpcTransport -from .transports.grpc_asyncio import WorkflowsGrpcAsyncIOTransport -from .transports.rest import WorkflowsRestTransport - - -class WorkflowsClientMeta(type): - """Metaclass for the Workflows 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[WorkflowsTransport]] - _transport_registry["grpc"] = WorkflowsGrpcTransport - _transport_registry["grpc_asyncio"] = WorkflowsGrpcAsyncIOTransport - _transport_registry["rest"] = WorkflowsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[WorkflowsTransport]: - """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 WorkflowsClient(metaclass=WorkflowsClientMeta): - """Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - """ - - @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 = "workflows.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "workflows.{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: - WorkflowsClient: 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: - WorkflowsClient: 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) -> WorkflowsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkflowsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def workflow_path(project: str,location: str,workflow: str,) -> str: - """Returns a fully-qualified workflow string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - - @staticmethod - def parse_workflow_path(path: str) -> Dict[str,str]: - """Parses a workflow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = WorkflowsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = WorkflowsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = WorkflowsClient._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 = WorkflowsClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = WorkflowsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - WorkflowsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, WorkflowsTransport, Callable[..., WorkflowsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workflows client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,WorkflowsTransport,Callable[..., WorkflowsTransport]]]): - 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 WorkflowsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WorkflowsClient._read_environment_variables() - self._client_cert_source = WorkflowsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = WorkflowsClient._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 - - 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, WorkflowsTransport) - if transport_provided: - # transport is a WorkflowsTransport 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(WorkflowsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - WorkflowsClient._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[WorkflowsTransport], Callable[..., WorkflowsTransport]] = ( - WorkflowsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., WorkflowsTransport], 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, - ) - - def list_workflows(self, - request: Optional[Union[workflows.ListWorkflowsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkflowsPager: - r"""Lists Workflows in a given project and location. - The default order is not specified. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1beta - - def sample_list_workflows(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1beta.ListWorkflowsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workflows(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workflows_v1beta.types.ListWorkflowsRequest, dict]): - The request object. Request for the - [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] - method. - parent (str): - Required. Project and location from - which the workflows should be listed. - Format: - projects/{project}/locations/{location} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows_v1beta.services.workflows.pagers.ListWorkflowsPager: - Response for the - [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] - 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, workflows.ListWorkflowsRequest): - request = workflows.ListWorkflowsRequest(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_workflows] - - # Certain fields should be provided within 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.ListWorkflowsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_workflow(self, - request: Optional[Union[workflows.GetWorkflowRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workflows.Workflow: - r"""Gets details of a single Workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1beta - - def sample_get_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1beta.GetWorkflowRequest( - name="name_value", - ) - - # Make the request - response = client.get_workflow(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows_v1beta.types.GetWorkflowRequest, dict]): - The request object. Request for the - [GetWorkflow][google.cloud.workflows.v1beta.Workflows.GetWorkflow] - method. - name (str): - Required. Name of the workflow which - information should be retrieved. Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workflows_v1beta.types.Workflow: - Workflow program to be executed by - Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflows.GetWorkflowRequest): - request = workflows.GetWorkflowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workflow] - - # Certain fields should be provided within 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_workflow(self, - request: Optional[Union[workflows.CreateWorkflowRequest, dict]] = None, - *, - parent: Optional[str] = None, - workflow: Optional[workflows.Workflow] = None, - workflow_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workflow. If a workflow with the specified name - already exists in the specified project and location, the long - running operation will return - [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] 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.cloud import workflows_v1beta - - def sample_create_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - workflow = workflows_v1beta.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1beta.CreateWorkflowRequest( - parent="parent_value", - workflow=workflow, - workflow_id="workflow_id_value", - ) - - # Make the request - operation = client.create_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows_v1beta.types.CreateWorkflowRequest, dict]): - The request object. Request for the - [CreateWorkflow][google.cloud.workflows.v1beta.Workflows.CreateWorkflow] - method. - parent (str): - Required. Project and location in - which the workflow should be created. - Format: - projects/{project}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workflow (google.cloud.workflows_v1beta.types.Workflow): - Required. Workflow to be created. - This corresponds to the ``workflow`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workflow_id (str): - Required. The ID of the workflow to be created. It has - to fulfill the following requirements: - - - Must contain only letters, numbers, underscores and - hyphens. - - Must start with a letter. - - Must be between 1-64 characters. - - Must end with a number or a letter. - - Must be unique within the customer project and - location. - - This corresponds to the ``workflow_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workflows_v1beta.types.Workflow` - Workflow program to be executed by Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflow, workflow_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, workflows.CreateWorkflowRequest): - request = workflows.CreateWorkflowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workflow is not None: - request.workflow = workflow - if workflow_id is not None: - request.workflow_id = workflow_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workflow] - - # Certain fields should be provided within 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, - workflows.Workflow, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workflow(self, - request: Optional[Union[workflows.DeleteWorkflowRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a workflow with the specified name. - This method also cancels and deletes all running - executions of the workflow. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1beta - - def sample_delete_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1beta.DeleteWorkflowRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows_v1beta.types.DeleteWorkflowRequest, dict]): - The request object. Request for the - [DeleteWorkflow][google.cloud.workflows.v1beta.Workflows.DeleteWorkflow] - method. - name (str): - Required. Name of the workflow to be - deleted. Format: - projects/{project}/locations/{location}/workflows/{workflow} - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workflows.DeleteWorkflowRequest): - request = workflows.DeleteWorkflowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workflow] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workflow(self, - request: Optional[Union[workflows.UpdateWorkflowRequest, dict]] = None, - *, - workflow: Optional[workflows.Workflow] = 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, str]] = (), - ) -> operation.Operation: - r"""Updates an existing workflow. - Running this method has no impact on already running - executions of the workflow. A new revision of the - workflow may be created as a result of a successful - update operation. In that case, such revision will be - used in new workflow executions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workflows_v1beta - - def sample_update_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - workflow = workflows_v1beta.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1beta.UpdateWorkflowRequest( - workflow=workflow, - ) - - # Make the request - operation = client.update_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workflows_v1beta.types.UpdateWorkflowRequest, dict]): - The request object. Request for the - [UpdateWorkflow][google.cloud.workflows.v1beta.Workflows.UpdateWorkflow] - method. - workflow (google.cloud.workflows_v1beta.types.Workflow): - Required. Workflow to be updated. - This corresponds to the ``workflow`` 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 to be updated. If not - present, the entire workflow will 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workflows_v1beta.types.Workflow` - Workflow program to be executed by Workflows. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workflow, 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, workflows.UpdateWorkflowRequest): - request = workflows.UpdateWorkflowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workflow is not None: - request.workflow = workflow - 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_workflow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workflow.name", request.workflow.name), - )), - ) - - # 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, - workflows.Workflow, - metadata_type=workflows.OperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "WorkflowsClient": - 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__ = ( - "WorkflowsClient", -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/pagers.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/pagers.py deleted file mode 100644 index 7b99f09196f5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows_v1beta.types import workflows - - -class ListWorkflowsPager: - """A pager for iterating through ``list_workflows`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workflows_v1beta.types.ListWorkflowsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workflows`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkflows`` requests and continue to iterate - through the ``workflows`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workflows_v1beta.types.ListWorkflowsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workflows.ListWorkflowsResponse], - request: workflows.ListWorkflowsRequest, - response: workflows.ListWorkflowsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workflows_v1beta.types.ListWorkflowsRequest): - The initial request object. - response (google.cloud.workflows_v1beta.types.ListWorkflowsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workflows.ListWorkflowsRequest(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[workflows.ListWorkflowsResponse]: - 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[workflows.Workflow]: - for page in self.pages: - yield from page.workflows - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkflowsAsyncPager: - """A pager for iterating through ``list_workflows`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workflows_v1beta.types.ListWorkflowsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workflows`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkflows`` requests and continue to iterate - through the ``workflows`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workflows_v1beta.types.ListWorkflowsResponse` - attributes are available on the 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[workflows.ListWorkflowsResponse]], - request: workflows.ListWorkflowsRequest, - response: workflows.ListWorkflowsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workflows_v1beta.types.ListWorkflowsRequest): - The initial request object. - response (google.cloud.workflows_v1beta.types.ListWorkflowsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workflows.ListWorkflowsRequest(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[workflows.ListWorkflowsResponse]: - 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[workflows.Workflow]: - async def async_generator(): - async for page in self.pages: - for response in page.workflows: - 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-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/README.rst b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/README.rst deleted file mode 100644 index f8fb5a859227..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`WorkflowsTransport` is the ABC for all transports. -- public child `WorkflowsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `WorkflowsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseWorkflowsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `WorkflowsRestTransport` 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-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/__init__.py deleted file mode 100644 index 6ebe8b349db7..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/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 WorkflowsTransport -from .grpc import WorkflowsGrpcTransport -from .grpc_asyncio import WorkflowsGrpcAsyncIOTransport -from .rest import WorkflowsRestTransport -from .rest import WorkflowsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WorkflowsTransport]] -_transport_registry['grpc'] = WorkflowsGrpcTransport -_transport_registry['grpc_asyncio'] = WorkflowsGrpcAsyncIOTransport -_transport_registry['rest'] = WorkflowsRestTransport - -__all__ = ( - 'WorkflowsTransport', - 'WorkflowsGrpcTransport', - 'WorkflowsGrpcAsyncIOTransport', - 'WorkflowsRestTransport', - 'WorkflowsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/base.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/base.py deleted file mode 100644 index a19a3ab2bc92..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/base.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. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.workflows_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.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.cloud.workflows_v1beta.types import workflows -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class WorkflowsTransport(abc.ABC): - """Abstract transport class for Workflows.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'workflows.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: 'workflows.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_workflows: gapic_v1.method.wrap_method( - self.list_workflows, - default_timeout=None, - client_info=client_info, - ), - self.get_workflow: gapic_v1.method.wrap_method( - self.get_workflow, - default_timeout=None, - client_info=client_info, - ), - self.create_workflow: gapic_v1.method.wrap_method( - self.create_workflow, - default_timeout=None, - client_info=client_info, - ), - self.delete_workflow: gapic_v1.method.wrap_method( - self.delete_workflow, - default_timeout=None, - client_info=client_info, - ), - self.update_workflow: gapic_v1.method.wrap_method( - self.update_workflow, - 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 list_workflows(self) -> Callable[ - [workflows.ListWorkflowsRequest], - Union[ - workflows.ListWorkflowsResponse, - Awaitable[workflows.ListWorkflowsResponse] - ]]: - raise NotImplementedError() - - @property - def get_workflow(self) -> Callable[ - [workflows.GetWorkflowRequest], - Union[ - workflows.Workflow, - Awaitable[workflows.Workflow] - ]]: - raise NotImplementedError() - - @property - def create_workflow(self) -> Callable[ - [workflows.CreateWorkflowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workflow(self) -> Callable[ - [workflows.DeleteWorkflowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workflow(self) -> Callable[ - [workflows.UpdateWorkflowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'WorkflowsTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc.py deleted file mode 100644 index 8603c89a0fe7..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc.py +++ /dev/null @@ -1,406 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.cloud.workflows_v1beta.types import workflows -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO - - -class WorkflowsGrpcTransport(WorkflowsTransport): - """gRPC backend transport for Workflows. - - Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workflows.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: 'workflows.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'workflows.googleapis.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.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_workflows(self) -> Callable[ - [workflows.ListWorkflowsRequest], - workflows.ListWorkflowsResponse]: - r"""Return a callable for the list workflows method over gRPC. - - Lists Workflows in a given project and location. - The default order is not specified. - - Returns: - Callable[[~.ListWorkflowsRequest], - ~.ListWorkflowsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workflows' not in self._stubs: - self._stubs['list_workflows'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/ListWorkflows', - request_serializer=workflows.ListWorkflowsRequest.serialize, - response_deserializer=workflows.ListWorkflowsResponse.deserialize, - ) - return self._stubs['list_workflows'] - - @property - def get_workflow(self) -> Callable[ - [workflows.GetWorkflowRequest], - workflows.Workflow]: - r"""Return a callable for the get workflow method over gRPC. - - Gets details of a single Workflow. - - Returns: - Callable[[~.GetWorkflowRequest], - ~.Workflow]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workflow' not in self._stubs: - self._stubs['get_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/GetWorkflow', - request_serializer=workflows.GetWorkflowRequest.serialize, - response_deserializer=workflows.Workflow.deserialize, - ) - return self._stubs['get_workflow'] - - @property - def create_workflow(self) -> Callable[ - [workflows.CreateWorkflowRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workflow method over gRPC. - - Creates a new workflow. If a workflow with the specified name - already exists in the specified project and location, the long - running operation will return - [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error. - - Returns: - Callable[[~.CreateWorkflowRequest], - ~.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 'create_workflow' not in self._stubs: - self._stubs['create_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/CreateWorkflow', - request_serializer=workflows.CreateWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workflow'] - - @property - def delete_workflow(self) -> Callable[ - [workflows.DeleteWorkflowRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workflow method over gRPC. - - Deletes a workflow with the specified name. - This method also cancels and deletes all running - executions of the workflow. - - Returns: - Callable[[~.DeleteWorkflowRequest], - ~.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 'delete_workflow' not in self._stubs: - self._stubs['delete_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/DeleteWorkflow', - request_serializer=workflows.DeleteWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workflow'] - - @property - def update_workflow(self) -> Callable[ - [workflows.UpdateWorkflowRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workflow method over gRPC. - - Updates an existing workflow. - Running this method has no impact on already running - executions of the workflow. A new revision of the - workflow may be created as a result of a successful - update operation. In that case, such revision will be - used in new workflow executions. - - Returns: - Callable[[~.UpdateWorkflowRequest], - ~.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 'update_workflow' not in self._stubs: - self._stubs['update_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/UpdateWorkflow', - request_serializer=workflows.UpdateWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workflow'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'WorkflowsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc_asyncio.py deleted file mode 100644 index ce0f29c4c03b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/grpc_asyncio.py +++ /dev/null @@ -1,447 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.workflows_v1beta.types import workflows -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkflowsTransport, DEFAULT_CLIENT_INFO -from .grpc import WorkflowsGrpcTransport - - -class WorkflowsGrpcAsyncIOTransport(WorkflowsTransport): - """gRPC AsyncIO backend transport for Workflows. - - Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workflows.googleapis.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 = 'workflows.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: 'workflows.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_workflows(self) -> Callable[ - [workflows.ListWorkflowsRequest], - Awaitable[workflows.ListWorkflowsResponse]]: - r"""Return a callable for the list workflows method over gRPC. - - Lists Workflows in a given project and location. - The default order is not specified. - - Returns: - Callable[[~.ListWorkflowsRequest], - Awaitable[~.ListWorkflowsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workflows' not in self._stubs: - self._stubs['list_workflows'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/ListWorkflows', - request_serializer=workflows.ListWorkflowsRequest.serialize, - response_deserializer=workflows.ListWorkflowsResponse.deserialize, - ) - return self._stubs['list_workflows'] - - @property - def get_workflow(self) -> Callable[ - [workflows.GetWorkflowRequest], - Awaitable[workflows.Workflow]]: - r"""Return a callable for the get workflow method over gRPC. - - Gets details of a single Workflow. - - Returns: - Callable[[~.GetWorkflowRequest], - Awaitable[~.Workflow]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workflow' not in self._stubs: - self._stubs['get_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/GetWorkflow', - request_serializer=workflows.GetWorkflowRequest.serialize, - response_deserializer=workflows.Workflow.deserialize, - ) - return self._stubs['get_workflow'] - - @property - def create_workflow(self) -> Callable[ - [workflows.CreateWorkflowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workflow method over gRPC. - - Creates a new workflow. If a workflow with the specified name - already exists in the specified project and location, the long - running operation will return - [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error. - - Returns: - Callable[[~.CreateWorkflowRequest], - 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 'create_workflow' not in self._stubs: - self._stubs['create_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/CreateWorkflow', - request_serializer=workflows.CreateWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workflow'] - - @property - def delete_workflow(self) -> Callable[ - [workflows.DeleteWorkflowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workflow method over gRPC. - - Deletes a workflow with the specified name. - This method also cancels and deletes all running - executions of the workflow. - - Returns: - Callable[[~.DeleteWorkflowRequest], - 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 'delete_workflow' not in self._stubs: - self._stubs['delete_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/DeleteWorkflow', - request_serializer=workflows.DeleteWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workflow'] - - @property - def update_workflow(self) -> Callable[ - [workflows.UpdateWorkflowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workflow method over gRPC. - - Updates an existing workflow. - Running this method has no impact on already running - executions of the workflow. A new revision of the - workflow may be created as a result of a successful - update operation. In that case, such revision will be - used in new workflow executions. - - Returns: - Callable[[~.UpdateWorkflowRequest], - 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 'update_workflow' not in self._stubs: - self._stubs['update_workflow'] = self.grpc_channel.unary_unary( - '/google.cloud.workflows.v1beta.Workflows/UpdateWorkflow', - request_serializer=workflows.UpdateWorkflowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workflow'] - - 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_workflows: self._wrap_method( - self.list_workflows, - default_timeout=None, - client_info=client_info, - ), - self.get_workflow: self._wrap_method( - self.get_workflow, - default_timeout=None, - client_info=client_info, - ), - self.create_workflow: self._wrap_method( - self.create_workflow, - default_timeout=None, - client_info=client_info, - ), - self.delete_workflow: self._wrap_method( - self.delete_workflow, - default_timeout=None, - client_info=client_info, - ), - self.update_workflow: self._wrap_method( - self.update_workflow, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'WorkflowsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest.py deleted file mode 100644 index cd5fb32c8e3c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest.py +++ /dev/null @@ -1,760 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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.cloud.workflows_v1beta.types import workflows -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseWorkflowsRestTransport -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 - - -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 WorkflowsRestInterceptor: - """Interceptor for Workflows. - - 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 WorkflowsRestTransport. - - .. code-block:: python - class MyCustomWorkflowsInterceptor(WorkflowsRestInterceptor): - def pre_create_workflow(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workflow(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workflow(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workflow(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workflow(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workflow(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workflows(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workflows(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workflow(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workflow(self, response): - logging.log(f"Received response: {response}") - return response - - transport = WorkflowsRestTransport(interceptor=MyCustomWorkflowsInterceptor()) - client = WorkflowsClient(transport=transport) - - - """ - def pre_create_workflow(self, request: workflows.CreateWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.CreateWorkflowRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workflow - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_create_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workflow - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_delete_workflow(self, request: workflows.DeleteWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.DeleteWorkflowRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workflow - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_delete_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workflow - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_get_workflow(self, request: workflows.GetWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.GetWorkflowRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workflow - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_get_workflow(self, response: workflows.Workflow) -> workflows.Workflow: - """Post-rpc interceptor for get_workflow - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_list_workflows(self, request: workflows.ListWorkflowsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.ListWorkflowsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workflows - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_list_workflows(self, response: workflows.ListWorkflowsResponse) -> workflows.ListWorkflowsResponse: - """Post-rpc interceptor for list_workflows - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - def pre_update_workflow(self, request: workflows.UpdateWorkflowRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workflows.UpdateWorkflowRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workflow - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workflows server. - """ - return request, metadata - - def post_update_workflow(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workflow - - Override in a subclass to manipulate the response - after it is returned by the Workflows server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class WorkflowsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: WorkflowsRestInterceptor - - -class WorkflowsRestTransport(_BaseWorkflowsRestTransport): - """REST backend synchronous transport for Workflows. - - Workflows is used to deploy and execute workflow programs. - Workflows makes sure the program executes reliably, despite - hardware and networking interruptions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'workflows.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[WorkflowsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'workflows.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 WorkflowsRestInterceptor() - 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.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta/{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="v1beta") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateWorkflow(_BaseWorkflowsRestTransport._BaseCreateWorkflow, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.CreateWorkflow") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workflows.CreateWorkflowRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workflow method over HTTP. - - Args: - request (~.workflows.CreateWorkflowRequest): - The request object. Request for the - [CreateWorkflow][google.cloud.workflows.v1beta.Workflows.CreateWorkflow] - method. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_http_options() - request, metadata = self._interceptor.pre_create_workflow(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_transcoded_request(http_options, request) - - body = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseCreateWorkflow._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._CreateWorkflow._get_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_create_workflow(resp) - return resp - - class _DeleteWorkflow(_BaseWorkflowsRestTransport._BaseDeleteWorkflow, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.DeleteWorkflow") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workflows.DeleteWorkflowRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workflow method over HTTP. - - Args: - request (~.workflows.DeleteWorkflowRequest): - The request object. Request for the - [DeleteWorkflow][google.cloud.workflows.v1beta.Workflows.DeleteWorkflow] - method. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_http_options() - request, metadata = self._interceptor.pre_delete_workflow(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._DeleteWorkflow._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, 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_delete_workflow(resp) - return resp - - class _GetWorkflow(_BaseWorkflowsRestTransport._BaseGetWorkflow, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.GetWorkflow") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workflows.GetWorkflowRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workflows.Workflow: - r"""Call the get workflow method over HTTP. - - Args: - request (~.workflows.GetWorkflowRequest): - The request object. Request for the - [GetWorkflow][google.cloud.workflows.v1beta.Workflows.GetWorkflow] - method. - retry (google.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. - - Returns: - ~.workflows.Workflow: - Workflow program to be executed by - Workflows. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_http_options() - request, metadata = self._interceptor.pre_get_workflow(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseGetWorkflow._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._GetWorkflow._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workflows.Workflow() - pb_resp = workflows.Workflow.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workflow(resp) - return resp - - class _ListWorkflows(_BaseWorkflowsRestTransport._BaseListWorkflows, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.ListWorkflows") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workflows.ListWorkflowsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workflows.ListWorkflowsResponse: - r"""Call the list workflows method over HTTP. - - Args: - request (~.workflows.ListWorkflowsRequest): - The request object. Request for the - [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] - method. - retry (google.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. - - Returns: - ~.workflows.ListWorkflowsResponse: - Response for the - [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] - method. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseListWorkflows._get_http_options() - request, metadata = self._interceptor.pre_list_workflows(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseListWorkflows._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseListWorkflows._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._ListWorkflows._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workflows.ListWorkflowsResponse() - pb_resp = workflows.ListWorkflowsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workflows(resp) - return resp - - class _UpdateWorkflow(_BaseWorkflowsRestTransport._BaseUpdateWorkflow, WorkflowsRestStub): - def __hash__(self): - return hash("WorkflowsRestTransport.UpdateWorkflow") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workflows.UpdateWorkflowRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workflow method over HTTP. - - Args: - request (~.workflows.UpdateWorkflowRequest): - The request object. Request for the - [UpdateWorkflow][google.cloud.workflows.v1beta.Workflows.UpdateWorkflow] - method. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_http_options() - request, metadata = self._interceptor.pre_update_workflow(request, metadata) - transcoded_request = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_transcoded_request(http_options, request) - - body = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_query_params_json(transcoded_request) - - # Send the request - response = WorkflowsRestTransport._UpdateWorkflow._get_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_update_workflow(resp) - return resp - - @property - def create_workflow(self) -> Callable[ - [workflows.CreateWorkflowRequest], - 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._CreateWorkflow(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workflow(self) -> Callable[ - [workflows.DeleteWorkflowRequest], - 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._DeleteWorkflow(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workflow(self) -> Callable[ - [workflows.GetWorkflowRequest], - workflows.Workflow]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkflow(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workflows(self) -> Callable[ - [workflows.ListWorkflowsRequest], - workflows.ListWorkflowsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkflows(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workflow(self) -> Callable[ - [workflows.UpdateWorkflowRequest], - 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._UpdateWorkflow(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'WorkflowsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest_base.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/transports/rest_base.py deleted file mode 100644 index d8f04cdadc72..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/services/workflows/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 WorkflowsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.workflows_v1beta.types import workflows -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseWorkflowsRestTransport(WorkflowsTransport): - """Base REST backend transport for Workflows. - - 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 = 'workflows.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: 'workflows.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 _BaseCreateWorkflow: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workflowId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{parent=projects/*/locations/*}/workflows', - 'body': 'workflow', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.CreateWorkflowRequest.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(_BaseWorkflowsRestTransport._BaseCreateWorkflow._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteWorkflow: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workflows/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.DeleteWorkflowRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkflowsRestTransport._BaseDeleteWorkflow._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetWorkflow: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/workflows/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.GetWorkflowRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkflowsRestTransport._BaseGetWorkflow._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkflows: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*}/workflows', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.ListWorkflowsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkflowsRestTransport._BaseListWorkflows._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateWorkflow: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{workflow.name=projects/*/locations/*/workflows/*}', - 'body': 'workflow', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workflows.UpdateWorkflowRequest.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(_BaseWorkflowsRestTransport._BaseUpdateWorkflow._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseWorkflowsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/__init__.py deleted file mode 100644 index 99bb09e40279..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/__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 .workflows import ( - CreateWorkflowRequest, - DeleteWorkflowRequest, - GetWorkflowRequest, - ListWorkflowsRequest, - ListWorkflowsResponse, - OperationMetadata, - UpdateWorkflowRequest, - Workflow, -) - -__all__ = ( - 'CreateWorkflowRequest', - 'DeleteWorkflowRequest', - 'GetWorkflowRequest', - 'ListWorkflowsRequest', - 'ListWorkflowsResponse', - 'OperationMetadata', - 'UpdateWorkflowRequest', - 'Workflow', -) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/workflows.py b/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/workflows.py deleted file mode 100644 index 484981fdb84c..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/google/cloud/workflows_v1beta/types/workflows.py +++ /dev/null @@ -1,403 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.cloud.workflows.v1beta', - manifest={ - 'Workflow', - 'ListWorkflowsRequest', - 'ListWorkflowsResponse', - 'GetWorkflowRequest', - 'CreateWorkflowRequest', - 'DeleteWorkflowRequest', - 'UpdateWorkflowRequest', - 'OperationMetadata', - }, -) - - -class Workflow(proto.Message): - r"""Workflow program to be executed by Workflows. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The resource name of the workflow. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - description (str): - Description of the workflow provided by the - user. Must be at most 1000 unicode characters - long. - state (google.cloud.workflows_v1beta.types.Workflow.State): - Output only. State of the workflow - deployment. - revision_id (str): - Output only. The revision of the workflow. A new revision of - a workflow is created as a result of updating the following - fields of a workflow: - - - ``source_code`` - - ``service_account`` The format is "000001-a4d", where the - first 6 characters define the zero-padded revision - ordinal number. They are followed by a hyphen and 3 - hexadecimal random characters. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp of when the - workflow was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update timestamp of the - workflow. - revision_create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp that the latest - revision of the workflow was created. - labels (MutableMapping[str, str]): - Labels associated with this workflow. - Labels can contain at most 64 entries. Keys and - values can be no longer than 63 characters and - can only contain lowercase letters, numeric - characters, underscores and dashes. Label keys - must start with a letter. International - characters are allowed. - service_account (str): - Name of the service account associated with the latest - workflow version. This service account represents the - identity of the workflow and determines what permissions the - workflow has. Format: - projects/{project}/serviceAccounts/{account} - - Using ``-`` as a wildcard for the ``{project}`` will infer - the project from the account. The ``{account}`` value can be - the ``email`` address or the ``unique_id`` of the service - account. - - If not provided, workflow will use the project's default - service account. Modifying this field for an existing - workflow results in a new workflow revision. - source_contents (str): - Workflow code to be executed. The size limit - is 32KB. - - This field is a member of `oneof`_ ``source_code``. - """ - class State(proto.Enum): - r"""Describes the current state of workflow deployment. More - states may be added in the future. - - Values: - STATE_UNSPECIFIED (0): - Invalid state. - ACTIVE (1): - The workflow has been deployed successfully - and is serving. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - state: State = proto.Field( - proto.ENUM, - number=3, - enum=State, - ) - revision_id: str = proto.Field( - proto.STRING, - number=4, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - revision_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - service_account: str = proto.Field( - proto.STRING, - number=9, - ) - source_contents: str = proto.Field( - proto.STRING, - number=10, - oneof='source_code', - ) - - -class ListWorkflowsRequest(proto.Message): - r"""Request for the - [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] - method. - - Attributes: - parent (str): - Required. Project and location from which the - workflows should be listed. Format: - projects/{project}/locations/{location} - page_size (int): - Maximum number of workflows to return per - call. The service may return fewer than this - value. If the value is not specified, a default - value of 500 will be used. The maximum permitted - value is 1000 and values greater than 1000 will - be coerced down to 1000. - page_token (str): - A page token, received from a previous ``ListWorkflows`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListWorkflows`` must match the call that provided the page - token. - filter (str): - Filter to restrict results to specific - workflows. - order_by (str): - Comma-separated list of fields that that - specify the order of the results. Default - sorting order for a field is ascending. To - specify descending order for a field, append a " - desc" suffix. - If not specified, the results will be returned - in an unspecified order. - """ - - 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, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListWorkflowsResponse(proto.Message): - r"""Response for the - [ListWorkflows][google.cloud.workflows.v1beta.Workflows.ListWorkflows] - method. - - Attributes: - workflows (MutableSequence[google.cloud.workflows_v1beta.types.Workflow]): - The workflows which match the request. - 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. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workflows: MutableSequence['Workflow'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workflow', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetWorkflowRequest(proto.Message): - r"""Request for the - [GetWorkflow][google.cloud.workflows.v1beta.Workflows.GetWorkflow] - method. - - Attributes: - name (str): - Required. Name of the workflow which - information should be retrieved. Format: - projects/{project}/locations/{location}/workflows/{workflow} - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateWorkflowRequest(proto.Message): - r"""Request for the - [CreateWorkflow][google.cloud.workflows.v1beta.Workflows.CreateWorkflow] - method. - - Attributes: - parent (str): - Required. Project and location in which the - workflow should be created. Format: - projects/{project}/locations/{location} - workflow (google.cloud.workflows_v1beta.types.Workflow): - Required. Workflow to be created. - workflow_id (str): - Required. The ID of the workflow to be created. It has to - fulfill the following requirements: - - - Must contain only letters, numbers, underscores and - hyphens. - - Must start with a letter. - - Must be between 1-64 characters. - - Must end with a number or a letter. - - Must be unique within the customer project and location. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workflow: 'Workflow' = proto.Field( - proto.MESSAGE, - number=2, - message='Workflow', - ) - workflow_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteWorkflowRequest(proto.Message): - r"""Request for the - [DeleteWorkflow][google.cloud.workflows.v1beta.Workflows.DeleteWorkflow] - method. - - Attributes: - name (str): - Required. Name of the workflow to be deleted. - Format: - projects/{project}/locations/{location}/workflows/{workflow} - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateWorkflowRequest(proto.Message): - r"""Request for the - [UpdateWorkflow][google.cloud.workflows.v1beta.Workflows.UpdateWorkflow] - method. - - Attributes: - workflow (google.cloud.workflows_v1beta.types.Workflow): - Required. Workflow to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - List of fields to be updated. If not present, - the entire workflow will be updated. - """ - - workflow: 'Workflow' = proto.Field( - proto.MESSAGE, - number=1, - message='Workflow', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class OperationMetadata(proto.Message): - r"""Represents the metadata of the long-running operation. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time the operation was created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time the operation finished running. - target (str): - Server-defined resource path for the target - of the operation. - verb (str): - Name of the verb executed by the operation. - api_version (str): - API version used to start the operation. - """ - - create_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, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - api_version: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/mypy.ini b/owl-bot-staging/google-cloud-workflows/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/noxfile.py b/owl-bot-staging/google-cloud-workflows/v1beta/noxfile.py deleted file mode 100644 index 312ca9cfb58e..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows' - -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/cloud/workflows_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/cloud/workflows_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-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json deleted file mode 100644 index c486937ea17a..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json +++ /dev/null @@ -1,667 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.workflows.executions.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-cloud-workflows-executions", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient", - "shortName": "ExecutionsAsyncClient" - }, - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient.cancel_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions.CancelExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions", - "shortName": "Executions" - }, - "shortName": "CancelExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1beta.types.CancelExecutionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", - "shortName": "cancel_execution" - }, - "description": "Sample for CancelExecution", - "file": "workflowexecutions_v1beta_generated_executions_cancel_execution_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1beta_generated_Executions_CancelExecution_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": "workflowexecutions_v1beta_generated_executions_cancel_execution_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient", - "shortName": "ExecutionsClient" - }, - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient.cancel_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions.CancelExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions", - "shortName": "Executions" - }, - "shortName": "CancelExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1beta.types.CancelExecutionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", - "shortName": "cancel_execution" - }, - "description": "Sample for CancelExecution", - "file": "workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1beta_generated_Executions_CancelExecution_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": "workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient", - "shortName": "ExecutionsAsyncClient" - }, - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient.create_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions.CreateExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions", - "shortName": "Executions" - }, - "shortName": "CreateExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1beta.types.CreateExecutionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "execution", - "type": "google.cloud.workflows.executions_v1beta.types.Execution" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", - "shortName": "create_execution" - }, - "description": "Sample for CreateExecution", - "file": "workflowexecutions_v1beta_generated_executions_create_execution_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1beta_generated_Executions_CreateExecution_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": "workflowexecutions_v1beta_generated_executions_create_execution_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient", - "shortName": "ExecutionsClient" - }, - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient.create_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions.CreateExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions", - "shortName": "Executions" - }, - "shortName": "CreateExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1beta.types.CreateExecutionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "execution", - "type": "google.cloud.workflows.executions_v1beta.types.Execution" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", - "shortName": "create_execution" - }, - "description": "Sample for CreateExecution", - "file": "workflowexecutions_v1beta_generated_executions_create_execution_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1beta_generated_Executions_CreateExecution_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": "workflowexecutions_v1beta_generated_executions_create_execution_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient", - "shortName": "ExecutionsAsyncClient" - }, - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient.get_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions.GetExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions", - "shortName": "Executions" - }, - "shortName": "GetExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1beta.types.GetExecutionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", - "shortName": "get_execution" - }, - "description": "Sample for GetExecution", - "file": "workflowexecutions_v1beta_generated_executions_get_execution_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1beta_generated_Executions_GetExecution_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": "workflowexecutions_v1beta_generated_executions_get_execution_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient", - "shortName": "ExecutionsClient" - }, - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient.get_execution", - "method": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions.GetExecution", - "service": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions", - "shortName": "Executions" - }, - "shortName": "GetExecution" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1beta.types.GetExecutionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1beta.types.Execution", - "shortName": "get_execution" - }, - "description": "Sample for GetExecution", - "file": "workflowexecutions_v1beta_generated_executions_get_execution_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1beta_generated_Executions_GetExecution_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": "workflowexecutions_v1beta_generated_executions_get_execution_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient", - "shortName": "ExecutionsAsyncClient" - }, - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsAsyncClient.list_executions", - "method": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions.ListExecutions", - "service": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions", - "shortName": "Executions" - }, - "shortName": "ListExecutions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1beta.services.executions.pagers.ListExecutionsAsyncPager", - "shortName": "list_executions" - }, - "description": "Sample for ListExecutions", - "file": "workflowexecutions_v1beta_generated_executions_list_executions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1beta_generated_Executions_ListExecutions_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": "workflowexecutions_v1beta_generated_executions_list_executions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient", - "shortName": "ExecutionsClient" - }, - "fullName": "google.cloud.workflows.executions_v1beta.ExecutionsClient.list_executions", - "method": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions.ListExecutions", - "service": { - "fullName": "google.cloud.workflows.executions.v1beta.Executions", - "shortName": "Executions" - }, - "shortName": "ListExecutions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows.executions_v1beta.types.ListExecutionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows.executions_v1beta.services.executions.pagers.ListExecutionsPager", - "shortName": "list_executions" - }, - "description": "Sample for ListExecutions", - "file": "workflowexecutions_v1beta_generated_executions_list_executions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflowexecutions_v1beta_generated_Executions_ListExecutions_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": "workflowexecutions_v1beta_generated_executions_list_executions_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json deleted file mode 100644 index e6e1022f77a9..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json +++ /dev/null @@ -1,844 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.workflows.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-cloud-workflows", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.create_workflow", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.CreateWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "CreateWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.CreateWorkflowRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workflow", - "type": "google.cloud.workflows_v1beta.types.Workflow" - }, - { - "name": "workflow_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workflow" - }, - "description": "Sample for CreateWorkflow", - "file": "workflows_v1beta_generated_workflows_create_workflow_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_CreateWorkflow_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1beta_generated_workflows_create_workflow_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.create_workflow", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.CreateWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "CreateWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.CreateWorkflowRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workflow", - "type": "google.cloud.workflows_v1beta.types.Workflow" - }, - { - "name": "workflow_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workflow" - }, - "description": "Sample for CreateWorkflow", - "file": "workflows_v1beta_generated_workflows_create_workflow_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_CreateWorkflow_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1beta_generated_workflows_create_workflow_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.delete_workflow", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.DeleteWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "DeleteWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.DeleteWorkflowRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_workflow" - }, - "description": "Sample for DeleteWorkflow", - "file": "workflows_v1beta_generated_workflows_delete_workflow_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_DeleteWorkflow_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1beta_generated_workflows_delete_workflow_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.delete_workflow", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.DeleteWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "DeleteWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.DeleteWorkflowRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_workflow" - }, - "description": "Sample for DeleteWorkflow", - "file": "workflows_v1beta_generated_workflows_delete_workflow_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_DeleteWorkflow_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1beta_generated_workflows_delete_workflow_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.get_workflow", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.GetWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "GetWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.GetWorkflowRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows_v1beta.types.Workflow", - "shortName": "get_workflow" - }, - "description": "Sample for GetWorkflow", - "file": "workflows_v1beta_generated_workflows_get_workflow_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_GetWorkflow_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": "workflows_v1beta_generated_workflows_get_workflow_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.get_workflow", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.GetWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "GetWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.GetWorkflowRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows_v1beta.types.Workflow", - "shortName": "get_workflow" - }, - "description": "Sample for GetWorkflow", - "file": "workflows_v1beta_generated_workflows_get_workflow_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_GetWorkflow_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": "workflows_v1beta_generated_workflows_get_workflow_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.list_workflows", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.ListWorkflows", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "ListWorkflows" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.ListWorkflowsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows_v1beta.services.workflows.pagers.ListWorkflowsAsyncPager", - "shortName": "list_workflows" - }, - "description": "Sample for ListWorkflows", - "file": "workflows_v1beta_generated_workflows_list_workflows_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_ListWorkflows_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": "workflows_v1beta_generated_workflows_list_workflows_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.list_workflows", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.ListWorkflows", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "ListWorkflows" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.ListWorkflowsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workflows_v1beta.services.workflows.pagers.ListWorkflowsPager", - "shortName": "list_workflows" - }, - "description": "Sample for ListWorkflows", - "file": "workflows_v1beta_generated_workflows_list_workflows_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_ListWorkflows_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": "workflows_v1beta_generated_workflows_list_workflows_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient", - "shortName": "WorkflowsAsyncClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsAsyncClient.update_workflow", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.UpdateWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "UpdateWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.UpdateWorkflowRequest" - }, - { - "name": "workflow", - "type": "google.cloud.workflows_v1beta.types.Workflow" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_workflow" - }, - "description": "Sample for UpdateWorkflow", - "file": "workflows_v1beta_generated_workflows_update_workflow_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_UpdateWorkflow_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1beta_generated_workflows_update_workflow_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient", - "shortName": "WorkflowsClient" - }, - "fullName": "google.cloud.workflows_v1beta.WorkflowsClient.update_workflow", - "method": { - "fullName": "google.cloud.workflows.v1beta.Workflows.UpdateWorkflow", - "service": { - "fullName": "google.cloud.workflows.v1beta.Workflows", - "shortName": "Workflows" - }, - "shortName": "UpdateWorkflow" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workflows_v1beta.types.UpdateWorkflowRequest" - }, - { - "name": "workflow", - "type": "google.cloud.workflows_v1beta.types.Workflow" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_workflow" - }, - "description": "Sample for UpdateWorkflow", - "file": "workflows_v1beta_generated_workflows_update_workflow_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workflows_v1beta_generated_Workflows_UpdateWorkflow_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workflows_v1beta_generated_workflows_update_workflow_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_async.py deleted file mode 100644 index 57077da8b609..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_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 CancelExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1beta_generated_Executions_CancelExecution_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1beta - - -async def sample_cancel_execution(): - # Create a client - client = executions_v1beta.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1beta.CancelExecutionRequest( - name="name_value", - ) - - # Make the request - response = await client.cancel_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1beta_generated_Executions_CancelExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_sync.py deleted file mode 100644 index 8a127df8dd29..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_cancel_execution_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 CancelExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1beta_generated_Executions_CancelExecution_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1beta - - -def sample_cancel_execution(): - # Create a client - client = executions_v1beta.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1beta.CancelExecutionRequest( - name="name_value", - ) - - # Make the request - response = client.cancel_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1beta_generated_Executions_CancelExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_async.py deleted file mode 100644 index 8486d9f53417..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_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 CreateExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1beta_generated_Executions_CreateExecution_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1beta - - -async def sample_create_execution(): - # Create a client - client = executions_v1beta.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1beta.CreateExecutionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1beta_generated_Executions_CreateExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_sync.py deleted file mode 100644 index 57fa24a51891..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_create_execution_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 CreateExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1beta_generated_Executions_CreateExecution_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1beta - - -def sample_create_execution(): - # Create a client - client = executions_v1beta.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1beta.CreateExecutionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1beta_generated_Executions_CreateExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_async.py deleted file mode 100644 index 8779820f1c99..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_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 GetExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1beta_generated_Executions_GetExecution_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1beta - - -async def sample_get_execution(): - # Create a client - client = executions_v1beta.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1beta.GetExecutionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1beta_generated_Executions_GetExecution_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_sync.py deleted file mode 100644 index 749dcd2bd082..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_get_execution_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 GetExecution -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1beta_generated_Executions_GetExecution_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1beta - - -def sample_get_execution(): - # Create a client - client = executions_v1beta.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1beta.GetExecutionRequest( - name="name_value", - ) - - # Make the request - response = client.get_execution(request=request) - - # Handle the response - print(response) - -# [END workflowexecutions_v1beta_generated_Executions_GetExecution_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_async.py deleted file mode 100644 index bdbc9b363786..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_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 ListExecutions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1beta_generated_Executions_ListExecutions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1beta - - -async def sample_list_executions(): - # Create a client - client = executions_v1beta.ExecutionsAsyncClient() - - # Initialize request argument(s) - request = executions_v1beta.ListExecutionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_executions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workflowexecutions_v1beta_generated_Executions_ListExecutions_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_sync.py deleted file mode 100644 index 18afcff69079..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflowexecutions_v1beta_generated_executions_list_executions_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 ListExecutions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows-executions - - -# [START workflowexecutions_v1beta_generated_Executions_ListExecutions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud.workflows import executions_v1beta - - -def sample_list_executions(): - # Create a client - client = executions_v1beta.ExecutionsClient() - - # Initialize request argument(s) - request = executions_v1beta.ListExecutionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_executions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workflowexecutions_v1beta_generated_Executions_ListExecutions_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_async.py deleted file mode 100644 index bf8988582165..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_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 CreateWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_CreateWorkflow_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -async def sample_create_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - workflow = workflows_v1beta.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1beta.CreateWorkflowRequest( - parent="parent_value", - workflow=workflow, - workflow_id="workflow_id_value", - ) - - # Make the request - operation = client.create_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workflows_v1beta_generated_Workflows_CreateWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_sync.py deleted file mode 100644 index 3b9aba651936..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_create_workflow_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 CreateWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_CreateWorkflow_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -def sample_create_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - workflow = workflows_v1beta.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1beta.CreateWorkflowRequest( - parent="parent_value", - workflow=workflow, - workflow_id="workflow_id_value", - ) - - # Make the request - operation = client.create_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workflows_v1beta_generated_Workflows_CreateWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_async.py deleted file mode 100644 index 8422fac54b60..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_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 DeleteWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_DeleteWorkflow_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -async def sample_delete_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1beta.DeleteWorkflowRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workflows_v1beta_generated_Workflows_DeleteWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_sync.py deleted file mode 100644 index c474e3cbe6c4..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_delete_workflow_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 DeleteWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_DeleteWorkflow_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -def sample_delete_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1beta.DeleteWorkflowRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workflows_v1beta_generated_Workflows_DeleteWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_async.py deleted file mode 100644 index 96602f24aad9..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_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 GetWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_GetWorkflow_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -async def sample_get_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1beta.GetWorkflowRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workflow(request=request) - - # Handle the response - print(response) - -# [END workflows_v1beta_generated_Workflows_GetWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_sync.py deleted file mode 100644 index 2a96994f32a9..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_get_workflow_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 GetWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_GetWorkflow_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -def sample_get_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1beta.GetWorkflowRequest( - name="name_value", - ) - - # Make the request - response = client.get_workflow(request=request) - - # Handle the response - print(response) - -# [END workflows_v1beta_generated_Workflows_GetWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_async.py deleted file mode 100644 index 4f85d7bebf66..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_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 ListWorkflows -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_ListWorkflows_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -async def sample_list_workflows(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - request = workflows_v1beta.ListWorkflowsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workflows(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workflows_v1beta_generated_Workflows_ListWorkflows_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_sync.py deleted file mode 100644 index e6b2ea2bf0f5..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_list_workflows_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 ListWorkflows -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_ListWorkflows_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -def sample_list_workflows(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - request = workflows_v1beta.ListWorkflowsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workflows(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workflows_v1beta_generated_Workflows_ListWorkflows_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_async.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_async.py deleted file mode 100644 index a3e9b76ccfbe..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_UpdateWorkflow_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -async def sample_update_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsAsyncClient() - - # Initialize request argument(s) - workflow = workflows_v1beta.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1beta.UpdateWorkflowRequest( - workflow=workflow, - ) - - # Make the request - operation = client.update_workflow(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workflows_v1beta_generated_Workflows_UpdateWorkflow_async] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_sync.py b/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_sync.py deleted file mode 100644 index 95d82e6a4c91..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/samples/generated_samples/workflows_v1beta_generated_workflows_update_workflow_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkflow -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workflows - - -# [START workflows_v1beta_generated_Workflows_UpdateWorkflow_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workflows_v1beta - - -def sample_update_workflow(): - # Create a client - client = workflows_v1beta.WorkflowsClient() - - # Initialize request argument(s) - workflow = workflows_v1beta.Workflow() - workflow.source_contents = "source_contents_value" - - request = workflows_v1beta.UpdateWorkflowRequest( - workflow=workflow, - ) - - # Make the request - operation = client.update_workflow(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workflows_v1beta_generated_Workflows_UpdateWorkflow_sync] diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_executions_v1beta_keywords.py b/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_executions_v1beta_keywords.py deleted file mode 100644 index 92c2e5d886c8..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_executions_v1beta_keywords.py +++ /dev/null @@ -1,179 +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 executionsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'cancel_execution': ('name', ), - 'create_execution': ('parent', 'execution', ), - 'get_execution': ('name', 'view', ), - 'list_executions': ('parent', 'page_size', 'page_token', 'view', ), - } - - 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=executionsCallTransformer(), -): - """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 executions 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-cloud-workflows/v1beta/scripts/fixup_workflows_v1beta_keywords.py b/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_workflows_v1beta_keywords.py deleted file mode 100644 index a0144dc0ff65..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/scripts/fixup_workflows_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 workflowsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_workflow': ('parent', 'workflow', 'workflow_id', ), - 'delete_workflow': ('name', ), - 'get_workflow': ('name', ), - 'list_workflows': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'update_workflow': ('workflow', '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=workflowsCallTransformer(), -): - """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 workflows 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-cloud-workflows/v1beta/setup.py b/owl-bot-staging/google-cloud-workflows/v1beta/setup.py deleted file mode 100644 index 85ca80f0b4ea..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows' - - -description = "Google Cloud Workflows API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/workflows/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-cloud-workflows" - -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-cloud-workflows/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/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-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_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-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/test_executions.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/test_executions.py deleted file mode 100644 index 065f19fcccb7..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/executions_v1beta/test_executions.py +++ /dev/null @@ -1,3145 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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.cloud.workflows.executions_v1beta.services.executions import ExecutionsAsyncClient -from google.cloud.workflows.executions_v1beta.services.executions import ExecutionsClient -from google.cloud.workflows.executions_v1beta.services.executions import pagers -from google.cloud.workflows.executions_v1beta.services.executions import transports -from google.cloud.workflows.executions_v1beta.types import executions -from google.oauth2 import service_account -from google.protobuf import timestamp_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 ExecutionsClient._get_default_mtls_endpoint(None) is None - assert ExecutionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ExecutionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ExecutionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ExecutionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ExecutionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ExecutionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ExecutionsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ExecutionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ExecutionsClient._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 ExecutionsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ExecutionsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ExecutionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ExecutionsClient._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 ExecutionsClient._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 ExecutionsClient._get_client_cert_source(None, False) is None - assert ExecutionsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ExecutionsClient._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 ExecutionsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ExecutionsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ExecutionsClient._DEFAULT_UNIVERSE - default_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ExecutionsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ExecutionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT - assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "always") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT - assert ExecutionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ExecutionsClient.DEFAULT_MTLS_ENDPOINT - assert ExecutionsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ExecutionsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ExecutionsClient._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 ExecutionsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ExecutionsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ExecutionsClient._get_universe_domain(None, None) == ExecutionsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ExecutionsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ExecutionsClient, "grpc"), - (ExecutionsAsyncClient, "grpc_asyncio"), -]) -def test_executions_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 == ( - 'workflowexecutions.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ExecutionsGrpcTransport, "grpc"), - (transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_executions_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", [ - (ExecutionsClient, "grpc"), - (ExecutionsAsyncClient, "grpc_asyncio"), -]) -def test_executions_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 == ( - 'workflowexecutions.googleapis.com:443' - ) - - -def test_executions_client_get_transport_class(): - transport = ExecutionsClient.get_transport_class() - available_transports = [ - transports.ExecutionsGrpcTransport, - ] - assert transport in available_transports - - transport = ExecutionsClient.get_transport_class("grpc") - assert transport == transports.ExecutionsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) -def test_executions_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(ExecutionsClient, '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(ExecutionsClient, '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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", "true"), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", "false"), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_executions_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", [ - ExecutionsClient, ExecutionsAsyncClient -]) -@mock.patch.object(ExecutionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExecutionsAsyncClient)) -def test_executions_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", [ - ExecutionsClient, ExecutionsAsyncClient -]) -@mock.patch.object(ExecutionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsClient)) -@mock.patch.object(ExecutionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ExecutionsAsyncClient)) -def test_executions_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ExecutionsClient._DEFAULT_UNIVERSE - default_endpoint = ExecutionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ExecutionsClient._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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc"), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_executions_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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", grpc_helpers), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_executions_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_executions_client_client_options_from_dict(): - with mock.patch('google.cloud.workflows.executions_v1beta.services.executions.transports.ExecutionsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ExecutionsClient( - 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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport, "grpc", grpc_helpers), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_executions_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( - "workflowexecutions.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="workflowexecutions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - executions.ListExecutionsRequest, - dict, -]) -def test_list_executions(request_type, transport: str = 'grpc'): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.ListExecutionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = executions.ListExecutionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExecutionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_executions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = executions.ListExecutionsRequest( - 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_executions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_executions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == executions.ListExecutionsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_executions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_executions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_executions] = mock_rpc - request = {} - client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_executions(request) - - # Establish that a new wrapper 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_executions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_executions in client._client._transport._wrapped_methods - - # 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_executions] = mock_rpc - - request = {} - await client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_executions(request) - - # Establish that a new wrapper 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_executions_async(transport: str = 'grpc_asyncio', request_type=executions.ListExecutionsRequest): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = executions.ListExecutionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExecutionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_executions_async_from_dict(): - await test_list_executions_async(request_type=dict) - -def test_list_executions_field_headers(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.ListExecutionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - call.return_value = executions.ListExecutionsResponse() - client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_executions_field_headers_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.ListExecutionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse()) - await client.list_executions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_executions_flattened(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.ListExecutionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_executions( - 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_executions_flattened_error(): - client = ExecutionsClient( - credentials=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_executions( - executions.ListExecutionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_executions_flattened_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.ListExecutionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_executions( - 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_executions_flattened_error_async(): - client = ExecutionsAsyncClient( - credentials=async_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_executions( - executions.ListExecutionsRequest(), - parent='parent_value', - ) - - -def test_list_executions_pager(transport_name: str = "grpc"): - client = ExecutionsClient( - 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_executions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - executions.Execution(), - ], - next_page_token='abc', - ), - executions.ListExecutionsResponse( - executions=[], - next_page_token='def', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - ], - next_page_token='ghi', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_executions(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, executions.Execution) - for i in results) -def test_list_executions_pages(transport_name: str = "grpc"): - client = ExecutionsClient( - 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_executions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - executions.Execution(), - ], - next_page_token='abc', - ), - executions.ListExecutionsResponse( - executions=[], - next_page_token='def', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - ], - next_page_token='ghi', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - ], - ), - RuntimeError, - ) - pages = list(client.list_executions(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_executions_async_pager(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - executions.Execution(), - ], - next_page_token='abc', - ), - executions.ListExecutionsResponse( - executions=[], - next_page_token='def', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - ], - next_page_token='ghi', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_executions(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, executions.Execution) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_executions_async_pages(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - executions.Execution(), - ], - next_page_token='abc', - ), - executions.ListExecutionsResponse( - executions=[], - next_page_token='def', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - ], - next_page_token='ghi', - ), - executions.ListExecutionsResponse( - executions=[ - executions.Execution(), - executions.Execution(), - ], - ), - 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_executions(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", [ - executions.CreateExecutionRequest, - dict, -]) -def test_create_execution(request_type, transport: str = 'grpc'): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - ) - response = client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = executions.CreateExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - - -def test_create_execution_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = executions.CreateExecutionRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_execution(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == executions.CreateExecutionRequest( - parent='parent_value', - ) - -def test_create_execution_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_execution in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_execution] = mock_rpc - request = {} - client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_execution(request) - - # Establish that a new wrapper 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_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_execution in client._client._transport._wrapped_methods - - # 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_execution] = mock_rpc - - request = {} - await client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_execution(request) - - # Establish that a new wrapper 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_execution_async(transport: str = 'grpc_asyncio', request_type=executions.CreateExecutionRequest): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - )) - response = await client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = executions.CreateExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - - -@pytest.mark.asyncio -async def test_create_execution_async_from_dict(): - await test_create_execution_async(request_type=dict) - -def test_create_execution_field_headers(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.CreateExecutionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_execution_field_headers_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.CreateExecutionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - await client.create_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_execution_flattened(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_execution( - parent='parent_value', - execution=executions.Execution(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].execution - mock_val = executions.Execution(name='name_value') - assert arg == mock_val - - -def test_create_execution_flattened_error(): - client = ExecutionsClient( - credentials=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_execution( - executions.CreateExecutionRequest(), - parent='parent_value', - execution=executions.Execution(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_execution_flattened_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_execution( - parent='parent_value', - execution=executions.Execution(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].execution - mock_val = executions.Execution(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_execution_flattened_error_async(): - client = ExecutionsAsyncClient( - credentials=async_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_execution( - executions.CreateExecutionRequest(), - parent='parent_value', - execution=executions.Execution(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - executions.GetExecutionRequest, - dict, -]) -def test_get_execution(request_type, transport: str = 'grpc'): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - ) - response = client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = executions.GetExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - - -def test_get_execution_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = executions.GetExecutionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_execution(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == executions.GetExecutionRequest( - name='name_value', - ) - -def test_get_execution_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_execution in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_execution] = mock_rpc - request = {} - client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_execution(request) - - # Establish that a new wrapper 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_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_execution in client._client._transport._wrapped_methods - - # 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_execution] = mock_rpc - - request = {} - await client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_execution(request) - - # Establish that a new wrapper 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_execution_async(transport: str = 'grpc_asyncio', request_type=executions.GetExecutionRequest): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - )) - response = await client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = executions.GetExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - - -@pytest.mark.asyncio -async def test_get_execution_async_from_dict(): - await test_get_execution_async(request_type=dict) - -def test_get_execution_field_headers(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.GetExecutionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_execution_field_headers_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.GetExecutionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - await client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_execution_flattened(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_execution( - 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_execution_flattened_error(): - client = ExecutionsClient( - credentials=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_execution( - executions.GetExecutionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_execution_flattened_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_execution( - 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_execution_flattened_error_async(): - client = ExecutionsAsyncClient( - credentials=async_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_execution( - executions.GetExecutionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - executions.CancelExecutionRequest, - dict, -]) -def test_cancel_execution(request_type, transport: str = 'grpc'): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - ) - response = client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = executions.CancelExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - - -def test_cancel_execution_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = executions.CancelExecutionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.cancel_execution(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == executions.CancelExecutionRequest( - name='name_value', - ) - -def test_cancel_execution_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.cancel_execution in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.cancel_execution] = mock_rpc - request = {} - client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.cancel_execution(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_cancel_execution_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.cancel_execution in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.cancel_execution] = mock_rpc - - request = {} - await client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.cancel_execution(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_cancel_execution_async(transport: str = 'grpc_asyncio', request_type=executions.CancelExecutionRequest): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - )) - response = await client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = executions.CancelExecutionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, executions.Execution) - assert response.name == 'name_value' - assert response.state == executions.Execution.State.ACTIVE - assert response.argument == 'argument_value' - assert response.result == 'result_value' - assert response.workflow_revision_id == 'workflow_revision_id_value' - - -@pytest.mark.asyncio -async def test_cancel_execution_async_from_dict(): - await test_cancel_execution_async(request_type=dict) - -def test_cancel_execution_field_headers(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.CancelExecutionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_cancel_execution_field_headers_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = executions.CancelExecutionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - await client.cancel_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_cancel_execution_flattened(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.cancel_execution( - 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_cancel_execution_flattened_error(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.cancel_execution( - executions.CancelExecutionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_cancel_execution_flattened_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = executions.Execution() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.cancel_execution( - 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_cancel_execution_flattened_error_async(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.cancel_execution( - executions.CancelExecutionRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExecutionsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ExecutionsClient( - 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 = ExecutionsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExecutionsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ExecutionsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ExecutionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ExecutionsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ExecutionsGrpcTransport, - transports.ExecutionsGrpcAsyncIOTransport, -]) -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 = ExecutionsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ExecutionsClient( - 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_executions_empty_call_grpc(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - call.return_value = executions.ListExecutionsResponse() - client.list_executions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.ListExecutionsRequest() - - assert args[0] == request_msg - - -# This 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_execution_empty_call_grpc(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.create_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.CreateExecutionRequest() - - assert args[0] == request_msg - - -# This 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_execution_empty_call_grpc(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.get_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.GetExecutionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_cancel_execution_empty_call_grpc(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - call.return_value = executions.Execution() - client.cancel_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.CancelExecutionRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ExecutionsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ExecutionsAsyncClient( - 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_executions_empty_call_grpc_asyncio(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_executions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.ListExecutionsResponse( - next_page_token='next_page_token_value', - )) - await client.list_executions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.ListExecutionsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_execution_empty_call_grpc_asyncio(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - )) - await client.create_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.CreateExecutionRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_execution_empty_call_grpc_asyncio(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - )) - await client.get_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.GetExecutionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_cancel_execution_empty_call_grpc_asyncio(): - client = ExecutionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.cancel_execution), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(executions.Execution( - name='name_value', - state=executions.Execution.State.ACTIVE, - argument='argument_value', - result='result_value', - workflow_revision_id='workflow_revision_id_value', - )) - await client.cancel_execution(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = executions.CancelExecutionRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ExecutionsGrpcTransport, - ) - -def test_executions_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ExecutionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_executions_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.workflows.executions_v1beta.services.executions.transports.ExecutionsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ExecutionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_executions', - 'create_execution', - 'get_execution', - 'cancel_execution', - ) - 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_executions_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workflows.executions_v1beta.services.executions.transports.ExecutionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExecutionsTransport( - 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_executions_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workflows.executions_v1beta.services.executions.transports.ExecutionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExecutionsTransport() - adc.assert_called_once() - - -def test_executions_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) - ExecutionsClient() - 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.ExecutionsGrpcTransport, - transports.ExecutionsGrpcAsyncIOTransport, - ], -) -def test_executions_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.ExecutionsGrpcTransport, - transports.ExecutionsGrpcAsyncIOTransport, - ], -) -def test_executions_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.ExecutionsGrpcTransport, grpc_helpers), - (transports.ExecutionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_executions_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( - "workflowexecutions.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="workflowexecutions.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) -def test_executions_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_executions_host_no_port(transport_name): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workflowexecutions.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workflowexecutions.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_executions_host_with_port(transport_name): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workflowexecutions.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workflowexecutions.googleapis.com:8000' - ) - -def test_executions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ExecutionsGrpcTransport( - 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_executions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ExecutionsGrpcAsyncIOTransport( - 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.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) -def test_executions_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.ExecutionsGrpcTransport, transports.ExecutionsGrpcAsyncIOTransport]) -def test_executions_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_execution_path(): - project = "squid" - location = "clam" - workflow = "whelk" - execution = "octopus" - expected = "projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}".format(project=project, location=location, workflow=workflow, execution=execution, ) - actual = ExecutionsClient.execution_path(project, location, workflow, execution) - assert expected == actual - - -def test_parse_execution_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "workflow": "cuttlefish", - "execution": "mussel", - } - path = ExecutionsClient.execution_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_execution_path(path) - assert expected == actual - -def test_workflow_path(): - project = "winkle" - location = "nautilus" - workflow = "scallop" - expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - actual = ExecutionsClient.workflow_path(project, location, workflow) - assert expected == actual - - -def test_parse_workflow_path(): - expected = { - "project": "abalone", - "location": "squid", - "workflow": "clam", - } - path = ExecutionsClient.workflow_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_workflow_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ExecutionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ExecutionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ExecutionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ExecutionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ExecutionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ExecutionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ExecutionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ExecutionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.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 = ExecutionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ExecutionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.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.ExecutionsTransport, '_prep_wrapped_messages') as prep: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ExecutionsTransport, '_prep_wrapped_messages') as prep: - transport_class = ExecutionsClient.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 = ExecutionsClient( - 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 = ExecutionsAsyncClient( - 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_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = ExecutionsClient( - 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", [ - (ExecutionsClient, transports.ExecutionsGrpcTransport), - (ExecutionsAsyncClient, transports.ExecutionsGrpcAsyncIOTransport), -]) -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-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/__init__.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_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-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/test_workflows.py b/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/test_workflows.py deleted file mode 100644 index f63551e82c3b..000000000000 --- a/owl-bot-staging/google-cloud-workflows/v1beta/tests/unit/gapic/workflows_v1beta/test_workflows.py +++ /dev/null @@ -1,5286 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workflows_v1beta.services.workflows import WorkflowsAsyncClient -from google.cloud.workflows_v1beta.services.workflows import WorkflowsClient -from google.cloud.workflows_v1beta.services.workflows import pagers -from google.cloud.workflows_v1beta.services.workflows import transports -from google.cloud.workflows_v1beta.types import workflows -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -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 WorkflowsClient._get_default_mtls_endpoint(None) is None - assert WorkflowsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WorkflowsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WorkflowsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WorkflowsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WorkflowsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert WorkflowsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert WorkflowsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert WorkflowsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - WorkflowsClient._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 WorkflowsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert WorkflowsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert WorkflowsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - WorkflowsClient._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 WorkflowsClient._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 WorkflowsClient._get_client_cert_source(None, False) is None - assert WorkflowsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert WorkflowsClient._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 WorkflowsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert WorkflowsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = WorkflowsClient._DEFAULT_UNIVERSE - default_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert WorkflowsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert WorkflowsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT - assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "always") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT - assert WorkflowsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WorkflowsClient.DEFAULT_MTLS_ENDPOINT - assert WorkflowsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert WorkflowsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - WorkflowsClient._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 WorkflowsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert WorkflowsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert WorkflowsClient._get_universe_domain(None, None) == WorkflowsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - WorkflowsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (WorkflowsClient, "grpc"), - (WorkflowsAsyncClient, "grpc_asyncio"), - (WorkflowsClient, "rest"), -]) -def test_workflows_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 == ( - 'workflows.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workflows.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WorkflowsGrpcTransport, "grpc"), - (transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.WorkflowsRestTransport, "rest"), -]) -def test_workflows_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", [ - (WorkflowsClient, "grpc"), - (WorkflowsAsyncClient, "grpc_asyncio"), - (WorkflowsClient, "rest"), -]) -def test_workflows_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 == ( - 'workflows.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workflows.googleapis.com' - ) - - -def test_workflows_client_get_transport_class(): - transport = WorkflowsClient.get_transport_class() - available_transports = [ - transports.WorkflowsGrpcTransport, - transports.WorkflowsRestTransport, - ] - assert transport in available_transports - - transport = WorkflowsClient.get_transport_class("grpc") - assert transport == transports.WorkflowsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), -]) -@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) -def test_workflows_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(WorkflowsClient, '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(WorkflowsClient, '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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", "true"), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", "false"), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest", "true"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest", "false"), -]) -@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_workflows_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", [ - WorkflowsClient, WorkflowsAsyncClient -]) -@mock.patch.object(WorkflowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkflowsAsyncClient)) -def test_workflows_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", [ - WorkflowsClient, WorkflowsAsyncClient -]) -@mock.patch.object(WorkflowsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsClient)) -@mock.patch.object(WorkflowsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkflowsAsyncClient)) -def test_workflows_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = WorkflowsClient._DEFAULT_UNIVERSE - default_endpoint = WorkflowsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WorkflowsClient._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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc"), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest"), -]) -def test_workflows_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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", grpc_helpers), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (WorkflowsClient, transports.WorkflowsRestTransport, "rest", None), -]) -def test_workflows_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_workflows_client_client_options_from_dict(): - with mock.patch('google.cloud.workflows_v1beta.services.workflows.transports.WorkflowsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WorkflowsClient( - 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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport, "grpc", grpc_helpers), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_workflows_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( - "workflows.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="workflows.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - workflows.ListWorkflowsRequest, - dict, -]) -def test_list_workflows(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.ListWorkflowsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.ListWorkflowsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkflowsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workflows_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.ListWorkflowsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workflows(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.ListWorkflowsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_workflows_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflows in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflows] = mock_rpc - request = {} - client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workflows(request) - - # Establish that a new wrapper 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_workflows_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflows in client._client._transport._wrapped_methods - - # 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_workflows] = mock_rpc - - request = {} - await client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workflows(request) - - # Establish that a new wrapper 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_workflows_async(transport: str = 'grpc_asyncio', request_type=workflows.ListWorkflowsRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.ListWorkflowsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkflowsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workflows_async_from_dict(): - await test_list_workflows_async(request_type=dict) - -def test_list_workflows_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.ListWorkflowsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - call.return_value = workflows.ListWorkflowsResponse() - client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflows_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.ListWorkflowsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse()) - await client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflows_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.ListWorkflowsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workflows( - 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_workflows_flattened_error(): - client = WorkflowsClient( - credentials=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_workflows( - workflows.ListWorkflowsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workflows_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.ListWorkflowsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workflows( - 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_workflows_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflows( - workflows.ListWorkflowsRequest(), - parent='parent_value', - ) - - -def test_list_workflows_pager(transport_name: str = "grpc"): - client = WorkflowsClient( - 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_workflows), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workflows(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, workflows.Workflow) - for i in results) -def test_list_workflows_pages(transport_name: str = "grpc"): - client = WorkflowsClient( - 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_workflows), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workflows(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_workflows_async_pager(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workflows(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, workflows.Workflow) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workflows_async_pages(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - 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_workflows(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", [ - workflows.GetWorkflowRequest, - dict, -]) -def test_get_workflow(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.Workflow( - name='name_value', - description='description_value', - state=workflows.Workflow.State.ACTIVE, - revision_id='revision_id_value', - service_account='service_account_value', - source_contents='source_contents_value', - ) - response = client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.GetWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workflows.Workflow) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == workflows.Workflow.State.ACTIVE - assert response.revision_id == 'revision_id_value' - assert response.service_account == 'service_account_value' - - -def test_get_workflow_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.GetWorkflowRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_workflow(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.GetWorkflowRequest( - name='name_value', - ) - -def test_get_workflow_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workflow] = mock_rpc - request = {} - client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workflow(request) - - # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflow in client._client._transport._wrapped_methods - - # 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_workflow] = mock_rpc - - request = {} - await client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_workflow(request) - - # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.GetWorkflowRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow( - name='name_value', - description='description_value', - state=workflows.Workflow.State.ACTIVE, - revision_id='revision_id_value', - service_account='service_account_value', - )) - response = await client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.GetWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workflows.Workflow) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == workflows.Workflow.State.ACTIVE - assert response.revision_id == 'revision_id_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_workflow_async_from_dict(): - await test_get_workflow_async(request_type=dict) - -def test_get_workflow_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.GetWorkflowRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - call.return_value = workflows.Workflow() - client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.GetWorkflowRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow()) - await client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.Workflow() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workflow( - 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_workflow_flattened_error(): - client = WorkflowsClient( - credentials=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_workflow( - workflows.GetWorkflowRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workflow_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workflows.Workflow() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workflow( - 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_workflow_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflow( - workflows.GetWorkflowRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workflows.CreateWorkflowRequest, - dict, -]) -def test_create_workflow(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.CreateWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workflow_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.CreateWorkflowRequest( - parent='parent_value', - workflow_id='workflow_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_workflow(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.CreateWorkflowRequest( - parent='parent_value', - workflow_id='workflow_id_value', - ) - -def test_create_workflow_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - request = {} - client.create_workflow(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.create_workflow(request) - - # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflow in client._client._transport._wrapped_methods - - # 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_workflow] = mock_rpc - - request = {} - await client.create_workflow(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.create_workflow(request) - - # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.CreateWorkflowRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__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.create_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.CreateWorkflowRequest() - 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_create_workflow_async_from_dict(): - await test_create_workflow_async(request_type=dict) - -def test_create_workflow_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.CreateWorkflowRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.CreateWorkflowRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_workflow( - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_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].workflow - mock_val = workflows.Workflow(name='name_value') - assert arg == mock_val - arg = args[0].workflow_id - mock_val = 'workflow_id_value' - assert arg == mock_val - - -def test_create_workflow_flattened_error(): - client = WorkflowsClient( - credentials=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_workflow( - workflows.CreateWorkflowRequest(), - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workflow_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_workflow( - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_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].workflow - mock_val = workflows.Workflow(name='name_value') - assert arg == mock_val - arg = args[0].workflow_id - mock_val = 'workflow_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workflow_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflow( - workflows.CreateWorkflowRequest(), - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workflows.DeleteWorkflowRequest, - dict, -]) -def test_delete_workflow(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.DeleteWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workflow_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.DeleteWorkflowRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_workflow(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.DeleteWorkflowRequest( - name='name_value', - ) - -def test_delete_workflow_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - request = {} - client.delete_workflow(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.delete_workflow(request) - - # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflow in client._client._transport._wrapped_methods - - # 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_workflow] = mock_rpc - - request = {} - await client.delete_workflow(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.delete_workflow(request) - - # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.DeleteWorkflowRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__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.delete_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.DeleteWorkflowRequest() - 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_delete_workflow_async_from_dict(): - await test_delete_workflow_async(request_type=dict) - -def test_delete_workflow_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.DeleteWorkflowRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.DeleteWorkflowRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workflow_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_workflow( - 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_workflow_flattened_error(): - client = WorkflowsClient( - credentials=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_workflow( - workflows.DeleteWorkflowRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workflow_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_workflow( - 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_workflow_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflow( - workflows.DeleteWorkflowRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workflows.UpdateWorkflowRequest, - dict, -]) -def test_update_workflow(request_type, transport: str = 'grpc'): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workflows.UpdateWorkflowRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workflow_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workflows.UpdateWorkflowRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_workflow(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workflows.UpdateWorkflowRequest( - ) - -def test_update_workflow_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - request = {} - client.update_workflow(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.update_workflow(request) - - # Establish that a new wrapper 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_workflow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workflow in client._client._transport._wrapped_methods - - # 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_workflow] = mock_rpc - - request = {} - await client.update_workflow(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.update_workflow(request) - - # Establish that a new wrapper 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_workflow_async(transport: str = 'grpc_asyncio', request_type=workflows.UpdateWorkflowRequest): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workflow), - '__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.update_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workflows.UpdateWorkflowRequest() - 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_update_workflow_async_from_dict(): - await test_update_workflow_async(request_type=dict) - -def test_update_workflow_field_headers(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.UpdateWorkflowRequest() - - request.workflow.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workflow.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workflow_field_headers_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workflows.UpdateWorkflowRequest() - - request.workflow.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workflow.name=name_value', - ) in kw['metadata'] - - -def test_update_workflow_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_workflow( - workflow=workflows.Workflow(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].workflow - mock_val = workflows.Workflow(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_workflow_flattened_error(): - client = WorkflowsClient( - credentials=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_workflow( - workflows.UpdateWorkflowRequest(), - workflow=workflows.Workflow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workflow_flattened_async(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_workflow( - workflow=workflows.Workflow(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].workflow - mock_val = workflows.Workflow(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_workflow_flattened_error_async(): - client = WorkflowsAsyncClient( - credentials=async_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_workflow( - workflows.UpdateWorkflowRequest(), - workflow=workflows.Workflow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_workflows_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflows in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflows] = mock_rpc - - request = {} - client.list_workflows(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workflows(request) - - # Establish 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_workflows_rest_required_fields(request_type=workflows.ListWorkflowsRequest): - transport_class = transports.WorkflowsRestTransport - - 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_workflows._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_workflows._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "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 = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workflows.ListWorkflowsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workflows.ListWorkflowsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_workflows(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workflows_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workflows._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workflows_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workflows.ListWorkflowsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/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 = workflows.ListWorkflowsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_workflows(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workflows" % client.transport._host, args[1]) - - -def test_list_workflows_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflows( - workflows.ListWorkflowsRequest(), - parent='parent_value', - ) - - -def test_list_workflows_rest_pager(transport: str = 'rest'): - client = WorkflowsClient( - 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 = ( - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - workflows.Workflow(), - ], - next_page_token='abc', - ), - workflows.ListWorkflowsResponse( - workflows=[], - next_page_token='def', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - ], - next_page_token='ghi', - ), - workflows.ListWorkflowsResponse( - workflows=[ - workflows.Workflow(), - workflows.Workflow(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workflows.ListWorkflowsResponse.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/locations/sample2'} - - pager = client.list_workflows(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workflows.Workflow) - for i in results) - - pages = list(client.list_workflows(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_workflow_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workflow] = mock_rpc - - request = {} - client.get_workflow(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workflow(request) - - # Establish 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_workflow_rest_required_fields(request_type=workflows.GetWorkflowRequest): - transport_class = transports.WorkflowsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workflow._get_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_workflow._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workflows.Workflow() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workflows.Workflow.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_workflow(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workflow_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workflow._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_workflow_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workflows.Workflow() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workflows/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 = workflows.Workflow.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_workflow(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workflows/*}" % client.transport._host, args[1]) - - -def test_get_workflow_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflow( - workflows.GetWorkflowRequest(), - name='name_value', - ) - - -def test_create_workflow_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - - request = {} - client.create_workflow(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.create_workflow(request) - - # Establish 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_workflow_rest_required_fields(request_type=workflows.CreateWorkflowRequest): - transport_class = transports.WorkflowsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workflow_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 "workflowId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workflow._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workflowId" in jsonified_request - assert jsonified_request["workflowId"] == request_init["workflow_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workflowId"] = 'workflow_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workflow._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("workflow_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 "workflowId" in jsonified_request - assert jsonified_request["workflowId"] == 'workflow_id_value' - - client = WorkflowsClient( - 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 - - response = client.create_workflow(request) - - expected_params = [ - ( - "workflowId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workflow_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workflow._get_unset_required_fields({}) - assert set(unset_fields) == (set(("workflowId", )) & set(("parent", "workflow", "workflowId", ))) - - -def test_create_workflow_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_id_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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workflow(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workflows" % client.transport._host, args[1]) - - -def test_create_workflow_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflow( - workflows.CreateWorkflowRequest(), - parent='parent_value', - workflow=workflows.Workflow(name='name_value'), - workflow_id='workflow_id_value', - ) - - -def test_delete_workflow_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - - request = {} - client.delete_workflow(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.delete_workflow(request) - - # Establish 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_workflow_rest_required_fields(request_type=workflows.DeleteWorkflowRequest): - transport_class = transports.WorkflowsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workflow._get_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_workflow._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkflowsClient( - 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': "delete", - '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 - - response = client.delete_workflow(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workflow_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workflow._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_workflow_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workflows/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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workflow(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workflows/*}" % client.transport._host, args[1]) - - -def test_delete_workflow_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflow( - workflows.DeleteWorkflowRequest(), - name='name_value', - ) - - -def test_update_workflow_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workflow in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workflow] = mock_rpc - - request = {} - client.update_workflow(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.update_workflow(request) - - # Establish 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_workflow_rest_required_fields(request_type=workflows.UpdateWorkflowRequest): - transport_class = transports.WorkflowsRestTransport - - 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_workflow._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_workflow._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 = WorkflowsClient( - 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': "patch", - '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 - - response = client.update_workflow(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workflow_rest_unset_required_fields(): - transport = transports.WorkflowsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workflow._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("workflow", ))) - - -def test_update_workflow_rest_flattened(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - workflow=workflows.Workflow(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_workflow(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{workflow.name=projects/*/locations/*/workflows/*}" % client.transport._host, args[1]) - - -def test_update_workflow_rest_flattened_error(transport: str = 'rest'): - client = WorkflowsClient( - credentials=ga_credentials.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_workflow( - workflows.UpdateWorkflowRequest(), - workflow=workflows.Workflow(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.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkflowsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WorkflowsClient( - 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 = WorkflowsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkflowsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WorkflowsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkflowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WorkflowsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WorkflowsGrpcTransport, - transports.WorkflowsGrpcAsyncIOTransport, - transports.WorkflowsRestTransport, -]) -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 = WorkflowsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = WorkflowsClient( - 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_workflows_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - call.return_value = workflows.ListWorkflowsResponse() - client.list_workflows(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.ListWorkflowsRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - call.return_value = workflows.Workflow() - client.get_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.GetWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.CreateWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.DeleteWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_grpc(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.UpdateWorkflowRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = WorkflowsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = WorkflowsAsyncClient( - 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_workflows_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.ListWorkflowsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_workflows(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.ListWorkflowsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workflows.Workflow( - name='name_value', - description='description_value', - state=workflows.Workflow.State.ACTIVE, - revision_id='revision_id_value', - service_account='service_account_value', - )) - await client.get_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.GetWorkflowRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__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.create_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.CreateWorkflowRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__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.delete_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.DeleteWorkflowRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workflow_empty_call_grpc_asyncio(): - client = WorkflowsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__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.update_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.UpdateWorkflowRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = WorkflowsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_workflows_rest_bad_request(request_type=workflows.ListWorkflowsRequest): - client = WorkflowsClient( - 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 - client.list_workflows(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.ListWorkflowsRequest, - dict, -]) -def test_list_workflows_rest_call_success(request_type): - client = WorkflowsClient( - 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 = workflows.ListWorkflowsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workflows.ListWorkflowsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_workflows(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkflowsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workflows_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "post_list_workflows") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_list_workflows") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.ListWorkflowsRequest.pb(workflows.ListWorkflowsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workflows.ListWorkflowsResponse.to_json(workflows.ListWorkflowsResponse()) - req.return_value.content = return_value - - request = workflows.ListWorkflowsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workflows.ListWorkflowsResponse() - - client.list_workflows(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workflow_rest_bad_request(request_type=workflows.GetWorkflowRequest): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 - client.get_workflow(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.GetWorkflowRequest, - dict, -]) -def test_get_workflow_rest_call_success(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 = workflows.Workflow( - name='name_value', - description='description_value', - state=workflows.Workflow.State.ACTIVE, - revision_id='revision_id_value', - service_account='service_account_value', - source_contents='source_contents_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 = workflows.Workflow.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_workflow(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workflows.Workflow) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == workflows.Workflow.State.ACTIVE - assert response.revision_id == 'revision_id_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workflow_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "post_get_workflow") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_get_workflow") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.GetWorkflowRequest.pb(workflows.GetWorkflowRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workflows.Workflow.to_json(workflows.Workflow()) - req.return_value.content = return_value - - request = workflows.GetWorkflowRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workflows.Workflow() - - client.get_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workflow_rest_bad_request(request_type=workflows.CreateWorkflowRequest): - client = WorkflowsClient( - 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 - client.create_workflow(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.CreateWorkflowRequest, - dict, -]) -def test_create_workflow_rest_call_success(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["workflow"] = {'name': 'name_value', 'description': 'description_value', 'state': 1, 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'revision_create_time': {}, 'labels': {}, 'service_account': 'service_account_value', 'source_contents': 'source_contents_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 = workflows.CreateWorkflowRequest.meta.fields["workflow"] - - 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["workflow"].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["workflow"][field])): - del request_init["workflow"][field][i][subfield] - else: - del request_init["workflow"][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 = 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 - response = client.create_workflow(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_create_workflow_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_create_workflow") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_create_workflow") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.CreateWorkflowRequest.pb(workflows.CreateWorkflowRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workflows.CreateWorkflowRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workflow_rest_bad_request(request_type=workflows.DeleteWorkflowRequest): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 - client.delete_workflow(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.DeleteWorkflowRequest, - dict, -]) -def test_delete_workflow_rest_call_success(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workflows/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 = 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 - response = client.delete_workflow(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_delete_workflow_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_delete_workflow") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_delete_workflow") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.DeleteWorkflowRequest.pb(workflows.DeleteWorkflowRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workflows.DeleteWorkflowRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workflow_rest_bad_request(request_type=workflows.UpdateWorkflowRequest): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/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 - client.update_workflow(request) - - -@pytest.mark.parametrize("request_type", [ - workflows.UpdateWorkflowRequest, - dict, -]) -def test_update_workflow_rest_call_success(request_type): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workflow': {'name': 'projects/sample1/locations/sample2/workflows/sample3'}} - request_init["workflow"] = {'name': 'projects/sample1/locations/sample2/workflows/sample3', 'description': 'description_value', 'state': 1, 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'revision_create_time': {}, 'labels': {}, 'service_account': 'service_account_value', 'source_contents': 'source_contents_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 = workflows.UpdateWorkflowRequest.meta.fields["workflow"] - - 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["workflow"].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["workflow"][field])): - del request_init["workflow"][field][i][subfield] - else: - del request_init["workflow"][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 = 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 - response = client.update_workflow(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_update_workflow_rest_interceptors(null_interceptor): - transport = transports.WorkflowsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkflowsRestInterceptor(), - ) - client = WorkflowsClient(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.WorkflowsRestInterceptor, "post_update_workflow") as post, \ - mock.patch.object(transports.WorkflowsRestInterceptor, "pre_update_workflow") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workflows.UpdateWorkflowRequest.pb(workflows.UpdateWorkflowRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workflows.UpdateWorkflowRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workflow(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = WorkflowsClient( - 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_workflows_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workflows), - '__call__') as call: - client.list_workflows(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.ListWorkflowsRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workflow), - '__call__') as call: - client.get_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.GetWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workflow), - '__call__') as call: - client.create_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.CreateWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workflow), - '__call__') as call: - client.delete_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.DeleteWorkflowRequest() - - assert args[0] == request_msg - - -# This 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_workflow_empty_call_rest(): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workflow), - '__call__') as call: - client.update_workflow(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workflows.UpdateWorkflowRequest() - - assert args[0] == request_msg - - -def test_workflows_rest_lro_client(): - client = WorkflowsClient( - 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 = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WorkflowsGrpcTransport, - ) - -def test_workflows_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WorkflowsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_workflows_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.workflows_v1beta.services.workflows.transports.WorkflowsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WorkflowsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_workflows', - 'get_workflow', - 'create_workflow', - 'delete_workflow', - 'update_workflow', - ) - 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_workflows_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workflows_v1beta.services.workflows.transports.WorkflowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkflowsTransport( - 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_workflows_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workflows_v1beta.services.workflows.transports.WorkflowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkflowsTransport() - adc.assert_called_once() - - -def test_workflows_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) - WorkflowsClient() - 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.WorkflowsGrpcTransport, - transports.WorkflowsGrpcAsyncIOTransport, - ], -) -def test_workflows_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.WorkflowsGrpcTransport, - transports.WorkflowsGrpcAsyncIOTransport, - transports.WorkflowsRestTransport, - ], -) -def test_workflows_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.WorkflowsGrpcTransport, grpc_helpers), - (transports.WorkflowsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_workflows_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( - "workflows.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="workflows.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) -def test_workflows_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_workflows_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.WorkflowsRestTransport ( - 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_workflows_host_no_port(transport_name): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workflows.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workflows.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workflows.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_workflows_host_with_port(transport_name): - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workflows.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workflows.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workflows.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_workflows_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = WorkflowsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = WorkflowsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_workflows._session - session2 = client2.transport.list_workflows._session - assert session1 != session2 - session1 = client1.transport.get_workflow._session - session2 = client2.transport.get_workflow._session - assert session1 != session2 - session1 = client1.transport.create_workflow._session - session2 = client2.transport.create_workflow._session - assert session1 != session2 - session1 = client1.transport.delete_workflow._session - session2 = client2.transport.delete_workflow._session - assert session1 != session2 - session1 = client1.transport.update_workflow._session - session2 = client2.transport.update_workflow._session - assert session1 != session2 -def test_workflows_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkflowsGrpcTransport( - 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_workflows_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkflowsGrpcAsyncIOTransport( - 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.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) -def test_workflows_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.WorkflowsGrpcTransport, transports.WorkflowsGrpcAsyncIOTransport]) -def test_workflows_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_workflows_grpc_lro_client(): - client = WorkflowsClient( - 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_workflows_grpc_lro_async_client(): - client = WorkflowsAsyncClient( - 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_workflow_path(): - project = "squid" - location = "clam" - workflow = "whelk" - expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - actual = WorkflowsClient.workflow_path(project, location, workflow) - assert expected == actual - - -def test_parse_workflow_path(): - expected = { - "project": "octopus", - "location": "oyster", - "workflow": "nudibranch", - } - path = WorkflowsClient.workflow_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.parse_workflow_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WorkflowsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = WorkflowsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = WorkflowsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = WorkflowsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WorkflowsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = WorkflowsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = WorkflowsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = WorkflowsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.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 = WorkflowsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = WorkflowsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WorkflowsClient.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.WorkflowsTransport, '_prep_wrapped_messages') as prep: - client = WorkflowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WorkflowsTransport, '_prep_wrapped_messages') as prep: - transport_class = WorkflowsClient.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 = WorkflowsClient( - 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 = WorkflowsAsyncClient( - 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 = WorkflowsClient( - 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 = WorkflowsClient( - 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", [ - (WorkflowsClient, transports.WorkflowsGrpcTransport), - (WorkflowsAsyncClient, transports.WorkflowsGrpcAsyncIOTransport), -]) -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-cloud-workstations/v1/.coveragerc b/owl-bot-staging/google-cloud-workstations/v1/.coveragerc deleted file mode 100644 index ee1a17c3e2ca..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/workstations/__init__.py - google/cloud/workstations/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-cloud-workstations/v1/.flake8 b/owl-bot-staging/google-cloud-workstations/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1/MANIFEST.in b/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in deleted file mode 100644 index 81d49b157276..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/workstations *.py -recursive-include google/cloud/workstations_v1 *.py diff --git a/owl-bot-staging/google-cloud-workstations/v1/README.rst b/owl-bot-staging/google-cloud-workstations/v1/README.rst deleted file mode 100644 index 48a711be018f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Workstations 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 Cloud Workstations 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-cloud-workstations/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-workstations/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1/docs/conf.py b/owl-bot-staging/google-cloud-workstations/v1/docs/conf.py deleted file mode 100644 index 65ff2ad5ae85..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations 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-cloud-workstations" -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 Cloud 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-cloud-workstations-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-cloud-workstations.tex", - u"google-cloud-workstations 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-cloud-workstations", - u"Google Cloud Workstations 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-cloud-workstations", - u"google-cloud-workstations Documentation", - author, - "google-cloud-workstations", - "GAPIC library for Google Cloud Workstations 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-cloud-workstations/v1/docs/index.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst deleted file mode 100644 index 48bce1a5d563..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - workstations_v1/services_ - workstations_v1/types_ diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services_.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services_.rst deleted file mode 100644 index 4d34f8795a80..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Workstations v1 API -============================================= -.. toctree:: - :maxdepth: 2 - - workstations diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types_.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types_.rst deleted file mode 100644 index f2d1f8aae76b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Workstations v1 API -========================================== - -.. automodule:: google.cloud.workstations_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst deleted file mode 100644 index 1a3ded4d683d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst +++ /dev/null @@ -1,10 +0,0 @@ -Workstations ------------------------------- - -.. automodule:: google.cloud.workstations_v1.services.workstations - :members: - :inherited-members: - -.. automodule:: google.cloud.workstations_v1.services.workstations.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py deleted file mode 100644 index 6323e1047e2f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workstations import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.workstations_v1.services.workstations.client import WorkstationsClient -from google.cloud.workstations_v1.services.workstations.async_client import WorkstationsAsyncClient - -from google.cloud.workstations_v1.types.workstations import CreateWorkstationClusterRequest -from google.cloud.workstations_v1.types.workstations import CreateWorkstationConfigRequest -from google.cloud.workstations_v1.types.workstations import CreateWorkstationRequest -from google.cloud.workstations_v1.types.workstations import DeleteWorkstationClusterRequest -from google.cloud.workstations_v1.types.workstations import DeleteWorkstationConfigRequest -from google.cloud.workstations_v1.types.workstations import DeleteWorkstationRequest -from google.cloud.workstations_v1.types.workstations import GenerateAccessTokenRequest -from google.cloud.workstations_v1.types.workstations import GenerateAccessTokenResponse -from google.cloud.workstations_v1.types.workstations import GetWorkstationClusterRequest -from google.cloud.workstations_v1.types.workstations import GetWorkstationConfigRequest -from google.cloud.workstations_v1.types.workstations import GetWorkstationRequest -from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationConfigsRequest -from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationConfigsResponse -from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationsRequest -from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationsResponse -from google.cloud.workstations_v1.types.workstations import ListWorkstationClustersRequest -from google.cloud.workstations_v1.types.workstations import ListWorkstationClustersResponse -from google.cloud.workstations_v1.types.workstations import ListWorkstationConfigsRequest -from google.cloud.workstations_v1.types.workstations import ListWorkstationConfigsResponse -from google.cloud.workstations_v1.types.workstations import ListWorkstationsRequest -from google.cloud.workstations_v1.types.workstations import ListWorkstationsResponse -from google.cloud.workstations_v1.types.workstations import OperationMetadata -from google.cloud.workstations_v1.types.workstations import StartWorkstationRequest -from google.cloud.workstations_v1.types.workstations import StopWorkstationRequest -from google.cloud.workstations_v1.types.workstations import UpdateWorkstationClusterRequest -from google.cloud.workstations_v1.types.workstations import UpdateWorkstationConfigRequest -from google.cloud.workstations_v1.types.workstations import UpdateWorkstationRequest -from google.cloud.workstations_v1.types.workstations import Workstation -from google.cloud.workstations_v1.types.workstations import WorkstationCluster -from google.cloud.workstations_v1.types.workstations import WorkstationConfig - -__all__ = ('WorkstationsClient', - 'WorkstationsAsyncClient', - 'CreateWorkstationClusterRequest', - 'CreateWorkstationConfigRequest', - 'CreateWorkstationRequest', - 'DeleteWorkstationClusterRequest', - 'DeleteWorkstationConfigRequest', - 'DeleteWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GetWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'OperationMetadata', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'UpdateWorkstationClusterRequest', - 'UpdateWorkstationConfigRequest', - 'UpdateWorkstationRequest', - 'Workstation', - 'WorkstationCluster', - 'WorkstationConfig', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/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-cloud-workstations/v1/google/cloud/workstations/py.typed b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed deleted file mode 100644 index 04170223dff9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py deleted file mode 100644 index 50e519bf99c1..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py +++ /dev/null @@ -1,88 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workstations_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.workstations import WorkstationsClient -from .services.workstations import WorkstationsAsyncClient - -from .types.workstations import CreateWorkstationClusterRequest -from .types.workstations import CreateWorkstationConfigRequest -from .types.workstations import CreateWorkstationRequest -from .types.workstations import DeleteWorkstationClusterRequest -from .types.workstations import DeleteWorkstationConfigRequest -from .types.workstations import DeleteWorkstationRequest -from .types.workstations import GenerateAccessTokenRequest -from .types.workstations import GenerateAccessTokenResponse -from .types.workstations import GetWorkstationClusterRequest -from .types.workstations import GetWorkstationConfigRequest -from .types.workstations import GetWorkstationRequest -from .types.workstations import ListUsableWorkstationConfigsRequest -from .types.workstations import ListUsableWorkstationConfigsResponse -from .types.workstations import ListUsableWorkstationsRequest -from .types.workstations import ListUsableWorkstationsResponse -from .types.workstations import ListWorkstationClustersRequest -from .types.workstations import ListWorkstationClustersResponse -from .types.workstations import ListWorkstationConfigsRequest -from .types.workstations import ListWorkstationConfigsResponse -from .types.workstations import ListWorkstationsRequest -from .types.workstations import ListWorkstationsResponse -from .types.workstations import OperationMetadata -from .types.workstations import StartWorkstationRequest -from .types.workstations import StopWorkstationRequest -from .types.workstations import UpdateWorkstationClusterRequest -from .types.workstations import UpdateWorkstationConfigRequest -from .types.workstations import UpdateWorkstationRequest -from .types.workstations import Workstation -from .types.workstations import WorkstationCluster -from .types.workstations import WorkstationConfig - -__all__ = ( - 'WorkstationsAsyncClient', -'CreateWorkstationClusterRequest', -'CreateWorkstationConfigRequest', -'CreateWorkstationRequest', -'DeleteWorkstationClusterRequest', -'DeleteWorkstationConfigRequest', -'DeleteWorkstationRequest', -'GenerateAccessTokenRequest', -'GenerateAccessTokenResponse', -'GetWorkstationClusterRequest', -'GetWorkstationConfigRequest', -'GetWorkstationRequest', -'ListUsableWorkstationConfigsRequest', -'ListUsableWorkstationConfigsResponse', -'ListUsableWorkstationsRequest', -'ListUsableWorkstationsResponse', -'ListWorkstationClustersRequest', -'ListWorkstationClustersResponse', -'ListWorkstationConfigsRequest', -'ListWorkstationConfigsResponse', -'ListWorkstationsRequest', -'ListWorkstationsResponse', -'OperationMetadata', -'StartWorkstationRequest', -'StopWorkstationRequest', -'UpdateWorkstationClusterRequest', -'UpdateWorkstationConfigRequest', -'UpdateWorkstationRequest', -'Workstation', -'WorkstationCluster', -'WorkstationConfig', -'WorkstationsClient', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json deleted file mode 100644 index 27a21c6d848b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json +++ /dev/null @@ -1,328 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.workstations_v1", - "protoPackage": "google.cloud.workstations.v1", - "schema": "1.0", - "services": { - "Workstations": { - "clients": { - "grpc": { - "libraryClient": "WorkstationsClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WorkstationsAsyncClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - }, - "rest": { - "libraryClient": "WorkstationsClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_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-cloud-workstations/v1/google/cloud/workstations_v1/py.typed b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed deleted file mode 100644 index 04170223dff9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_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-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py deleted file mode 100644 index e8958d8c0d6d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__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 WorkstationsClient -from .async_client import WorkstationsAsyncClient - -__all__ = ( - 'WorkstationsClient', - 'WorkstationsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py deleted file mode 100644 index 1cd023b1e894..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py +++ /dev/null @@ -1,3183 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.workstations_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.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.services.workstations import pagers -from google.cloud.workstations_v1.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .client import WorkstationsClient - - -class WorkstationsAsyncClient: - """Service for interacting with Cloud Workstations.""" - - _client: WorkstationsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = WorkstationsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WorkstationsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = WorkstationsClient._DEFAULT_UNIVERSE - - workstation_path = staticmethod(WorkstationsClient.workstation_path) - parse_workstation_path = staticmethod(WorkstationsClient.parse_workstation_path) - workstation_cluster_path = staticmethod(WorkstationsClient.workstation_cluster_path) - parse_workstation_cluster_path = staticmethod(WorkstationsClient.parse_workstation_cluster_path) - workstation_config_path = staticmethod(WorkstationsClient.workstation_config_path) - parse_workstation_config_path = staticmethod(WorkstationsClient.parse_workstation_config_path) - common_billing_account_path = staticmethod(WorkstationsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WorkstationsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WorkstationsClient.common_folder_path) - parse_common_folder_path = staticmethod(WorkstationsClient.parse_common_folder_path) - common_organization_path = staticmethod(WorkstationsClient.common_organization_path) - parse_common_organization_path = staticmethod(WorkstationsClient.parse_common_organization_path) - common_project_path = staticmethod(WorkstationsClient.common_project_path) - parse_common_project_path = staticmethod(WorkstationsClient.parse_common_project_path) - common_location_path = staticmethod(WorkstationsClient.common_location_path) - parse_common_location_path = staticmethod(WorkstationsClient.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: - WorkstationsAsyncClient: The constructed client. - """ - return WorkstationsClient.from_service_account_info.__func__(WorkstationsAsyncClient, 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: - WorkstationsAsyncClient: The constructed client. - """ - return WorkstationsClient.from_service_account_file.__func__(WorkstationsAsyncClient, 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 WorkstationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> WorkstationsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkstationsTransport: 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 = WorkstationsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, WorkstationsTransport, Callable[..., WorkstationsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workstations 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,WorkstationsTransport,Callable[..., WorkstationsTransport]]]): - 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 WorkstationsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WorkstationsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_workstation_cluster(self, - request: Optional[Union[workstations.GetWorkstationClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.WorkstationCluster: - r"""Returns the requested workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationClusterRequest, dict]]): - The request object. Request message for - GetWorkstationCluster. - name (:class:`str`): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.types.WorkstationCluster: - A workstation cluster resource in the - Cloud Workstations API. - Defines a group of workstations in a - particular region and the VPC network - they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationClusterRequest): - request = workstations.GetWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_cluster] - - # Certain fields should be provided within 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_workstation_clusters(self, - request: Optional[Union[workstations.ListWorkstationClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationClustersAsyncPager: - r"""Returns all workstation clusters in the specified - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationClustersRequest, dict]]): - The request object. Request message for - ListWorkstationClusters. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationClustersAsyncPager: - Response message for - ListWorkstationClusters. - 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, workstations.ListWorkstationClustersRequest): - request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] - - # Certain fields should be provided within 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.ListWorkstationClustersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation_cluster(self, - request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_cluster: Optional[workstations.WorkstationCluster] = None, - workstation_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationClusterRequest, dict]]): - The request object. Message for creating a - CreateWorkstationCluster. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster (:class:`google.cloud.workstations_v1.types.WorkstationCluster`): - Required. Workstation cluster to - create. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster_id (:class:`str`): - Required. ID to use for the - workstation cluster. - - This corresponds to the ``workstation_cluster_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation_cluster, workstation_cluster_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, workstations.CreateWorkstationClusterRequest): - request = workstations.CreateWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - if workstation_cluster_id is not None: - request.workstation_cluster_id = workstation_cluster_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_workstation_cluster] - - # Certain fields should be provided within 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation_cluster(self, - request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, - *, - workstation_cluster: Optional[workstations.WorkstationCluster] = 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, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an existing workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest, dict]]): - The request object. Request message for - UpdateWorkstationCluster. - workstation_cluster (:class:`google.cloud.workstations_v1.types.WorkstationCluster`): - Required. Workstation cluster to - update. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask that specifies which - fields in the workstation cluster should - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_cluster, 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, workstations.UpdateWorkstationClusterRequest): - request = workstations.UpdateWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - 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_workstation_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_cluster.name", request.workstation_cluster.name), - )), - ) - - # 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation_cluster(self, - request: Optional[Union[workstations.DeleteWorkstationClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest, dict]]): - The request object. Message for deleting a workstation - cluster. - name (:class:`str`): - Required. Name of the workstation - cluster to delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationClusterRequest): - request = workstations.DeleteWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_cluster] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_workstation_config(self, - request: Optional[Union[workstations.GetWorkstationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.WorkstationConfig: - r"""Returns the requested workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_get_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationConfigRequest, dict]]): - The request object. Request message for - GetWorkstationConfig. - name (:class:`str`): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.types.WorkstationConfig: - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationConfigRequest): - request = workstations.GetWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_config] - - # Certain fields should be provided within 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_workstation_configs(self, - request: Optional[Union[workstations.ListWorkstationConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationConfigsAsyncPager: - r"""Returns all workstation configurations in the - specified cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationConfigsRequest, dict]]): - The request object. Request message for - ListWorkstationConfigs. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationConfigsAsyncPager: - Response message for - ListWorkstationConfigs. - 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, workstations.ListWorkstationConfigsRequest): - request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] - - # Certain fields should be provided within 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.ListWorkstationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_usable_workstation_configs(self, - request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUsableWorkstationConfigsAsyncPager: - r"""Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest, dict]]): - The request object. Request message for - ListUsableWorkstationConfigs. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager: - Response message for - ListUsableWorkstationConfigs. - 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, workstations.ListUsableWorkstationConfigsRequest): - request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] - - # Certain fields should be provided within 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.ListUsableWorkstationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation_config(self, - request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_config: Optional[workstations.WorkstationConfig] = None, - workstation_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_create_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationConfigRequest, dict]]): - The request object. Message for creating a - CreateWorkstationConfig. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config (:class:`google.cloud.workstations_v1.types.WorkstationConfig`): - Required. Config to create. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config_id (:class:`str`): - Required. ID to use for the - workstation configuration. - - This corresponds to the ``workstation_config_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation_config, workstation_config_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, workstations.CreateWorkstationConfigRequest): - request = workstations.CreateWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_config is not None: - request.workstation_config = workstation_config - if workstation_config_id is not None: - request.workstation_config_id = workstation_config_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_workstation_config] - - # Certain fields should be provided within 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation_config(self, - request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, - *, - workstation_config: Optional[workstations.WorkstationConfig] = 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, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an existing workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_update_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest, dict]]): - The request object. Request message for - UpdateWorkstationConfig. - workstation_config (:class:`google.cloud.workstations_v1.types.WorkstationConfig`): - Required. Config to update. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask specifying which - fields in the workstation configuration - should 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_config, 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, workstations.UpdateWorkstationConfigRequest): - request = workstations.UpdateWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_config is not None: - request.workstation_config = workstation_config - 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_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_config.name", request.workstation_config.name), - )), - ) - - # 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation_config(self, - request: Optional[Union[workstations.DeleteWorkstationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_delete_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest, dict]]): - The request object. Message for deleting a workstation - configuration. - name (:class:`str`): - Required. Name of the workstation - configuration to delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationConfigRequest): - request = workstations.DeleteWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_config] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_workstation(self, - request: Optional[Union[workstations.GetWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.Workstation: - r"""Returns the requested workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_get_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationRequest, dict]]): - The request object. Request message for GetWorkstation. - name (:class:`str`): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.types.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationRequest): - request = workstations.GetWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation] - - # Certain fields should be provided within 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_workstations(self, - request: Optional[Union[workstations.ListWorkstationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationsAsyncPager: - r"""Returns all Workstations using the specified - workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_workstations(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationsRequest, dict]]): - The request object. Request message for ListWorkstations. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationsAsyncPager: - Response message for - ListWorkstations. - 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, workstations.ListWorkstationsRequest): - request = workstations.ListWorkstationsRequest(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_workstations] - - # Certain fields should be provided within 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.ListWorkstationsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_usable_workstations(self, - request: Optional[Union[workstations.ListUsableWorkstationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUsableWorkstationsAsyncPager: - r"""Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_usable_workstations(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListUsableWorkstationsRequest, dict]]): - The request object. Request message for - ListUsableWorkstations. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationsAsyncPager: - Response message for - ListUsableWorkstations. - 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, workstations.ListUsableWorkstationsRequest): - request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] - - # Certain fields should be provided within 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.ListUsableWorkstationsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation(self, - request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation: Optional[workstations.Workstation] = None, - workstation_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_create_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationRequest, dict]]): - The request object. Message for creating a - CreateWorkstation. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation (:class:`google.cloud.workstations_v1.types.Workstation`): - Required. Workstation to create. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_id (:class:`str`): - Required. ID to use for the - workstation. - - This corresponds to the ``workstation_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation, workstation_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, workstations.CreateWorkstationRequest): - request = workstations.CreateWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation is not None: - request.workstation = workstation - if workstation_id is not None: - request.workstation_id = workstation_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_workstation] - - # Certain fields should be provided within 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation(self, - request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, - *, - workstation: Optional[workstations.Workstation] = 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, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an existing workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_update_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationRequest, dict]]): - The request object. Request message for - UpdateWorkstation. - workstation (:class:`google.cloud.workstations_v1.types.Workstation`): - Required. Workstation to update. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask specifying which - fields in the workstation configuration - should 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation, 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, workstations.UpdateWorkstationRequest): - request = workstations.UpdateWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - 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_workstation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation.name", request.workstation.name), - )), - ) - - # 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation(self, - request: Optional[Union[workstations.DeleteWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_delete_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationRequest, dict]]): - The request object. Request message for - DeleteWorkstation. - name (:class:`str`): - Required. Name of the workstation to - delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationRequest): - request = workstations.DeleteWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def start_workstation(self, - request: Optional[Union[workstations.StartWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts running a workstation so that users can - connect to it. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_start_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.StartWorkstationRequest, dict]]): - The request object. Request message for StartWorkstation. - name (:class:`str`): - Required. Name of the workstation to - start. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.StartWorkstationRequest): - request = workstations.StartWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.start_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def stop_workstation(self, - request: Optional[Union[workstations.StopWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Stops running a workstation, reducing costs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_stop_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.StopWorkstationRequest, dict]]): - The request object. Request message for StopWorkstation. - name (:class:`str`): - Required. Name of the workstation to - stop. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.StopWorkstationRequest): - request = workstations.StopWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.stop_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def generate_access_token(self, - request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, - *, - workstation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.GenerateAccessTokenResponse: - r"""Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_generate_access_token(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.GenerateAccessTokenRequest, dict]]): - The request object. Request message for - GenerateAccessToken. - workstation (:class:`str`): - Required. Name of the workstation for - which the access token should be - generated. - - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_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. - - Returns: - google.cloud.workstations_v1.types.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, workstations.GenerateAccessTokenRequest): - request = workstations.GenerateAccessTokenRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation", request.workstation), - )), - ) - - # Validate the universe domain. - self._client._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_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # 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.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_operations] - - # Certain fields should be provided within 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_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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # 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.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.delete_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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # 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.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.cancel_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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._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_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._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) -> "WorkstationsAsyncClient": - 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__ = ( - "WorkstationsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py deleted file mode 100644 index 61b0aa5acd49..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py +++ /dev/null @@ -1,3536 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.workstations_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 - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.services.workstations import pagers -from google.cloud.workstations_v1.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WorkstationsGrpcTransport -from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .transports.rest import WorkstationsRestTransport - - -class WorkstationsClientMeta(type): - """Metaclass for the Workstations 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[WorkstationsTransport]] - _transport_registry["grpc"] = WorkstationsGrpcTransport - _transport_registry["grpc_asyncio"] = WorkstationsGrpcAsyncIOTransport - _transport_registry["rest"] = WorkstationsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[WorkstationsTransport]: - """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 WorkstationsClient(metaclass=WorkstationsClientMeta): - """Service for interacting with Cloud Workstations.""" - - @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 = "workstations.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "workstations.{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: - WorkstationsClient: 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: - WorkstationsClient: 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) -> WorkstationsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkstationsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def workstation_path(project: str,location: str,workstation_cluster: str,workstation_config: str,workstation: str,) -> str: - """Returns a fully-qualified workstation string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) - - @staticmethod - def parse_workstation_path(path: str) -> Dict[str,str]: - """Parses a workstation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?P.+?)/workstations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workstation_cluster_path(project: str,location: str,workstation_cluster: str,) -> str: - """Returns a fully-qualified workstation_cluster string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) - - @staticmethod - def parse_workstation_cluster_path(path: str) -> Dict[str,str]: - """Parses a workstation_cluster path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workstation_config_path(project: str,location: str,workstation_cluster: str,workstation_config: str,) -> str: - """Returns a fully-qualified workstation_config string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) - - @staticmethod - def parse_workstation_config_path(path: str) -> Dict[str,str]: - """Parses a workstation_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?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 = WorkstationsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = WorkstationsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = WorkstationsClient._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 = WorkstationsClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = WorkstationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - WorkstationsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, WorkstationsTransport, Callable[..., WorkstationsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workstations client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,WorkstationsTransport,Callable[..., WorkstationsTransport]]]): - 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 WorkstationsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WorkstationsClient._read_environment_variables() - self._client_cert_source = WorkstationsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = WorkstationsClient._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 - - 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, WorkstationsTransport) - if transport_provided: - # transport is a WorkstationsTransport 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(WorkstationsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - WorkstationsClient._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[WorkstationsTransport], Callable[..., WorkstationsTransport]] = ( - WorkstationsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., WorkstationsTransport], 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, - ) - - def get_workstation_cluster(self, - request: Optional[Union[workstations.GetWorkstationClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.WorkstationCluster: - r"""Returns the requested workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.GetWorkstationClusterRequest, dict]): - The request object. Request message for - GetWorkstationCluster. - name (str): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.types.WorkstationCluster: - A workstation cluster resource in the - Cloud Workstations API. - Defines a group of workstations in a - particular region and the VPC network - they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationClusterRequest): - request = workstations.GetWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_cluster] - - # Certain fields should be provided within 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_workstation_clusters(self, - request: Optional[Union[workstations.ListWorkstationClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationClustersPager: - r"""Returns all workstation clusters in the specified - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListWorkstationClustersRequest, dict]): - The request object. Request message for - ListWorkstationClusters. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationClustersPager: - Response message for - ListWorkstationClusters. - 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, workstations.ListWorkstationClustersRequest): - request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] - - # Certain fields should be provided within 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.ListWorkstationClustersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation_cluster(self, - request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_cluster: Optional[workstations.WorkstationCluster] = None, - workstation_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.CreateWorkstationClusterRequest, dict]): - The request object. Message for creating a - CreateWorkstationCluster. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): - Required. Workstation cluster to - create. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster_id (str): - Required. ID to use for the - workstation cluster. - - This corresponds to the ``workstation_cluster_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation_cluster, workstation_cluster_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, workstations.CreateWorkstationClusterRequest): - request = workstations.CreateWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - if workstation_cluster_id is not None: - request.workstation_cluster_id = workstation_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation_cluster] - - # Certain fields should be provided within 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation_cluster(self, - request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, - *, - workstation_cluster: Optional[workstations.WorkstationCluster] = 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, str]] = (), - ) -> operation.Operation: - r"""Updates an existing workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest, dict]): - The request object. Request message for - UpdateWorkstationCluster. - workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): - Required. Workstation cluster to - update. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask that specifies which - fields in the workstation cluster should - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_cluster, 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, workstations.UpdateWorkstationClusterRequest): - request = workstations.UpdateWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - 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_workstation_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_cluster.name", request.workstation_cluster.name), - )), - ) - - # 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation_cluster(self, - request: Optional[Union[workstations.DeleteWorkstationClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest, dict]): - The request object. Message for deleting a workstation - cluster. - name (str): - Required. Name of the workstation - cluster to delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationClusterRequest): - request = workstations.DeleteWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_cluster] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_workstation_config(self, - request: Optional[Union[workstations.GetWorkstationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.WorkstationConfig: - r"""Returns the requested workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_get_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.GetWorkstationConfigRequest, dict]): - The request object. Request message for - GetWorkstationConfig. - name (str): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.types.WorkstationConfig: - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationConfigRequest): - request = workstations.GetWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_config] - - # Certain fields should be provided within 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_workstation_configs(self, - request: Optional[Union[workstations.ListWorkstationConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationConfigsPager: - r"""Returns all workstation configurations in the - specified cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListWorkstationConfigsRequest, dict]): - The request object. Request message for - ListWorkstationConfigs. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationConfigsPager: - Response message for - ListWorkstationConfigs. - 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, workstations.ListWorkstationConfigsRequest): - request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] - - # Certain fields should be provided within 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.ListWorkstationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_usable_workstation_configs(self, - request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUsableWorkstationConfigsPager: - r"""Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest, dict]): - The request object. Request message for - ListUsableWorkstationConfigs. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsPager: - Response message for - ListUsableWorkstationConfigs. - 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, workstations.ListUsableWorkstationConfigsRequest): - request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] - - # Certain fields should be provided within 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.ListUsableWorkstationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation_config(self, - request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_config: Optional[workstations.WorkstationConfig] = None, - workstation_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_create_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.CreateWorkstationConfigRequest, dict]): - The request object. Message for creating a - CreateWorkstationConfig. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): - Required. Config to create. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config_id (str): - Required. ID to use for the - workstation configuration. - - This corresponds to the ``workstation_config_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation_config, workstation_config_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, workstations.CreateWorkstationConfigRequest): - request = workstations.CreateWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_config is not None: - request.workstation_config = workstation_config - if workstation_config_id is not None: - request.workstation_config_id = workstation_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation_config] - - # Certain fields should be provided within 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation_config(self, - request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, - *, - workstation_config: Optional[workstations.WorkstationConfig] = 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, str]] = (), - ) -> operation.Operation: - r"""Updates an existing workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_update_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest, dict]): - The request object. Request message for - UpdateWorkstationConfig. - workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): - Required. Config to update. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which - fields in the workstation configuration - should 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_config, 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, workstations.UpdateWorkstationConfigRequest): - request = workstations.UpdateWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_config is not None: - request.workstation_config = workstation_config - 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_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_config.name", request.workstation_config.name), - )), - ) - - # 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation_config(self, - request: Optional[Union[workstations.DeleteWorkstationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_delete_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest, dict]): - The request object. Message for deleting a workstation - configuration. - name (str): - Required. Name of the workstation - configuration to delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationConfigRequest): - request = workstations.DeleteWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_config] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_workstation(self, - request: Optional[Union[workstations.GetWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.Workstation: - r"""Returns the requested workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_get_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.GetWorkstationRequest, dict]): - The request object. Request message for GetWorkstation. - name (str): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.types.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationRequest): - request = workstations.GetWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation] - - # Certain fields should be provided within 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_workstations(self, - request: Optional[Union[workstations.ListWorkstationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationsPager: - r"""Returns all Workstations using the specified - workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_workstations(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListWorkstationsRequest, dict]): - The request object. Request message for ListWorkstations. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationsPager: - Response message for - ListWorkstations. - 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, workstations.ListWorkstationsRequest): - request = workstations.ListWorkstationsRequest(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_workstations] - - # Certain fields should be provided within 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.ListWorkstationsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_usable_workstations(self, - request: Optional[Union[workstations.ListUsableWorkstationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUsableWorkstationsPager: - r"""Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_usable_workstations(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListUsableWorkstationsRequest, dict]): - The request object. Request message for - ListUsableWorkstations. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationsPager: - Response message for - ListUsableWorkstations. - 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, workstations.ListUsableWorkstationsRequest): - request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] - - # Certain fields should be provided within 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.ListUsableWorkstationsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation(self, - request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation: Optional[workstations.Workstation] = None, - workstation_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_create_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.CreateWorkstationRequest, dict]): - The request object. Message for creating a - CreateWorkstation. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation (google.cloud.workstations_v1.types.Workstation): - Required. Workstation to create. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_id (str): - Required. ID to use for the - workstation. - - This corresponds to the ``workstation_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation, workstation_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, workstations.CreateWorkstationRequest): - request = workstations.CreateWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation is not None: - request.workstation = workstation - if workstation_id is not None: - request.workstation_id = workstation_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation] - - # Certain fields should be provided within 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation(self, - request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, - *, - workstation: Optional[workstations.Workstation] = 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, str]] = (), - ) -> operation.Operation: - r"""Updates an existing workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_update_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.UpdateWorkstationRequest, dict]): - The request object. Request message for - UpdateWorkstation. - workstation (google.cloud.workstations_v1.types.Workstation): - Required. Workstation to update. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which - fields in the workstation configuration - should 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation, 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, workstations.UpdateWorkstationRequest): - request = workstations.UpdateWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - 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_workstation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation.name", request.workstation.name), - )), - ) - - # 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation(self, - request: Optional[Union[workstations.DeleteWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_delete_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.DeleteWorkstationRequest, dict]): - The request object. Request message for - DeleteWorkstation. - name (str): - Required. Name of the workstation to - delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationRequest): - request = workstations.DeleteWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def start_workstation(self, - request: Optional[Union[workstations.StartWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts running a workstation so that users can - connect to it. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_start_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.StartWorkstationRequest, dict]): - The request object. Request message for StartWorkstation. - name (str): - Required. Name of the workstation to - start. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.StartWorkstationRequest): - request = workstations.StartWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.start_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def stop_workstation(self, - request: Optional[Union[workstations.StopWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Stops running a workstation, reducing costs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_stop_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.StopWorkstationRequest, dict]): - The request object. Request message for StopWorkstation. - name (str): - Required. Name of the workstation to - stop. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.StopWorkstationRequest): - request = workstations.StopWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.stop_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def generate_access_token(self, - request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, - *, - workstation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.GenerateAccessTokenResponse: - r"""Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_generate_access_token(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.GenerateAccessTokenRequest, dict]): - The request object. Request message for - GenerateAccessToken. - workstation (str): - Required. Name of the workstation for - which the access token should be - generated. - - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.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. - - Returns: - google.cloud.workstations_v1.types.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, workstations.GenerateAccessTokenRequest): - request = workstations.GenerateAccessTokenRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation", request.workstation), - )), - ) - - # Validate the universe 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) -> "WorkstationsClient": - 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 list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.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. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # 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.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_operations] - - # Certain fields should be provided within 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_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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.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. - Returns: - None - """ - # 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.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.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. - Returns: - None - """ - # 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.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.cancel_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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.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. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe 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_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.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. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.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. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the 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__ = ( - "WorkstationsClient", -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py deleted file mode 100644 index 8ab2db0999ce..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py +++ /dev/null @@ -1,702 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workstations_v1.types import workstations - - -class ListWorkstationClustersPager: - """A pager for iterating through ``list_workstation_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_clusters`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstationClusters`` requests and continue to iterate - through the ``workstation_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListWorkstationClustersResponse], - request: workstations.ListWorkstationClustersRequest, - response: workstations.ListWorkstationClustersResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListWorkstationClustersRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationClustersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationClustersRequest(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[workstations.ListWorkstationClustersResponse]: - 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[workstations.WorkstationCluster]: - for page in self.pages: - yield from page.workstation_clusters - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationClustersAsyncPager: - """A pager for iterating through ``list_workstation_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_clusters`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstationClusters`` requests and continue to iterate - through the ``workstation_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` - attributes are available on the 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[workstations.ListWorkstationClustersResponse]], - request: workstations.ListWorkstationClustersRequest, - response: workstations.ListWorkstationClustersResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListWorkstationClustersRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationClustersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationClustersRequest(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[workstations.ListWorkstationClustersResponse]: - 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[workstations.WorkstationCluster]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_clusters: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationConfigsPager: - """A pager for iterating through ``list_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListWorkstationConfigsResponse], - request: workstations.ListWorkstationConfigsRequest, - response: workstations.ListWorkstationConfigsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationConfigsRequest(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[workstations.ListWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - for page in self.pages: - yield from page.workstation_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationConfigsAsyncPager: - """A pager for iterating through ``list_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` - attributes are available on the 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[workstations.ListWorkstationConfigsResponse]], - request: workstations.ListWorkstationConfigsRequest, - response: workstations.ListWorkstationConfigsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationConfigsRequest(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[workstations.ListWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationConfigsPager: - """A pager for iterating through ``list_usable_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsableWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListUsableWorkstationConfigsResponse], - request: workstations.ListUsableWorkstationConfigsRequest, - response: workstations.ListUsableWorkstationConfigsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListUsableWorkstationConfigsRequest(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[workstations.ListUsableWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - for page in self.pages: - yield from page.workstation_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationConfigsAsyncPager: - """A pager for iterating through ``list_usable_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsableWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` - attributes are available on the 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[workstations.ListUsableWorkstationConfigsResponse]], - request: workstations.ListUsableWorkstationConfigsRequest, - response: workstations.ListUsableWorkstationConfigsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListUsableWorkstationConfigsRequest(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[workstations.ListUsableWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationsPager: - """A pager for iterating through ``list_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListWorkstationsResponse], - request: workstations.ListWorkstationsRequest, - response: workstations.ListWorkstationsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationsRequest(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[workstations.ListWorkstationsResponse]: - 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[workstations.Workstation]: - for page in self.pages: - yield from page.workstations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationsAsyncPager: - """A pager for iterating through ``list_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` - attributes are available on the 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[workstations.ListWorkstationsResponse]], - request: workstations.ListWorkstationsRequest, - response: workstations.ListWorkstationsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationsRequest(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[workstations.ListWorkstationsResponse]: - 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[workstations.Workstation]: - async def async_generator(): - async for page in self.pages: - for response in page.workstations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationsPager: - """A pager for iterating through ``list_usable_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsableWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListUsableWorkstationsResponse], - request: workstations.ListUsableWorkstationsRequest, - response: workstations.ListUsableWorkstationsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListUsableWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListUsableWorkstationsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListUsableWorkstationsRequest(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[workstations.ListUsableWorkstationsResponse]: - 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[workstations.Workstation]: - for page in self.pages: - yield from page.workstations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationsAsyncPager: - """A pager for iterating through ``list_usable_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsableWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` - attributes are available on the 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[workstations.ListUsableWorkstationsResponse]], - request: workstations.ListUsableWorkstationsRequest, - response: workstations.ListUsableWorkstationsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1.types.ListUsableWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListUsableWorkstationsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListUsableWorkstationsRequest(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[workstations.ListUsableWorkstationsResponse]: - 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[workstations.Workstation]: - async def async_generator(): - async for page in self.pages: - for response in page.workstations: - 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-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/README.rst b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/README.rst deleted file mode 100644 index e25a7cc4b1cf..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`WorkstationsTransport` is the ABC for all transports. -- public child `WorkstationsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `WorkstationsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseWorkstationsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `WorkstationsRestTransport` 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-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py deleted file mode 100644 index 3ae547e57985..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/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 WorkstationsTransport -from .grpc import WorkstationsGrpcTransport -from .grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .rest import WorkstationsRestTransport -from .rest import WorkstationsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WorkstationsTransport]] -_transport_registry['grpc'] = WorkstationsGrpcTransport -_transport_registry['grpc_asyncio'] = WorkstationsGrpcAsyncIOTransport -_transport_registry['rest'] = WorkstationsRestTransport - -__all__ = ( - 'WorkstationsTransport', - 'WorkstationsGrpcTransport', - 'WorkstationsGrpcAsyncIOTransport', - 'WorkstationsRestTransport', - 'WorkstationsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py deleted file mode 100644 index dbd5003a5aab..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.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 abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.workstations_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.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class WorkstationsTransport(abc.ABC): - """Abstract transport class for Workstations.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'workstations.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: 'workstations.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_workstation_cluster: gapic_v1.method.wrap_method( - self.get_workstation_cluster, - 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_workstation_clusters: gapic_v1.method.wrap_method( - self.list_workstation_clusters, - 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.create_workstation_cluster: gapic_v1.method.wrap_method( - self.create_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_cluster: gapic_v1.method.wrap_method( - self.update_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_cluster: gapic_v1.method.wrap_method( - self.delete_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation_config: gapic_v1.method.wrap_method( - self.get_workstation_config, - 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_workstation_configs: gapic_v1.method.wrap_method( - self.list_workstation_configs, - 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_usable_workstation_configs: gapic_v1.method.wrap_method( - self.list_usable_workstation_configs, - 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.create_workstation_config: gapic_v1.method.wrap_method( - self.create_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_config: gapic_v1.method.wrap_method( - self.update_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_config: gapic_v1.method.wrap_method( - self.delete_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation: gapic_v1.method.wrap_method( - self.get_workstation, - 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_workstations: gapic_v1.method.wrap_method( - self.list_workstations, - 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_usable_workstations: gapic_v1.method.wrap_method( - self.list_usable_workstations, - 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.create_workstation: gapic_v1.method.wrap_method( - self.create_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation: gapic_v1.method.wrap_method( - self.update_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation: gapic_v1.method.wrap_method( - self.delete_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.start_workstation: gapic_v1.method.wrap_method( - self.start_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.stop_workstation: gapic_v1.method.wrap_method( - self.stop_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_access_token: gapic_v1.method.wrap_method( - self.generate_access_token, - 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_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - 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, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - 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 get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - Union[ - workstations.WorkstationCluster, - Awaitable[workstations.WorkstationCluster] - ]]: - raise NotImplementedError() - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - Union[ - workstations.ListWorkstationClustersResponse, - Awaitable[workstations.ListWorkstationClustersResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - Union[ - workstations.WorkstationConfig, - Awaitable[workstations.WorkstationConfig] - ]]: - raise NotImplementedError() - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - Union[ - workstations.ListWorkstationConfigsResponse, - Awaitable[workstations.ListWorkstationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - Union[ - workstations.ListUsableWorkstationConfigsResponse, - Awaitable[workstations.ListUsableWorkstationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - Union[ - workstations.Workstation, - Awaitable[workstations.Workstation] - ]]: - raise NotImplementedError() - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - Union[ - workstations.ListWorkstationsResponse, - Awaitable[workstations.ListWorkstationsResponse] - ]]: - raise NotImplementedError() - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - Union[ - workstations.ListUsableWorkstationsResponse, - Awaitable[workstations.ListUsableWorkstationsResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - Union[ - workstations.GenerateAccessTokenResponse, - Awaitable[workstations.GenerateAccessTokenResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'WorkstationsTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py deleted file mode 100644 index aa0262c75a33..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py +++ /dev/null @@ -1,948 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO - - -class WorkstationsGrpcTransport(WorkstationsTransport): - """gRPC backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workstations.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: 'workstations.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'workstations.googleapis.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.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - workstations.WorkstationCluster]: - r"""Return a callable for the get workstation cluster method over gRPC. - - Returns the requested workstation cluster. - - Returns: - Callable[[~.GetWorkstationClusterRequest], - ~.WorkstationCluster]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstationCluster', - request_serializer=workstations.GetWorkstationClusterRequest.serialize, - response_deserializer=workstations.WorkstationCluster.deserialize, - ) - return self._stubs['get_workstation_cluster'] - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - workstations.ListWorkstationClustersResponse]: - r"""Return a callable for the list workstation clusters method over gRPC. - - Returns all workstation clusters in the specified - location. - - Returns: - Callable[[~.ListWorkstationClustersRequest], - ~.ListWorkstationClustersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: - self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstationClusters', - request_serializer=workstations.ListWorkstationClustersRequest.serialize, - response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, - ) - return self._stubs['list_workstation_clusters'] - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation cluster method over gRPC. - - Creates a new workstation cluster. - - Returns: - Callable[[~.CreateWorkstationClusterRequest], - ~.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 'create_workstation_cluster' not in self._stubs: - self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstationCluster', - request_serializer=workstations.CreateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_cluster'] - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation cluster method over gRPC. - - Updates an existing workstation cluster. - - Returns: - Callable[[~.UpdateWorkstationClusterRequest], - ~.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 'update_workstation_cluster' not in self._stubs: - self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstationCluster', - request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_cluster'] - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation cluster method over gRPC. - - Deletes the specified workstation cluster. - - Returns: - Callable[[~.DeleteWorkstationClusterRequest], - ~.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 'delete_workstation_cluster' not in self._stubs: - self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstationCluster', - request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_cluster'] - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - workstations.WorkstationConfig]: - r"""Return a callable for the get workstation config method over gRPC. - - Returns the requested workstation configuration. - - Returns: - Callable[[~.GetWorkstationConfigRequest], - ~.WorkstationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstationConfig', - request_serializer=workstations.GetWorkstationConfigRequest.serialize, - response_deserializer=workstations.WorkstationConfig.deserialize, - ) - return self._stubs['get_workstation_config'] - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - workstations.ListWorkstationConfigsResponse]: - r"""Return a callable for the list workstation configs method over gRPC. - - Returns all workstation configurations in the - specified cluster. - - Returns: - Callable[[~.ListWorkstationConfigsRequest], - ~.ListWorkstationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: - self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstationConfigs', - request_serializer=workstations.ListWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_workstation_configs'] - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - workstations.ListUsableWorkstationConfigsResponse]: - r"""Return a callable for the list usable workstation - configs method over gRPC. - - Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - Returns: - Callable[[~.ListUsableWorkstationConfigsRequest], - ~.ListUsableWorkstationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: - self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListUsableWorkstationConfigs', - request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_usable_workstation_configs'] - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation config method over gRPC. - - Creates a new workstation configuration. - - Returns: - Callable[[~.CreateWorkstationConfigRequest], - ~.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 'create_workstation_config' not in self._stubs: - self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstationConfig', - request_serializer=workstations.CreateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_config'] - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation config method over gRPC. - - Updates an existing workstation configuration. - - Returns: - Callable[[~.UpdateWorkstationConfigRequest], - ~.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 'update_workstation_config' not in self._stubs: - self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstationConfig', - request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_config'] - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation config method over gRPC. - - Deletes the specified workstation configuration. - - Returns: - Callable[[~.DeleteWorkstationConfigRequest], - ~.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 'delete_workstation_config' not in self._stubs: - self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstationConfig', - request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_config'] - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - workstations.Workstation]: - r"""Return a callable for the get workstation method over gRPC. - - Returns the requested workstation. - - Returns: - Callable[[~.GetWorkstationRequest], - ~.Workstation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['get_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstation', - request_serializer=workstations.GetWorkstationRequest.serialize, - response_deserializer=workstations.Workstation.deserialize, - ) - return self._stubs['get_workstation'] - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - workstations.ListWorkstationsResponse]: - r"""Return a callable for the list workstations method over gRPC. - - Returns all Workstations using the specified - workstation configuration. - - Returns: - Callable[[~.ListWorkstationsRequest], - ~.ListWorkstationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstations' not in self._stubs: - self._stubs['list_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstations', - request_serializer=workstations.ListWorkstationsRequest.serialize, - response_deserializer=workstations.ListWorkstationsResponse.deserialize, - ) - return self._stubs['list_workstations'] - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - workstations.ListUsableWorkstationsResponse]: - r"""Return a callable for the list usable workstations method over gRPC. - - Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - Returns: - Callable[[~.ListUsableWorkstationsRequest], - ~.ListUsableWorkstationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: - self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListUsableWorkstations', - request_serializer=workstations.ListUsableWorkstationsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, - ) - return self._stubs['list_usable_workstations'] - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation method over gRPC. - - Creates a new workstation. - - Returns: - Callable[[~.CreateWorkstationRequest], - ~.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 'create_workstation' not in self._stubs: - self._stubs['create_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstation', - request_serializer=workstations.CreateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation'] - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation method over gRPC. - - Updates an existing workstation. - - Returns: - Callable[[~.UpdateWorkstationRequest], - ~.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 'update_workstation' not in self._stubs: - self._stubs['update_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstation', - request_serializer=workstations.UpdateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation'] - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation method over gRPC. - - Deletes the specified workstation. - - Returns: - Callable[[~.DeleteWorkstationRequest], - ~.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 'delete_workstation' not in self._stubs: - self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstation', - request_serializer=workstations.DeleteWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation'] - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the start workstation method over gRPC. - - Starts running a workstation so that users can - connect to it. - - Returns: - Callable[[~.StartWorkstationRequest], - ~.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 'start_workstation' not in self._stubs: - self._stubs['start_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/StartWorkstation', - request_serializer=workstations.StartWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['start_workstation'] - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the stop workstation method over gRPC. - - Stops running a workstation, reducing costs. - - Returns: - Callable[[~.StopWorkstationRequest], - ~.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 'stop_workstation' not in self._stubs: - self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/StopWorkstation', - request_serializer=workstations.StopWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['stop_workstation'] - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - workstations.GenerateAccessTokenResponse]: - r"""Return a callable for the generate access token method over gRPC. - - Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - ~.GenerateAccessTokenResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GenerateAccessToken', - request_serializer=workstations.GenerateAccessTokenRequest.serialize, - response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @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.grpc_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 list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'WorkstationsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py deleted file mode 100644 index 27b09102ef5f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py +++ /dev/null @@ -1,1180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .grpc import WorkstationsGrpcTransport - - -class WorkstationsGrpcAsyncIOTransport(WorkstationsTransport): - """gRPC AsyncIO backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workstations.googleapis.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 = 'workstations.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: 'workstations.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - Awaitable[workstations.WorkstationCluster]]: - r"""Return a callable for the get workstation cluster method over gRPC. - - Returns the requested workstation cluster. - - Returns: - Callable[[~.GetWorkstationClusterRequest], - Awaitable[~.WorkstationCluster]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstationCluster', - request_serializer=workstations.GetWorkstationClusterRequest.serialize, - response_deserializer=workstations.WorkstationCluster.deserialize, - ) - return self._stubs['get_workstation_cluster'] - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - Awaitable[workstations.ListWorkstationClustersResponse]]: - r"""Return a callable for the list workstation clusters method over gRPC. - - Returns all workstation clusters in the specified - location. - - Returns: - Callable[[~.ListWorkstationClustersRequest], - Awaitable[~.ListWorkstationClustersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: - self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstationClusters', - request_serializer=workstations.ListWorkstationClustersRequest.serialize, - response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, - ) - return self._stubs['list_workstation_clusters'] - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation cluster method over gRPC. - - Creates a new workstation cluster. - - Returns: - Callable[[~.CreateWorkstationClusterRequest], - 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 'create_workstation_cluster' not in self._stubs: - self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstationCluster', - request_serializer=workstations.CreateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_cluster'] - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation cluster method over gRPC. - - Updates an existing workstation cluster. - - Returns: - Callable[[~.UpdateWorkstationClusterRequest], - 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 'update_workstation_cluster' not in self._stubs: - self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstationCluster', - request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_cluster'] - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation cluster method over gRPC. - - Deletes the specified workstation cluster. - - Returns: - Callable[[~.DeleteWorkstationClusterRequest], - 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 'delete_workstation_cluster' not in self._stubs: - self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstationCluster', - request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_cluster'] - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - Awaitable[workstations.WorkstationConfig]]: - r"""Return a callable for the get workstation config method over gRPC. - - Returns the requested workstation configuration. - - Returns: - Callable[[~.GetWorkstationConfigRequest], - Awaitable[~.WorkstationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstationConfig', - request_serializer=workstations.GetWorkstationConfigRequest.serialize, - response_deserializer=workstations.WorkstationConfig.deserialize, - ) - return self._stubs['get_workstation_config'] - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - Awaitable[workstations.ListWorkstationConfigsResponse]]: - r"""Return a callable for the list workstation configs method over gRPC. - - Returns all workstation configurations in the - specified cluster. - - Returns: - Callable[[~.ListWorkstationConfigsRequest], - Awaitable[~.ListWorkstationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: - self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstationConfigs', - request_serializer=workstations.ListWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_workstation_configs'] - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - Awaitable[workstations.ListUsableWorkstationConfigsResponse]]: - r"""Return a callable for the list usable workstation - configs method over gRPC. - - Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - Returns: - Callable[[~.ListUsableWorkstationConfigsRequest], - Awaitable[~.ListUsableWorkstationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: - self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListUsableWorkstationConfigs', - request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_usable_workstation_configs'] - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation config method over gRPC. - - Creates a new workstation configuration. - - Returns: - Callable[[~.CreateWorkstationConfigRequest], - 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 'create_workstation_config' not in self._stubs: - self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstationConfig', - request_serializer=workstations.CreateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_config'] - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation config method over gRPC. - - Updates an existing workstation configuration. - - Returns: - Callable[[~.UpdateWorkstationConfigRequest], - 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 'update_workstation_config' not in self._stubs: - self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstationConfig', - request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_config'] - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation config method over gRPC. - - Deletes the specified workstation configuration. - - Returns: - Callable[[~.DeleteWorkstationConfigRequest], - 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 'delete_workstation_config' not in self._stubs: - self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstationConfig', - request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_config'] - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - Awaitable[workstations.Workstation]]: - r"""Return a callable for the get workstation method over gRPC. - - Returns the requested workstation. - - Returns: - Callable[[~.GetWorkstationRequest], - Awaitable[~.Workstation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['get_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstation', - request_serializer=workstations.GetWorkstationRequest.serialize, - response_deserializer=workstations.Workstation.deserialize, - ) - return self._stubs['get_workstation'] - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - Awaitable[workstations.ListWorkstationsResponse]]: - r"""Return a callable for the list workstations method over gRPC. - - Returns all Workstations using the specified - workstation configuration. - - Returns: - Callable[[~.ListWorkstationsRequest], - Awaitable[~.ListWorkstationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstations' not in self._stubs: - self._stubs['list_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstations', - request_serializer=workstations.ListWorkstationsRequest.serialize, - response_deserializer=workstations.ListWorkstationsResponse.deserialize, - ) - return self._stubs['list_workstations'] - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - Awaitable[workstations.ListUsableWorkstationsResponse]]: - r"""Return a callable for the list usable workstations method over gRPC. - - Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - Returns: - Callable[[~.ListUsableWorkstationsRequest], - Awaitable[~.ListUsableWorkstationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: - self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListUsableWorkstations', - request_serializer=workstations.ListUsableWorkstationsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, - ) - return self._stubs['list_usable_workstations'] - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation method over gRPC. - - Creates a new workstation. - - Returns: - Callable[[~.CreateWorkstationRequest], - 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 'create_workstation' not in self._stubs: - self._stubs['create_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstation', - request_serializer=workstations.CreateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation'] - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation method over gRPC. - - Updates an existing workstation. - - Returns: - Callable[[~.UpdateWorkstationRequest], - 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 'update_workstation' not in self._stubs: - self._stubs['update_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstation', - request_serializer=workstations.UpdateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation'] - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation method over gRPC. - - Deletes the specified workstation. - - Returns: - Callable[[~.DeleteWorkstationRequest], - 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 'delete_workstation' not in self._stubs: - self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstation', - request_serializer=workstations.DeleteWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation'] - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the start workstation method over gRPC. - - Starts running a workstation so that users can - connect to it. - - Returns: - Callable[[~.StartWorkstationRequest], - 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 'start_workstation' not in self._stubs: - self._stubs['start_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/StartWorkstation', - request_serializer=workstations.StartWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['start_workstation'] - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the stop workstation method over gRPC. - - Stops running a workstation, reducing costs. - - Returns: - Callable[[~.StopWorkstationRequest], - 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 'stop_workstation' not in self._stubs: - self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/StopWorkstation', - request_serializer=workstations.StopWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['stop_workstation'] - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - Awaitable[workstations.GenerateAccessTokenResponse]]: - r"""Return a callable for the generate access token method over gRPC. - - Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - Awaitable[~.GenerateAccessTokenResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GenerateAccessToken', - request_serializer=workstations.GenerateAccessTokenRequest.serialize, - response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - 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_workstation_cluster: self._wrap_method( - self.get_workstation_cluster, - 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_workstation_clusters: self._wrap_method( - self.list_workstation_clusters, - 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.create_workstation_cluster: self._wrap_method( - self.create_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_cluster: self._wrap_method( - self.update_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_cluster: self._wrap_method( - self.delete_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation_config: self._wrap_method( - self.get_workstation_config, - 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_workstation_configs: self._wrap_method( - self.list_workstation_configs, - 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_usable_workstation_configs: self._wrap_method( - self.list_usable_workstation_configs, - 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.create_workstation_config: self._wrap_method( - self.create_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_config: self._wrap_method( - self.update_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_config: self._wrap_method( - self.delete_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation: self._wrap_method( - self.get_workstation, - 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_workstations: self._wrap_method( - self.list_workstations, - 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_usable_workstations: self._wrap_method( - self.list_usable_workstations, - 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.create_workstation: self._wrap_method( - self.create_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation: self._wrap_method( - self.update_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation: self._wrap_method( - self.delete_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.start_workstation: self._wrap_method( - self.start_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.stop_workstation: self._wrap_method( - self.stop_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_access_token: self._wrap_method( - self.generate_access_token, - 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_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @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.grpc_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 list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'WorkstationsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py deleted file mode 100644 index 456fb9226990..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py +++ /dev/null @@ -1,3048 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.workstations_v1.types import workstations -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseWorkstationsRestTransport -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 - - -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 WorkstationsRestInterceptor: - """Interceptor for Workstations. - - 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 WorkstationsRestTransport. - - .. code-block:: python - class MyCustomWorkstationsInterceptor(WorkstationsRestInterceptor): - def pre_create_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_access_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_access_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_usable_workstation_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_usable_workstation_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_usable_workstations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_usable_workstations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstation_clusters(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstation_clusters(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstation_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstation_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_start_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_start_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stop_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stop_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - transport = WorkstationsRestTransport(interceptor=MyCustomWorkstationsInterceptor()) - client = WorkstationsClient(transport=transport) - - - """ - def pre_create_workstation(self, request: workstations.CreateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_create_workstation_cluster(self, request: workstations.CreateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_create_workstation_config(self, request: workstations.CreateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_delete_workstation(self, request: workstations.DeleteWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_delete_workstation_cluster(self, request: workstations.DeleteWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_delete_workstation_config(self, request: workstations.DeleteWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_generate_access_token(self, request: workstations.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_generate_access_token(self, response: workstations.GenerateAccessTokenResponse) -> workstations.GenerateAccessTokenResponse: - """Post-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_workstation(self, request: workstations.GetWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation(self, response: workstations.Workstation) -> workstations.Workstation: - """Post-rpc interceptor for get_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_workstation_cluster(self, request: workstations.GetWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation_cluster(self, response: workstations.WorkstationCluster) -> workstations.WorkstationCluster: - """Post-rpc interceptor for get_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_workstation_config(self, request: workstations.GetWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation_config(self, response: workstations.WorkstationConfig) -> workstations.WorkstationConfig: - """Post-rpc interceptor for get_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_usable_workstation_configs(self, request: workstations.ListUsableWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_usable_workstation_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_usable_workstation_configs(self, response: workstations.ListUsableWorkstationConfigsResponse) -> workstations.ListUsableWorkstationConfigsResponse: - """Post-rpc interceptor for list_usable_workstation_configs - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_usable_workstations(self, request: workstations.ListUsableWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_usable_workstations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_usable_workstations(self, response: workstations.ListUsableWorkstationsResponse) -> workstations.ListUsableWorkstationsResponse: - """Post-rpc interceptor for list_usable_workstations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_workstation_clusters(self, request: workstations.ListWorkstationClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationClustersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstation_clusters - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstation_clusters(self, response: workstations.ListWorkstationClustersResponse) -> workstations.ListWorkstationClustersResponse: - """Post-rpc interceptor for list_workstation_clusters - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_workstation_configs(self, request: workstations.ListWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstation_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstation_configs(self, response: workstations.ListWorkstationConfigsResponse) -> workstations.ListWorkstationConfigsResponse: - """Post-rpc interceptor for list_workstation_configs - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_workstations(self, request: workstations.ListWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstations(self, response: workstations.ListWorkstationsResponse) -> workstations.ListWorkstationsResponse: - """Post-rpc interceptor for list_workstations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_start_workstation(self, request: workstations.StartWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StartWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for start_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_start_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for start_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_stop_workstation(self, request: workstations.StopWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StopWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for stop_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_stop_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for stop_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_update_workstation(self, request: workstations.UpdateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_update_workstation_cluster(self, request: workstations.UpdateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_update_workstation_config(self, request: workstations.UpdateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations 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 Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class WorkstationsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: WorkstationsRestInterceptor - - -class WorkstationsRestTransport(_BaseWorkstationsRestTransport): - """REST backend synchronous transport for Workstations. - - Service for interacting with Cloud Workstations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'workstations.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[WorkstationsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'workstations.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 WorkstationsRestInterceptor() - 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.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - '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 _CreateWorkstation(_BaseWorkstationsRestTransport._BaseCreateWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.CreateWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.CreateWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation method over HTTP. - - Args: - request (~.workstations.CreateWorkstationRequest): - The request object. Message for creating a - CreateWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_http_options() - request, metadata = self._interceptor.pre_create_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._CreateWorkstation._get_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_create_workstation(resp) - return resp - - class _CreateWorkstationCluster(_BaseWorkstationsRestTransport._BaseCreateWorkstationCluster, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.CreateWorkstationCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.CreateWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation - cluster method over HTTP. - - Args: - request (~.workstations.CreateWorkstationClusterRequest): - The request object. Message for creating a - CreateWorkstationCluster. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_http_options() - request, metadata = self._interceptor.pre_create_workstation_cluster(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._CreateWorkstationCluster._get_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_create_workstation_cluster(resp) - return resp - - class _CreateWorkstationConfig(_BaseWorkstationsRestTransport._BaseCreateWorkstationConfig, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.CreateWorkstationConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.CreateWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation config method over HTTP. - - Args: - request (~.workstations.CreateWorkstationConfigRequest): - The request object. Message for creating a - CreateWorkstationConfig. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_http_options() - request, metadata = self._interceptor.pre_create_workstation_config(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._CreateWorkstationConfig._get_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_create_workstation_config(resp) - return resp - - class _DeleteWorkstation(_BaseWorkstationsRestTransport._BaseDeleteWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.DeleteWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.DeleteWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationRequest): - The request object. Request message for - DeleteWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_http_options() - request, metadata = self._interceptor.pre_delete_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._DeleteWorkstation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, 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_delete_workstation(resp) - return resp - - class _DeleteWorkstationCluster(_BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.DeleteWorkstationCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.DeleteWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation - cluster method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationClusterRequest): - The request object. Message for deleting a workstation - cluster. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_http_options() - request, metadata = self._interceptor.pre_delete_workstation_cluster(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._DeleteWorkstationCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, 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_delete_workstation_cluster(resp) - return resp - - class _DeleteWorkstationConfig(_BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.DeleteWorkstationConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.DeleteWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation config method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationConfigRequest): - The request object. Message for deleting a workstation - configuration. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_http_options() - request, metadata = self._interceptor.pre_delete_workstation_config(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._DeleteWorkstationConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, 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_delete_workstation_config(resp) - return resp - - class _GenerateAccessToken(_BaseWorkstationsRestTransport._BaseGenerateAccessToken, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GenerateAccessToken") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.GenerateAccessTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.GenerateAccessTokenResponse: - r"""Call the generate access token method over HTTP. - - Args: - request (~.workstations.GenerateAccessTokenRequest): - The request object. Request message for - GenerateAccessToken. - retry (google.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. - - Returns: - ~.workstations.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_http_options() - request, metadata = self._interceptor.pre_generate_access_token(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GenerateAccessToken._get_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 = workstations.GenerateAccessTokenResponse() - pb_resp = workstations.GenerateAccessTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_access_token(resp) - return resp - - class _GetWorkstation(_BaseWorkstationsRestTransport._BaseGetWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GetWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.GetWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.Workstation: - r"""Call the get workstation method over HTTP. - - Args: - request (~.workstations.GetWorkstationRequest): - The request object. Request message for GetWorkstation. - retry (google.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. - - Returns: - ~.workstations.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_http_options() - request, metadata = self._interceptor.pre_get_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GetWorkstation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.Workstation() - pb_resp = workstations.Workstation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation(resp) - return resp - - class _GetWorkstationCluster(_BaseWorkstationsRestTransport._BaseGetWorkstationCluster, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GetWorkstationCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.GetWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.WorkstationCluster: - r"""Call the get workstation cluster method over HTTP. - - Args: - request (~.workstations.GetWorkstationClusterRequest): - The request object. Request message for - GetWorkstationCluster. - retry (google.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. - - Returns: - ~.workstations.WorkstationCluster: - A workstation cluster resource in the - Cloud Workstations API. - Defines a group of workstations in a - particular region and the VPC network - they're attached to. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_http_options() - request, metadata = self._interceptor.pre_get_workstation_cluster(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GetWorkstationCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.WorkstationCluster() - pb_resp = workstations.WorkstationCluster.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation_cluster(resp) - return resp - - class _GetWorkstationConfig(_BaseWorkstationsRestTransport._BaseGetWorkstationConfig, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GetWorkstationConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.GetWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.WorkstationConfig: - r"""Call the get workstation config method over HTTP. - - Args: - request (~.workstations.GetWorkstationConfigRequest): - The request object. Request message for - GetWorkstationConfig. - retry (google.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. - - Returns: - ~.workstations.WorkstationConfig: - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to use, - and more. Administrators and platform teams can also use - `Identity and Access Management - (IAM) `__ - rules to grant access to teams or to individual - developers. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_http_options() - request, metadata = self._interceptor.pre_get_workstation_config(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GetWorkstationConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.WorkstationConfig() - pb_resp = workstations.WorkstationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation_config(resp) - return resp - - class _ListUsableWorkstationConfigs(_BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListUsableWorkstationConfigs") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListUsableWorkstationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListUsableWorkstationConfigsResponse: - r"""Call the list usable workstation - configs method over HTTP. - - Args: - request (~.workstations.ListUsableWorkstationConfigsRequest): - The request object. Request message for - ListUsableWorkstationConfigs. - retry (google.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. - - Returns: - ~.workstations.ListUsableWorkstationConfigsResponse: - Response message for - ListUsableWorkstationConfigs. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_http_options() - request, metadata = self._interceptor.pre_list_usable_workstation_configs(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListUsableWorkstationConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListUsableWorkstationConfigsResponse() - pb_resp = workstations.ListUsableWorkstationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_usable_workstation_configs(resp) - return resp - - class _ListUsableWorkstations(_BaseWorkstationsRestTransport._BaseListUsableWorkstations, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListUsableWorkstations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListUsableWorkstationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListUsableWorkstationsResponse: - r"""Call the list usable workstations method over HTTP. - - Args: - request (~.workstations.ListUsableWorkstationsRequest): - The request object. Request message for - ListUsableWorkstations. - retry (google.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. - - Returns: - ~.workstations.ListUsableWorkstationsResponse: - Response message for - ListUsableWorkstations. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_http_options() - request, metadata = self._interceptor.pre_list_usable_workstations(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListUsableWorkstations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListUsableWorkstationsResponse() - pb_resp = workstations.ListUsableWorkstationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_usable_workstations(resp) - return resp - - class _ListWorkstationClusters(_BaseWorkstationsRestTransport._BaseListWorkstationClusters, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListWorkstationClusters") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListWorkstationClustersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationClustersResponse: - r"""Call the list workstation clusters method over HTTP. - - Args: - request (~.workstations.ListWorkstationClustersRequest): - The request object. Request message for - ListWorkstationClusters. - retry (google.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. - - Returns: - ~.workstations.ListWorkstationClustersResponse: - Response message for - ListWorkstationClusters. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_http_options() - request, metadata = self._interceptor.pre_list_workstation_clusters(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListWorkstationClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListWorkstationClustersResponse() - pb_resp = workstations.ListWorkstationClustersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstation_clusters(resp) - return resp - - class _ListWorkstationConfigs(_BaseWorkstationsRestTransport._BaseListWorkstationConfigs, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListWorkstationConfigs") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListWorkstationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationConfigsResponse: - r"""Call the list workstation configs method over HTTP. - - Args: - request (~.workstations.ListWorkstationConfigsRequest): - The request object. Request message for - ListWorkstationConfigs. - retry (google.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. - - Returns: - ~.workstations.ListWorkstationConfigsResponse: - Response message for - ListWorkstationConfigs. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_http_options() - request, metadata = self._interceptor.pre_list_workstation_configs(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListWorkstationConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListWorkstationConfigsResponse() - pb_resp = workstations.ListWorkstationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstation_configs(resp) - return resp - - class _ListWorkstations(_BaseWorkstationsRestTransport._BaseListWorkstations, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListWorkstations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListWorkstationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationsResponse: - r"""Call the list workstations method over HTTP. - - Args: - request (~.workstations.ListWorkstationsRequest): - The request object. Request message for ListWorkstations. - retry (google.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. - - Returns: - ~.workstations.ListWorkstationsResponse: - Response message for - ListWorkstations. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListWorkstations._get_http_options() - request, metadata = self._interceptor.pre_list_workstations(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListWorkstations._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListWorkstations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListWorkstationsResponse() - pb_resp = workstations.ListWorkstationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstations(resp) - return resp - - class _StartWorkstation(_BaseWorkstationsRestTransport._BaseStartWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.StartWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.StartWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the start workstation method over HTTP. - - Args: - request (~.workstations.StartWorkstationRequest): - The request object. Request message for StartWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_http_options() - request, metadata = self._interceptor.pre_start_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._StartWorkstation._get_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_start_workstation(resp) - return resp - - class _StopWorkstation(_BaseWorkstationsRestTransport._BaseStopWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.StopWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.StopWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the stop workstation method over HTTP. - - Args: - request (~.workstations.StopWorkstationRequest): - The request object. Request message for StopWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_http_options() - request, metadata = self._interceptor.pre_stop_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._StopWorkstation._get_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_stop_workstation(resp) - return resp - - class _UpdateWorkstation(_BaseWorkstationsRestTransport._BaseUpdateWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.UpdateWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.UpdateWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationRequest): - The request object. Request message for - UpdateWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_http_options() - request, metadata = self._interceptor.pre_update_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._UpdateWorkstation._get_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_update_workstation(resp) - return resp - - class _UpdateWorkstationCluster(_BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.UpdateWorkstationCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.UpdateWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation - cluster method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationClusterRequest): - The request object. Request message for - UpdateWorkstationCluster. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_http_options() - request, metadata = self._interceptor.pre_update_workstation_cluster(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._UpdateWorkstationCluster._get_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_update_workstation_cluster(resp) - return resp - - class _UpdateWorkstationConfig(_BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.UpdateWorkstationConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.UpdateWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation config method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationConfigRequest): - The request object. Request message for - UpdateWorkstationConfig. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_http_options() - request, metadata = self._interceptor.pre_update_workstation_config(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._UpdateWorkstationConfig._get_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_update_workstation_config(resp) - return resp - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - 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._CreateWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - 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._CreateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - 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._CreateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - 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._DeleteWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - 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._DeleteWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - 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._DeleteWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - workstations.GenerateAccessTokenResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - workstations.Workstation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - workstations.WorkstationCluster]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - workstations.WorkstationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - workstations.ListUsableWorkstationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListUsableWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - workstations.ListUsableWorkstationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListUsableWorkstations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - workstations.ListWorkstationClustersResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstationClusters(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - workstations.ListWorkstationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - workstations.ListWorkstationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstations(self._session, self._host, self._interceptor) # type: ignore - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - 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._StartWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - 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._StopWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - 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._UpdateWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - 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._UpdateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - 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._UpdateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseWorkstationsRestTransport._BaseGetIamPolicy, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.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. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseWorkstationsRestTransport._BaseSetIamPolicy, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.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. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._SetIamPolicy._get_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) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseWorkstationsRestTransport._BaseTestIamPermissions, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.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. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._TestIamPermissions._get_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) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseWorkstationsRestTransport._BaseCancelOperation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.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. - """ - - http_options = _BaseWorkstationsRestTransport._BaseCancelOperation._get_http_options() - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._CancelOperation._get_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 self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseWorkstationsRestTransport._BaseDeleteOperation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(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.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.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. - """ - - http_options = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseWorkstationsRestTransport._BaseGetOperation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._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) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseWorkstationsRestTransport._BaseListOperations, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(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.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.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. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'WorkstationsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest_base.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest_base.py deleted file mode 100644 index 4156ac1fa50d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest_base.py +++ /dev/null @@ -1,1129 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.workstations_v1.types import workstations -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseWorkstationsRestTransport(WorkstationsTransport): - """Base REST backend transport for Workstations. - - 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 = 'workstations.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: 'workstations.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 _BaseCreateWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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/*/workstationClusters/*/workstationConfigs/*}/workstations', - 'body': 'workstation', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.CreateWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateWorkstationCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationClusterId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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/*}/workstationClusters', - 'body': 'workstation_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.CreateWorkstationClusterRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateWorkstationConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationConfigId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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/*/workstationClusters/*}/workstationConfigs', - 'body': 'workstation_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.CreateWorkstationConfigRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.DeleteWorkstationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteWorkstationCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.DeleteWorkstationClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteWorkstationConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.DeleteWorkstationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGenerateAccessToken: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.GenerateAccessTokenRequest.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(_BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.GetWorkstationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetWorkstationCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.GetWorkstationClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetWorkstationConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.GetWorkstationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListUsableWorkstationConfigs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListUsableWorkstationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListUsableWorkstations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListUsableWorkstationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkstationClusters: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/workstationClusters', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListWorkstationClustersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkstationConfigs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListWorkstationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkstations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListWorkstationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstations._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStartWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.StartWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseStartWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStopWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.StopWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseStopWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateWorkstation: - 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': '/v1/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - 'body': 'workstation', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.UpdateWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateWorkstationCluster: - 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': '/v1/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}', - 'body': 'workstation_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.UpdateWorkstationClusterRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateWorkstationConfig: - 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': '/v1/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - 'body': 'workstation_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.UpdateWorkstationConfigRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetIamPolicy: - 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/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:getIamPolicy', - }, - ] - 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 - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:setIamPolicy', - 'body': '*', - }, - ] - 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_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:testIamPermissions', - 'body': '*', - }, - ] - 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_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - 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_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseDeleteOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - '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 - - 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 - - class _BaseListOperations: - 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__=( - '_BaseWorkstationsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py deleted file mode 100644 index 74244c2b3708..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .workstations import ( - CreateWorkstationClusterRequest, - CreateWorkstationConfigRequest, - CreateWorkstationRequest, - DeleteWorkstationClusterRequest, - DeleteWorkstationConfigRequest, - DeleteWorkstationRequest, - GenerateAccessTokenRequest, - GenerateAccessTokenResponse, - GetWorkstationClusterRequest, - GetWorkstationConfigRequest, - GetWorkstationRequest, - ListUsableWorkstationConfigsRequest, - ListUsableWorkstationConfigsResponse, - ListUsableWorkstationsRequest, - ListUsableWorkstationsResponse, - ListWorkstationClustersRequest, - ListWorkstationClustersResponse, - ListWorkstationConfigsRequest, - ListWorkstationConfigsResponse, - ListWorkstationsRequest, - ListWorkstationsResponse, - OperationMetadata, - StartWorkstationRequest, - StopWorkstationRequest, - UpdateWorkstationClusterRequest, - UpdateWorkstationConfigRequest, - UpdateWorkstationRequest, - Workstation, - WorkstationCluster, - WorkstationConfig, -) - -__all__ = ( - 'CreateWorkstationClusterRequest', - 'CreateWorkstationConfigRequest', - 'CreateWorkstationRequest', - 'DeleteWorkstationClusterRequest', - 'DeleteWorkstationConfigRequest', - 'DeleteWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GetWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'OperationMetadata', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'UpdateWorkstationClusterRequest', - 'UpdateWorkstationConfigRequest', - 'UpdateWorkstationRequest', - 'Workstation', - 'WorkstationCluster', - 'WorkstationConfig', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py deleted file mode 100644 index ef51fb4cc435..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py +++ /dev/null @@ -1,1953 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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 field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.workstations.v1', - manifest={ - 'WorkstationCluster', - 'WorkstationConfig', - 'Workstation', - 'GetWorkstationClusterRequest', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'CreateWorkstationClusterRequest', - 'UpdateWorkstationClusterRequest', - 'DeleteWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'CreateWorkstationConfigRequest', - 'UpdateWorkstationConfigRequest', - 'DeleteWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'CreateWorkstationRequest', - 'UpdateWorkstationRequest', - 'DeleteWorkstationRequest', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'OperationMetadata', - }, -) - - -class WorkstationCluster(proto.Message): - r"""A workstation cluster resource in the Cloud Workstations API. - - Defines a group of workstations in a particular region and the - VPC network they're attached to. - - Attributes: - name (str): - Full name of this workstation cluster. - display_name (str): - Optional. Human-readable name for this - workstation cluster. - uid (str): - Output only. A system-assigned unique - identifier for this workstation cluster. - reconciling (bool): - Output only. Indicates whether this - workstation cluster is currently being updated - to match its intended state. - annotations (MutableMapping[str, str]): - Optional. Client-specified annotations. - labels (MutableMapping[str, str]): - Optional. - `Labels `__ - that are applied to the workstation cluster and that are - also propagated to the underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - cluster was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - cluster was most recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - cluster was soft-deleted. - etag (str): - Optional. Checksum computed by the server. - May be sent on update and delete requests to - make sure that the client has an up-to-date - value before proceeding. - network (str): - Immutable. Name of the Compute Engine network - in which instances associated with this - workstation cluster will be created. - subnetwork (str): - Immutable. Name of the Compute Engine - subnetwork in which instances associated with - this workstation cluster will be created. Must - be part of the subnetwork specified for this - workstation cluster. - control_plane_ip (str): - Output only. The private IP address of the - control plane for this workstation cluster. - Workstation VMs need access to this IP address - to work with the service, so make sure that your - firewall rules allow egress from the workstation - VMs to this address. - private_cluster_config (google.cloud.workstations_v1.types.WorkstationCluster.PrivateClusterConfig): - Optional. Configuration for private - workstation cluster. - degraded (bool): - Output only. Whether this workstation cluster is in degraded - mode, in which case it may require user action to restore - full functionality. Details can be found in - [conditions][google.cloud.workstations.v1.WorkstationCluster.conditions]. - conditions (MutableSequence[google.rpc.status_pb2.Status]): - Output only. Status conditions describing the - workstation cluster's current state. - """ - - class PrivateClusterConfig(proto.Message): - r"""Configuration options for private workstation clusters. - - Attributes: - enable_private_endpoint (bool): - Immutable. Whether Workstations endpoint is - private. - cluster_hostname (str): - Output only. Hostname for the workstation - cluster. This field will be populated only when - private endpoint is enabled. To access - workstations in the workstation cluster, create - a new DNS zone mapping this domain name to an - internal IP address and a forwarding rule - mapping that address to the service attachment. - service_attachment_uri (str): - Output only. Service attachment URI for the workstation - cluster. The service attachemnt is created when private - endpoint is enabled. To access workstations in the - workstation cluster, configure access to the managed service - using `Private Service - Connect `__. - allowed_projects (MutableSequence[str]): - Optional. Additional projects that are - allowed to attach to the workstation cluster's - service attachment. By default, the workstation - cluster's project and the VPC host project (if - different) are allowed. - """ - - enable_private_endpoint: bool = proto.Field( - proto.BOOL, - number=1, - ) - cluster_hostname: str = proto.Field( - proto.STRING, - number=2, - ) - service_attachment_uri: str = proto.Field( - proto.STRING, - number=3, - ) - allowed_projects: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - 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, - ) - delete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=9, - ) - network: str = proto.Field( - proto.STRING, - number=10, - ) - subnetwork: str = proto.Field( - proto.STRING, - number=11, - ) - control_plane_ip: str = proto.Field( - proto.STRING, - number=16, - ) - private_cluster_config: PrivateClusterConfig = proto.Field( - proto.MESSAGE, - number=12, - message=PrivateClusterConfig, - ) - degraded: bool = proto.Field( - proto.BOOL, - number=13, - ) - conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=status_pb2.Status, - ) - - -class WorkstationConfig(proto.Message): - r"""A workstation configuration resource in the Cloud Workstations API. - - Workstation configurations act as templates for workstations. The - workstation configuration defines details such as the workstation - virtual machine (VM) instance type, persistent storage, container - image defining environment, which IDE or Code Editor to use, and - more. Administrators and platform teams can also use `Identity and - Access Management - (IAM) `__ rules to grant - access to teams or to individual developers. - - Attributes: - name (str): - Full name of this workstation configuration. - display_name (str): - Optional. Human-readable name for this - workstation configuration. - uid (str): - Output only. A system-assigned unique - identifier for this workstation configuration. - reconciling (bool): - Output only. Indicates whether this - workstation configuration is currently being - updated to match its intended state. - annotations (MutableMapping[str, str]): - Optional. Client-specified annotations. - labels (MutableMapping[str, str]): - Optional. - `Labels `__ - that are applied to the workstation configuration and that - are also propagated to the underlying Compute Engine - resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - configuration was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - configuration was most recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - configuration was soft-deleted. - etag (str): - Optional. Checksum computed by the server. - May be sent on update and delete requests to - make sure that the client has an up-to-date - value before proceeding. - idle_timeout (google.protobuf.duration_pb2.Duration): - Optional. Number of seconds to wait before automatically - stopping a workstation after it last received user traffic. - - A value of ``"0s"`` indicates that Cloud Workstations VMs - created with this configuration should never time out due to - idleness. Provide - `duration `__ - terminated by ``s`` for seconds—for example, ``"7200s"`` (2 - hours). The default is ``"1200s"`` (20 minutes). - running_timeout (google.protobuf.duration_pb2.Duration): - Optional. Number of seconds that a workstation can run until - it is automatically shut down. We recommend that - workstations be shut down daily to reduce costs and so that - security updates can be applied upon restart. The - [idle_timeout][google.cloud.workstations.v1.WorkstationConfig.idle_timeout] - and - [running_timeout][google.cloud.workstations.v1.WorkstationConfig.running_timeout] - fields are independent of each other. Note that the - [running_timeout][google.cloud.workstations.v1.WorkstationConfig.running_timeout] - field shuts down VMs after the specified time, regardless of - whether or not the VMs are idle. - - Provide duration terminated by ``s`` for seconds—for - example, ``"54000s"`` (15 hours). Defaults to ``"43200s"`` - (12 hours). A value of ``"0s"`` indicates that workstations - using this configuration should never time out. If - [encryption_key][google.cloud.workstations.v1.WorkstationConfig.encryption_key] - is set, it must be greater than ``"0s"`` and less than - ``"86400s"`` (24 hours). - - Warning: A value of ``"0s"`` indicates that Cloud - Workstations VMs created with this configuration have no - maximum running time. This is strongly discouraged because - you incur costs and will not pick up security updates. - host (google.cloud.workstations_v1.types.WorkstationConfig.Host): - Optional. Runtime host for the workstation. - persistent_directories (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory]): - Optional. Directories to persist across - workstation sessions. - container (google.cloud.workstations_v1.types.WorkstationConfig.Container): - Optional. Container that runs upon startup - for each workstation using this workstation - configuration. - encryption_key (google.cloud.workstations_v1.types.WorkstationConfig.CustomerEncryptionKey): - Immutable. Encrypts resources of this - workstation configuration using a - customer-managed encryption key (CMEK). - - If specified, the boot disk of the Compute - Engine instance and the persistent disk are - encrypted using this encryption key. If this - field is not set, the disks are encrypted using - a generated key. Customer-managed encryption - keys do not protect disk metadata. - - If the customer-managed encryption key is - rotated, when the workstation instance is - stopped, the system attempts to recreate the - persistent disk with the new version of the key. - Be sure to keep older versions of the key until - the persistent disk is recreated. Otherwise, - data on the persistent disk might be lost. - - If the encryption key is revoked, the - workstation session automatically stops within 7 - hours. - - Immutable after the workstation configuration is - created. - readiness_checks (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig.ReadinessCheck]): - Optional. Readiness checks to perform when - starting a workstation using this workstation - configuration. Mark a workstation as running - only after all specified readiness checks return - 200 status codes. - replica_zones (MutableSequence[str]): - Optional. Immutable. Specifies the zones used to replicate - the VM and disk resources within the region. If set, exactly - two zones within the workstation cluster's region must be - specified—for example, - ``['us-central1-a', 'us-central1-f']``. If this field is - empty, two default zones within the region are used. - - Immutable after the workstation configuration is created. - degraded (bool): - Output only. Whether this resource is degraded, in which - case it may require user action to restore full - functionality. See also the - [conditions][google.cloud.workstations.v1.WorkstationConfig.conditions] - field. - conditions (MutableSequence[google.rpc.status_pb2.Status]): - Output only. Status conditions describing the - current resource state. - """ - - class Host(proto.Message): - r"""Runtime host for a workstation. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gce_instance (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance): - Specifies a Compute Engine instance as the - host. - - This field is a member of `oneof`_ ``config``. - """ - - class GceInstance(proto.Message): - r"""A runtime using a Compute Engine instance. - - Attributes: - machine_type (str): - Optional. The type of machine to use for VM instances—for - example, ``"e2-standard-4"``. For more information about - machine types that Cloud Workstations supports, see the list - of `available machine - types `__. - service_account (str): - Optional. The email address of the service account for Cloud - Workstations VMs created with this configuration. When - specified, be sure that the service account has - ``logginglogEntries.create`` permission on the project so it - can write logs out to Cloud Logging. If using a custom - container image, the service account must have permissions - to pull the specified image. - - If you as the administrator want to be able to ``ssh`` into - the underlying VM, you need to set this value to a service - account for which you have the ``iam.serviceAccounts.actAs`` - permission. Conversely, if you don't want anyone to be able - to ``ssh`` into the underlying VM, use a service account - where no one has that permission. - - If not set, VMs run with a service account provided by the - Cloud Workstations service, and the image must be publicly - accessible. - service_account_scopes (MutableSequence[str]): - Optional. Scopes to grant to the - [service_account][google.cloud.workstations.v1.WorkstationConfig.Host.GceInstance.service_account]. - Various scopes are automatically added based on feature - usage. When specified, users of workstations under this - configuration must have ``iam.serviceAccounts.actAs`` on the - service account. - tags (MutableSequence[str]): - Optional. Network tags to add to the Compute Engine VMs - backing the workstations. This option applies `network - tags `__ - to VMs created with this configuration. These network tags - enable the creation of `firewall - rules `__. - pool_size (int): - Optional. The number of VMs that the system should keep idle - so that new workstations can be started quickly for new - users. Defaults to ``0`` in the API. - pooled_instances (int): - Output only. Number of instances currently - available in the pool for faster workstation - startup. - disable_public_ip_addresses (bool): - Optional. When set to true, disables public IP addresses for - VMs. If you disable public IP addresses, you must set up - Private Google Access or Cloud NAT on your network. If you - use Private Google Access and you use - ``private.googleapis.com`` or ``restricted.googleapis.com`` - for Container Registry and Artifact Registry, make sure that - you set up DNS records for domains ``*.gcr.io`` and - ``*.pkg.dev``. Defaults to false (VMs have public IP - addresses). - enable_nested_virtualization (bool): - Optional. Whether to enable nested virtualization on Cloud - Workstations VMs created under this workstation - configuration. - - Nested virtualization lets you run virtual machine (VM) - instances inside your workstation. Before enabling nested - virtualization, consider the following important - considerations. Cloud Workstations instances are subject to - the `same restrictions as Compute Engine - instances `__: - - - **Organization policy**: projects, folders, or - organizations may be restricted from creating nested VMs - if the **Disable VM nested virtualization** constraint is - enforced in the organization policy. For more - information, see the Compute Engine section, `Checking - whether nested virtualization is - allowed `__. - - **Performance**: nested VMs might experience a 10% or - greater decrease in performance for workloads that are - CPU-bound and possibly greater than a 10% decrease for - workloads that are input/output bound. - - **Machine Type**: nested virtualization can only be - enabled on workstation configurations that specify a - [machine_type][google.cloud.workstations.v1.WorkstationConfig.Host.GceInstance.machine_type] - in the N1 or N2 machine series. - - **GPUs**: nested virtualization may not be enabled on - workstation configurations with accelerators. - - **Operating System**: Because `Container-Optimized - OS `__ - does not support nested virtualization, when nested - virtualization is enabled, the underlying Compute Engine - VM instances boot from an `Ubuntu - LTS `__ - image. - shielded_instance_config (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig): - Optional. A set of Compute Engine Shielded - instance options. - confidential_instance_config (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig): - Optional. A set of Compute Engine - Confidential VM instance options. - boot_disk_size_gb (int): - Optional. The size of the boot disk for the VM in gigabytes - (GB). The minimum boot disk size is ``30`` GB. Defaults to - ``50`` GB. - """ - - class GceShieldedInstanceConfig(proto.Message): - r"""A set of Compute Engine Shielded instance options. - - Attributes: - enable_secure_boot (bool): - Optional. Whether the instance has Secure - Boot enabled. - enable_vtpm (bool): - Optional. Whether the instance has the vTPM - enabled. - enable_integrity_monitoring (bool): - Optional. Whether the instance has integrity - monitoring enabled. - """ - - enable_secure_boot: bool = proto.Field( - proto.BOOL, - number=1, - ) - enable_vtpm: bool = proto.Field( - proto.BOOL, - number=2, - ) - enable_integrity_monitoring: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class GceConfidentialInstanceConfig(proto.Message): - r"""A set of Compute Engine Confidential VM instance options. - - Attributes: - enable_confidential_compute (bool): - Optional. Whether the instance has - confidential compute enabled. - """ - - enable_confidential_compute: bool = proto.Field( - proto.BOOL, - number=1, - ) - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - service_account: str = proto.Field( - proto.STRING, - number=2, - ) - service_account_scopes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - pool_size: int = proto.Field( - proto.INT32, - number=5, - ) - pooled_instances: int = proto.Field( - proto.INT32, - number=12, - ) - disable_public_ip_addresses: bool = proto.Field( - proto.BOOL, - number=6, - ) - enable_nested_virtualization: bool = proto.Field( - proto.BOOL, - number=7, - ) - shielded_instance_config: 'WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig' = proto.Field( - proto.MESSAGE, - number=8, - message='WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig', - ) - confidential_instance_config: 'WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig', - ) - boot_disk_size_gb: int = proto.Field( - proto.INT32, - number=9, - ) - - gce_instance: 'WorkstationConfig.Host.GceInstance' = proto.Field( - proto.MESSAGE, - number=1, - oneof='config', - message='WorkstationConfig.Host.GceInstance', - ) - - class PersistentDirectory(proto.Message): - r"""A directory to persist across workstation sessions. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gce_pd (google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk): - A PersistentDirectory backed by a Compute - Engine persistent disk. - - This field is a member of `oneof`_ ``directory_type``. - mount_path (str): - Optional. Location of this directory in the - running workstation. - """ - - class GceRegionalPersistentDisk(proto.Message): - r"""A PersistentDirectory backed by a Compute Engine regional persistent - disk. The - [persistent_directories][google.cloud.workstations.v1.WorkstationConfig.persistent_directories] - field is repeated, but it may contain only one entry. It creates a - `persistent - disk `__ - that mounts to the workstation VM at ``/home`` when the session - starts and detaches when the session ends. If this field is empty, - workstations created with this configuration do not have a - persistent home directory. - - Attributes: - size_gb (int): - Optional. The GB capacity of a persistent home directory for - each workstation created with this configuration. Must be - empty if - [source_snapshot][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.source_snapshot] - is set. - - Valid values are ``10``, ``50``, ``100``, ``200``, ``500``, - or ``1000``. Defaults to ``200``. If less than ``200`` GB, - the - [disk_type][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.disk_type] - must be ``"pd-balanced"`` or ``"pd-ssd"``. - fs_type (str): - Optional. Type of file system that the disk should be - formatted with. The workstation image must support this file - system type. Must be empty if - [source_snapshot][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.source_snapshot] - is set. Defaults to ``"ext4"``. - disk_type (str): - Optional. The `type of the persistent - disk `__ - for the home directory. Defaults to ``"pd-standard"``. - source_snapshot (str): - Optional. Name of the snapshot to use as the source for the - disk. If set, - [size_gb][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.size_gb] - and - [fs_type][google.cloud.workstations.v1.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.fs_type] - must be empty. - reclaim_policy (google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy): - Optional. Whether the persistent disk should be deleted when - the workstation is deleted. Valid values are ``DELETE`` and - ``RETAIN``. Defaults to ``DELETE``. - """ - class ReclaimPolicy(proto.Enum): - r"""Value representing what should happen to the disk after the - workstation is deleted. - - Values: - RECLAIM_POLICY_UNSPECIFIED (0): - Do not use. - DELETE (1): - Delete the persistent disk when deleting the - workstation. - RETAIN (2): - Keep the persistent disk when deleting the - workstation. An administrator must manually - delete the disk. - """ - RECLAIM_POLICY_UNSPECIFIED = 0 - DELETE = 1 - RETAIN = 2 - - size_gb: int = proto.Field( - proto.INT32, - number=1, - ) - fs_type: str = proto.Field( - proto.STRING, - number=2, - ) - disk_type: str = proto.Field( - proto.STRING, - number=3, - ) - source_snapshot: str = proto.Field( - proto.STRING, - number=5, - ) - reclaim_policy: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy' = proto.Field( - proto.ENUM, - number=4, - enum='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy', - ) - - gce_pd: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk' = proto.Field( - proto.MESSAGE, - number=2, - oneof='directory_type', - message='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk', - ) - mount_path: str = proto.Field( - proto.STRING, - number=1, - ) - - class Container(proto.Message): - r"""A Docker container. - - Attributes: - image (str): - Optional. A Docker container image that defines a custom - environment. - - Cloud Workstations provides a number of `preconfigured - images `__, - but you can create your own `custom container - images `__. - If using a private image, the - ``host.gceInstance.serviceAccount`` field must be specified - in the workstation configuration and must have permission to - pull the specified image. Otherwise, the image must be - publicly accessible. - command (MutableSequence[str]): - Optional. If set, overrides the default - ENTRYPOINT specified by the image. - args (MutableSequence[str]): - Optional. Arguments passed to the entrypoint. - env (MutableMapping[str, str]): - Optional. Environment variables passed to the - container's entrypoint. - working_dir (str): - Optional. If set, overrides the default DIR - specified by the image. - run_as_user (int): - Optional. If set, overrides the USER - specified in the image with the given uid. - """ - - image: str = proto.Field( - proto.STRING, - number=1, - ) - command: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - env: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - working_dir: str = proto.Field( - proto.STRING, - number=5, - ) - run_as_user: int = proto.Field( - proto.INT32, - number=6, - ) - - class CustomerEncryptionKey(proto.Message): - r"""A customer-managed encryption key (CMEK) for the Compute Engine - resources of the associated workstation configuration. Specify the - name of your Cloud KMS encryption key and the default service - account. We recommend that you use a separate service account and - follow `Cloud KMS best - practices `__. - - Attributes: - kms_key (str): - Immutable. The name of the Google Cloud KMS encryption key. - For example, - ``"projects/PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY_NAME"``. - The key must be in the same region as the workstation - configuration. - kms_key_service_account (str): - Immutable. The service account to use with the specified KMS - key. We recommend that you use a separate service account - and follow KMS best practices. For more information, see - `Separation of - duties `__ - and ``gcloud kms keys add-iam-policy-binding`` - ```--member`` `__. - """ - - kms_key: str = proto.Field( - proto.STRING, - number=1, - ) - kms_key_service_account: str = proto.Field( - proto.STRING, - number=2, - ) - - class ReadinessCheck(proto.Message): - r"""A readiness check to be performed on a workstation. - - Attributes: - path (str): - Optional. Path to which the request should be - sent. - port (int): - Optional. Port to which the request should be - sent. - """ - - path: str = proto.Field( - proto.STRING, - number=1, - ) - port: int = proto.Field( - proto.INT32, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=18, - ) - 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, - ) - delete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=9, - ) - idle_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=10, - message=duration_pb2.Duration, - ) - running_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=11, - message=duration_pb2.Duration, - ) - host: Host = proto.Field( - proto.MESSAGE, - number=12, - message=Host, - ) - persistent_directories: MutableSequence[PersistentDirectory] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=PersistentDirectory, - ) - container: Container = proto.Field( - proto.MESSAGE, - number=14, - message=Container, - ) - encryption_key: CustomerEncryptionKey = proto.Field( - proto.MESSAGE, - number=17, - message=CustomerEncryptionKey, - ) - readiness_checks: MutableSequence[ReadinessCheck] = proto.RepeatedField( - proto.MESSAGE, - number=19, - message=ReadinessCheck, - ) - replica_zones: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=23, - ) - degraded: bool = proto.Field( - proto.BOOL, - number=15, - ) - conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=16, - message=status_pb2.Status, - ) - - -class Workstation(proto.Message): - r"""A single instance of a developer workstation with its own - persistent storage. - - Attributes: - name (str): - Full name of this workstation. - display_name (str): - Optional. Human-readable name for this - workstation. - uid (str): - Output only. A system-assigned unique - identifier for this workstation. - reconciling (bool): - Output only. Indicates whether this - workstation is currently being updated to match - its intended state. - annotations (MutableMapping[str, str]): - Optional. Client-specified annotations. - labels (MutableMapping[str, str]): - Optional. - `Labels `__ - that are applied to the workstation and that are also - propagated to the underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation was - most recently updated. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation was - most recently successfully started, regardless - of the workstation's initial state. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation was - soft-deleted. - etag (str): - Optional. Checksum computed by the server. - May be sent on update and delete requests to - make sure that the client has an up-to-date - value before proceeding. - state (google.cloud.workstations_v1.types.Workstation.State): - Output only. Current state of the - workstation. - host (str): - Output only. Host to which clients can send HTTPS traffic - that will be received by the workstation. Authorized traffic - will be received to the workstation as HTTP on port 80. To - send traffic to a different port, clients may prefix the - host with the destination port in the format - ``{port}-{host}``. - """ - class State(proto.Enum): - r"""Whether a workstation is running and ready to receive user - requests. - - Values: - STATE_UNSPECIFIED (0): - Do not use. - STATE_STARTING (1): - The workstation is not yet ready to accept - requests from users but will be soon. - STATE_RUNNING (2): - The workstation is ready to accept requests - from users. - STATE_STOPPING (3): - The workstation is being stopped. - STATE_STOPPED (4): - The workstation is stopped and will not be - able to receive requests until it is started. - """ - STATE_UNSPECIFIED = 0 - STATE_STARTING = 1 - STATE_RUNNING = 2 - STATE_STOPPING = 3 - STATE_STOPPED = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=13, - ) - 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, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=14, - message=timestamp_pb2.Timestamp, - ) - delete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=9, - ) - state: State = proto.Field( - proto.ENUM, - number=10, - enum=State, - ) - host: str = proto.Field( - proto.STRING, - number=11, - ) - - -class GetWorkstationClusterRequest(proto.Message): - r"""Request message for GetWorkstationCluster. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationClustersRequest(proto.Message): - r"""Request message for ListWorkstationClusters. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListWorkstationClustersResponse(proto.Message): - r"""Response message for ListWorkstationClusters. - - Attributes: - workstation_clusters (MutableSequence[google.cloud.workstations_v1.types.WorkstationCluster]): - The requested workstation clusters. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_clusters: MutableSequence['WorkstationCluster'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationCluster', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationClusterRequest(proto.Message): - r"""Message for creating a CreateWorkstationCluster. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_cluster_id (str): - Required. ID to use for the workstation - cluster. - workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): - Required. Workstation cluster to create. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_cluster_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation_cluster: 'WorkstationCluster' = proto.Field( - proto.MESSAGE, - number=3, - message='WorkstationCluster', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationClusterRequest(proto.Message): - r"""Request message for UpdateWorkstationCluster. - - Attributes: - workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): - Required. Workstation cluster to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask that specifies which fields in - the workstation cluster should be updated. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - allow_missing (bool): - Optional. If set, and the workstation cluster is not found, - a new workstation cluster will be created. In this - situation, update_mask is ignored. - """ - - workstation_cluster: 'WorkstationCluster' = proto.Field( - proto.MESSAGE, - number=1, - message='WorkstationCluster', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationClusterRequest(proto.Message): - r"""Message for deleting a workstation cluster. - - Attributes: - name (str): - Required. Name of the workstation cluster to - delete. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not apply it. - etag (str): - Optional. If set, the request will be - rejected if the latest version of the - workstation cluster on the server does not have - this ETag. - force (bool): - Optional. If set, any workstation - configurations and workstations in the - workstation cluster are also deleted. Otherwise, - the request only works if the workstation - cluster has no configurations or workstations. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - force: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetWorkstationConfigRequest(proto.Message): - r"""Request message for GetWorkstationConfig. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationConfigsRequest(proto.Message): - r"""Request message for ListWorkstationConfigs. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListWorkstationConfigsResponse(proto.Message): - r"""Response message for ListWorkstationConfigs. - - Attributes: - workstation_configs (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig]): - The requested configs. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationConfigsRequest(proto.Message): - r"""Request message for ListUsableWorkstationConfigs. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListUsableWorkstationConfigsResponse(proto.Message): - r"""Response message for ListUsableWorkstationConfigs. - - Attributes: - workstation_configs (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig]): - The requested configs. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationConfigRequest(proto.Message): - r"""Message for creating a CreateWorkstationConfig. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_config_id (str): - Required. ID to use for the workstation - configuration. - workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): - Required. Config to create. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_config_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation_config: 'WorkstationConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='WorkstationConfig', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationConfigRequest(proto.Message): - r"""Request message for UpdateWorkstationConfig. - - Attributes: - workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): - Required. Config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which fields in the - workstation configuration should be updated. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - allow_missing (bool): - Optional. If set and the workstation configuration is not - found, a new workstation configuration will be created. In - this situation, update_mask is ignored. - """ - - workstation_config: 'WorkstationConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationConfigRequest(proto.Message): - r"""Message for deleting a workstation configuration. - - Attributes: - name (str): - Required. Name of the workstation - configuration to delete. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - etag (str): - Optional. If set, the request is rejected if - the latest version of the workstation - configuration on the server does not have this - ETag. - force (bool): - Optional. If set, any workstations in the - workstation configuration are also deleted. - Otherwise, the request works only if the - workstation configuration has no workstations. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - force: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetWorkstationRequest(proto.Message): - r"""Request message for GetWorkstation. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationsRequest(proto.Message): - r"""Request message for ListWorkstations. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListWorkstationsResponse(proto.Message): - r"""Response message for ListWorkstations. - - Attributes: - workstations (MutableSequence[google.cloud.workstations_v1.types.Workstation]): - The requested workstations. - next_page_token (str): - Optional. Token to retrieve the next page of - results, or empty if there are no more results - in the list. - unreachable (MutableSequence[str]): - Optional. Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstations: MutableSequence['Workstation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workstation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationsRequest(proto.Message): - r"""Request message for ListUsableWorkstations. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListUsableWorkstationsResponse(proto.Message): - r"""Response message for ListUsableWorkstations. - - Attributes: - workstations (MutableSequence[google.cloud.workstations_v1.types.Workstation]): - The requested workstations. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstations: MutableSequence['Workstation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workstation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationRequest(proto.Message): - r"""Message for creating a CreateWorkstation. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_id (str): - Required. ID to use for the workstation. - workstation (google.cloud.workstations_v1.types.Workstation): - Required. Workstation to create. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation: 'Workstation' = proto.Field( - proto.MESSAGE, - number=3, - message='Workstation', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationRequest(proto.Message): - r"""Request message for UpdateWorkstation. - - Attributes: - workstation (google.cloud.workstations_v1.types.Workstation): - Required. Workstation to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which fields in the - workstation configuration should be updated. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - allow_missing (bool): - Optional. If set and the workstation configuration is not - found, a new workstation configuration is created. In this - situation, update_mask is ignored. - """ - - workstation: 'Workstation' = proto.Field( - proto.MESSAGE, - number=1, - message='Workstation', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationRequest(proto.Message): - r"""Request message for DeleteWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to delete. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - etag (str): - Optional. If set, the request will be - rejected if the latest version of the - workstation on the server does not have this - ETag. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - - -class StartWorkstationRequest(proto.Message): - r"""Request message for StartWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to start. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - etag (str): - Optional. If set, the request will be - rejected if the latest version of the - workstation on the server does not have this - ETag. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - - -class StopWorkstationRequest(proto.Message): - r"""Request message for StopWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to stop. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - etag (str): - Optional. If set, the request will be - rejected if the latest version of the - workstation on the server does not have this - ETag. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GenerateAccessTokenRequest(proto.Message): - r"""Request message for GenerateAccessToken. - - 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: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Desired expiration time of the access token. - This value must be at most 24 hours in the - future. If a value is not specified, the token's - expiration time will be set to a default value - of 1 hour in the future. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Desired lifetime duration of the access - token. This value must be at most 24 hours. If a - value is not specified, the token's lifetime - will be set to a default value of 1 hour. - - This field is a member of `oneof`_ ``expiration``. - workstation (str): - Required. Name of the workstation for which - the access token should be generated. - """ - - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - oneof='expiration', - message=duration_pb2.Duration, - ) - workstation: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateAccessTokenResponse(proto.Message): - r"""Response message for GenerateAccessToken. - - Attributes: - access_token (str): - The generated bearer access token. To use this token, - include it in an Authorization header of an HTTP request - sent to the associated workstation's hostname—for example, - ``Authorization: Bearer ``. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the generated token will - expire. - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class OperationMetadata(proto.Message): - r"""Metadata for long-running operations. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time that the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time that the operation finished - running. - target (str): - Output only. Server-defined resource path for - the target of the operation. - verb (str): - Output only. Name of the verb executed by the - operation. - status_message (str): - Output only. Human-readable status of the - operation, if any. - requested_cancellation (bool): - Output only. Identifies whether the user has - requested cancellation of the operation. - api_version (str): - Output only. API version used to start the - operation. - """ - - create_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, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workstations/v1/mypy.ini b/owl-bot-staging/google-cloud-workstations/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workstations/v1/noxfile.py b/owl-bot-staging/google-cloud-workstations/v1/noxfile.py deleted file mode 100644 index b98447b026a8..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations' - -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/cloud/workstations_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/cloud/workstations_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-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json deleted file mode 100644 index 8dabda2a933a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json +++ /dev/null @@ -1,3307 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.workstations.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-workstations", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1.types.WorkstationCluster" - }, - { - "name": "workstation_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation_cluster" - }, - "description": "Sample for CreateWorkstationCluster", - "file": "workstations_v1_generated_workstations_create_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationCluster_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_create_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1.types.WorkstationCluster" - }, - { - "name": "workstation_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation_cluster" - }, - "description": "Sample for CreateWorkstationCluster", - "file": "workstations_v1_generated_workstations_create_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationCluster_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_create_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1.types.WorkstationConfig" - }, - { - "name": "workstation_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation_config" - }, - "description": "Sample for CreateWorkstationConfig", - "file": "workstations_v1_generated_workstations_create_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationConfig_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_create_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1.types.WorkstationConfig" - }, - { - "name": "workstation_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation_config" - }, - "description": "Sample for CreateWorkstationConfig", - "file": "workstations_v1_generated_workstations_create_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationConfig_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_create_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1.types.Workstation" - }, - { - "name": "workstation_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation" - }, - "description": "Sample for CreateWorkstation", - "file": "workstations_v1_generated_workstations_create_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstation_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_create_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1.types.Workstation" - }, - { - "name": "workstation_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation" - }, - "description": "Sample for CreateWorkstation", - "file": "workstations_v1_generated_workstations_create_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstation_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_create_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_workstation_cluster" - }, - "description": "Sample for DeleteWorkstationCluster", - "file": "workstations_v1_generated_workstations_delete_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationCluster_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_delete_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_workstation_cluster" - }, - "description": "Sample for DeleteWorkstationCluster", - "file": "workstations_v1_generated_workstations_delete_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_delete_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_workstation_config" - }, - "description": "Sample for DeleteWorkstationConfig", - "file": "workstations_v1_generated_workstations_delete_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationConfig_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_delete_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_workstation_config" - }, - "description": "Sample for DeleteWorkstationConfig", - "file": "workstations_v1_generated_workstations_delete_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_delete_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_workstation" - }, - "description": "Sample for DeleteWorkstation", - "file": "workstations_v1_generated_workstations_delete_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstation_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_delete_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_workstation" - }, - "description": "Sample for DeleteWorkstation", - "file": "workstations_v1_generated_workstations_delete_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstation_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_delete_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.generate_access_token", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GenerateAccessToken", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GenerateAccessTokenRequest" - }, - { - "name": "workstation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "workstations_v1_generated_workstations_generate_access_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GenerateAccessToken_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": "workstations_v1_generated_workstations_generate_access_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.generate_access_token", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GenerateAccessToken", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GenerateAccessTokenRequest" - }, - { - "name": "workstation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "workstations_v1_generated_workstations_generate_access_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GenerateAccessToken_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": "workstations_v1_generated_workstations_generate_access_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.WorkstationCluster", - "shortName": "get_workstation_cluster" - }, - "description": "Sample for GetWorkstationCluster", - "file": "workstations_v1_generated_workstations_get_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstationCluster_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": "workstations_v1_generated_workstations_get_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.WorkstationCluster", - "shortName": "get_workstation_cluster" - }, - "description": "Sample for GetWorkstationCluster", - "file": "workstations_v1_generated_workstations_get_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstationCluster_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": "workstations_v1_generated_workstations_get_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.WorkstationConfig", - "shortName": "get_workstation_config" - }, - "description": "Sample for GetWorkstationConfig", - "file": "workstations_v1_generated_workstations_get_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstationConfig_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": "workstations_v1_generated_workstations_get_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.WorkstationConfig", - "shortName": "get_workstation_config" - }, - "description": "Sample for GetWorkstationConfig", - "file": "workstations_v1_generated_workstations_get_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstationConfig_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": "workstations_v1_generated_workstations_get_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.Workstation", - "shortName": "get_workstation" - }, - "description": "Sample for GetWorkstation", - "file": "workstations_v1_generated_workstations_get_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstation_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": "workstations_v1_generated_workstations_get_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.Workstation", - "shortName": "get_workstation" - }, - "description": "Sample for GetWorkstation", - "file": "workstations_v1_generated_workstations_get_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstation_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": "workstations_v1_generated_workstations_get_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_usable_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager", - "shortName": "list_usable_workstation_configs" - }, - "description": "Sample for ListUsableWorkstationConfigs", - "file": "workstations_v1_generated_workstations_list_usable_workstation_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1_generated_workstations_list_usable_workstation_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_usable_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsPager", - "shortName": "list_usable_workstation_configs" - }, - "description": "Sample for ListUsableWorkstationConfigs", - "file": "workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_usable_workstations", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListUsableWorkstationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationsAsyncPager", - "shortName": "list_usable_workstations" - }, - "description": "Sample for ListUsableWorkstations", - "file": "workstations_v1_generated_workstations_list_usable_workstations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstations_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": "workstations_v1_generated_workstations_list_usable_workstations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_usable_workstations", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListUsableWorkstationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListUsableWorkstationsPager", - "shortName": "list_usable_workstations" - }, - "description": "Sample for ListUsableWorkstations", - "file": "workstations_v1_generated_workstations_list_usable_workstations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstations_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": "workstations_v1_generated_workstations_list_usable_workstations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstation_clusters", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationClusters", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationClustersAsyncPager", - "shortName": "list_workstation_clusters" - }, - "description": "Sample for ListWorkstationClusters", - "file": "workstations_v1_generated_workstations_list_workstation_clusters_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstationClusters_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": "workstations_v1_generated_workstations_list_workstation_clusters_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstation_clusters", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationClusters", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationClustersPager", - "shortName": "list_workstation_clusters" - }, - "description": "Sample for ListWorkstationClusters", - "file": "workstations_v1_generated_workstations_list_workstation_clusters_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstationClusters_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": "workstations_v1_generated_workstations_list_workstation_clusters_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationConfigsAsyncPager", - "shortName": "list_workstation_configs" - }, - "description": "Sample for ListWorkstationConfigs", - "file": "workstations_v1_generated_workstations_list_workstation_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1_generated_workstations_list_workstation_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationConfigsPager", - "shortName": "list_workstation_configs" - }, - "description": "Sample for ListWorkstationConfigs", - "file": "workstations_v1_generated_workstations_list_workstation_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1_generated_workstations_list_workstation_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstations", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationsAsyncPager", - "shortName": "list_workstations" - }, - "description": "Sample for ListWorkstations", - "file": "workstations_v1_generated_workstations_list_workstations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstations_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": "workstations_v1_generated_workstations_list_workstations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstations", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.services.workstations.pagers.ListWorkstationsPager", - "shortName": "list_workstations" - }, - "description": "Sample for ListWorkstations", - "file": "workstations_v1_generated_workstations_list_workstations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstations_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": "workstations_v1_generated_workstations_list_workstations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.start_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.StartWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "StartWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.StartWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "start_workstation" - }, - "description": "Sample for StartWorkstation", - "file": "workstations_v1_generated_workstations_start_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_StartWorkstation_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_start_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.start_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.StartWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "StartWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.StartWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "start_workstation" - }, - "description": "Sample for StartWorkstation", - "file": "workstations_v1_generated_workstations_start_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_StartWorkstation_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_start_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.stop_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.StopWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "StopWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.StopWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "stop_workstation" - }, - "description": "Sample for StopWorkstation", - "file": "workstations_v1_generated_workstations_stop_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_StopWorkstation_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_stop_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.stop_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.StopWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "StopWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.StopWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "stop_workstation" - }, - "description": "Sample for StopWorkstation", - "file": "workstations_v1_generated_workstations_stop_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_StopWorkstation_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_stop_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1.types.WorkstationCluster" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_workstation_cluster" - }, - "description": "Sample for UpdateWorkstationCluster", - "file": "workstations_v1_generated_workstations_update_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationCluster_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_update_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1.types.WorkstationCluster" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_workstation_cluster" - }, - "description": "Sample for UpdateWorkstationCluster", - "file": "workstations_v1_generated_workstations_update_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_update_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1.types.WorkstationConfig" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_workstation_config" - }, - "description": "Sample for UpdateWorkstationConfig", - "file": "workstations_v1_generated_workstations_update_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationConfig_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_update_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1.types.WorkstationConfig" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_workstation_config" - }, - "description": "Sample for UpdateWorkstationConfig", - "file": "workstations_v1_generated_workstations_update_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_update_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationRequest" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1.types.Workstation" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_workstation" - }, - "description": "Sample for UpdateWorkstation", - "file": "workstations_v1_generated_workstations_update_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstation_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_update_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationRequest" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1.types.Workstation" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_workstation" - }, - "description": "Sample for UpdateWorkstation", - "file": "workstations_v1_generated_workstations_update_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstation_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1_generated_workstations_update_workstation_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py deleted file mode 100644 index da9caa9dfb44..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_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 CreateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_create_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py deleted file mode 100644 index 25e77620a6d7..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_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 CreateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py deleted file mode 100644 index fa95cde5c45b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_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 CreateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py deleted file mode 100644 index 3388a7112edb..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_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 CreateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_create_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py deleted file mode 100644 index 944fdc87ea43..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_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 CreateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_create_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py deleted file mode 100644 index 514350dc4abd..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_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 CreateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_create_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py deleted file mode 100644 index 82e6981832ab..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_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 DeleteWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_delete_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py deleted file mode 100644 index 1071be9b0c41..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_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 DeleteWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py deleted file mode 100644 index 88853e5cb549..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_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 DeleteWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py deleted file mode 100644 index c5bed5490628..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_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 DeleteWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_delete_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py deleted file mode 100644 index 9b02260244de..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_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 DeleteWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_delete_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py deleted file mode 100644 index 26261d76f5dc..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_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 DeleteWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_delete_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py deleted file mode 100644 index 32a3d6878667..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_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 GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GenerateAccessToken_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_generate_access_token(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GenerateAccessToken_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py deleted file mode 100644 index 43530eef1bcb..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_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 GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GenerateAccessToken_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_generate_access_token(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GenerateAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py deleted file mode 100644 index 38d2ce054fa8..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_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 GetWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_get_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py deleted file mode 100644 index f82d2afc6418..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_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 GetWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py deleted file mode 100644 index 941ca6de929f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_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 GetWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py deleted file mode 100644 index 6b8c4cf6d4cc..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_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 GetWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_get_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_config(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py deleted file mode 100644 index 6adba3ae5d6a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_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 GetWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_get_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_config(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py deleted file mode 100644 index a2585a4cabaf..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_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 GetWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_get_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py deleted file mode 100644 index 13af6452678f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_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 ListUsableWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py deleted file mode 100644 index 6d41579a13e7..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_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 ListUsableWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py deleted file mode 100644 index b14a660ef62a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_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 ListUsableWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListUsableWorkstations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_usable_workstations(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListUsableWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py deleted file mode 100644 index 4c3f026ce7ab..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_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 ListUsableWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListUsableWorkstations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_usable_workstations(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListUsableWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py deleted file mode 100644 index 1807120300e5..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_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 ListWorkstationClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstationClusters_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstationClusters_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py deleted file mode 100644 index 6ccf5d82795d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_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 ListWorkstationClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstationClusters_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstationClusters_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py deleted file mode 100644 index 771317f07927..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_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 ListWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py deleted file mode 100644 index d1c5922918ed..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_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 ListWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py deleted file mode 100644 index 6f55b87c0f16..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_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 ListWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_workstations(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py deleted file mode 100644 index 150093503948..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_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 ListWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_workstations(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py deleted file mode 100644 index 6d6ceafebe49..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_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 StartWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_StartWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_start_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_StartWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py deleted file mode 100644 index 9f206e166057..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_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 StartWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_StartWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_start_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_StartWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py deleted file mode 100644 index 03a3c895665b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_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 StopWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_StopWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_stop_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_StopWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py deleted file mode 100644 index a584d0e232d8..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_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 StopWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_StopWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_stop_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_StopWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py deleted file mode 100644 index 04d0e9a0d277..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_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 UpdateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_update_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py deleted file mode 100644 index 337918ad3af6..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_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 UpdateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py deleted file mode 100644 index 9442c1046878..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_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 UpdateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py deleted file mode 100644 index 051ed5dadf59..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_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 UpdateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_update_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py deleted file mode 100644 index 599181d6399b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_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 UpdateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_update_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py deleted file mode 100644 index 906d0acb553a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_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 UpdateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_update_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py b/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py deleted file mode 100644 index d5f36b76dcbd..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py +++ /dev/null @@ -1,195 +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 workstationsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_workstation': ('parent', 'workstation_id', 'workstation', 'validate_only', ), - 'create_workstation_cluster': ('parent', 'workstation_cluster_id', 'workstation_cluster', 'validate_only', ), - 'create_workstation_config': ('parent', 'workstation_config_id', 'workstation_config', 'validate_only', ), - 'delete_workstation': ('name', 'validate_only', 'etag', ), - 'delete_workstation_cluster': ('name', 'validate_only', 'etag', 'force', ), - 'delete_workstation_config': ('name', 'validate_only', 'etag', 'force', ), - 'generate_access_token': ('workstation', 'expire_time', 'ttl', ), - 'get_workstation': ('name', ), - 'get_workstation_cluster': ('name', ), - 'get_workstation_config': ('name', ), - 'list_usable_workstation_configs': ('parent', 'page_size', 'page_token', ), - 'list_usable_workstations': ('parent', 'page_size', 'page_token', ), - 'list_workstation_clusters': ('parent', 'page_size', 'page_token', ), - 'list_workstation_configs': ('parent', 'page_size', 'page_token', ), - 'list_workstations': ('parent', 'page_size', 'page_token', ), - 'start_workstation': ('name', 'validate_only', 'etag', ), - 'stop_workstation': ('name', 'validate_only', 'etag', ), - 'update_workstation': ('workstation', 'update_mask', 'validate_only', 'allow_missing', ), - 'update_workstation_cluster': ('workstation_cluster', 'update_mask', 'validate_only', 'allow_missing', ), - 'update_workstation_config': ('workstation_config', 'update_mask', 'validate_only', 'allow_missing', ), - } - - 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=workstationsCallTransformer(), -): - """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 workstations 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-cloud-workstations/v1/setup.py b/owl-bot-staging/google-cloud-workstations/v1/setup.py deleted file mode 100644 index 6106efcf5486..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations' - - -description = "Google Cloud Workstations API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/workstations/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", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations" - -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-cloud-workstations/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_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-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py deleted file mode 100644 index cdc2049a589c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py +++ /dev/null @@ -1,17992 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.location import locations_pb2 -from google.cloud.workstations_v1.services.workstations import WorkstationsAsyncClient -from google.cloud.workstations_v1.services.workstations import WorkstationsClient -from google.cloud.workstations_v1.services.workstations import pagers -from google.cloud.workstations_v1.services.workstations import transports -from google.cloud.workstations_v1.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import google.auth - - -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 WorkstationsClient._get_default_mtls_endpoint(None) is None - assert WorkstationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert WorkstationsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert WorkstationsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert WorkstationsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - WorkstationsClient._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 WorkstationsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert WorkstationsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert WorkstationsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - WorkstationsClient._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 WorkstationsClient._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 WorkstationsClient._get_client_cert_source(None, False) is None - assert WorkstationsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert WorkstationsClient._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 WorkstationsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert WorkstationsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = WorkstationsClient._DEFAULT_UNIVERSE - default_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert WorkstationsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert WorkstationsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT - assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "always") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT - assert WorkstationsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT - assert WorkstationsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - WorkstationsClient._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 WorkstationsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert WorkstationsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert WorkstationsClient._get_universe_domain(None, None) == WorkstationsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - WorkstationsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (WorkstationsClient, "grpc"), - (WorkstationsAsyncClient, "grpc_asyncio"), - (WorkstationsClient, "rest"), -]) -def test_workstations_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 == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workstations.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WorkstationsGrpcTransport, "grpc"), - (transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.WorkstationsRestTransport, "rest"), -]) -def test_workstations_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", [ - (WorkstationsClient, "grpc"), - (WorkstationsAsyncClient, "grpc_asyncio"), - (WorkstationsClient, "rest"), -]) -def test_workstations_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 == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workstations.googleapis.com' - ) - - -def test_workstations_client_get_transport_class(): - transport = WorkstationsClient.get_transport_class() - available_transports = [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsRestTransport, - ] - assert transport in available_transports - - transport = WorkstationsClient.get_transport_class("grpc") - assert transport == transports.WorkstationsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) -def test_workstations_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(WorkstationsClient, '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(WorkstationsClient, '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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "true"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "false"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "true"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "false"), -]) -@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_workstations_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", [ - WorkstationsClient, WorkstationsAsyncClient -]) -@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) -def test_workstations_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", [ - WorkstationsClient, WorkstationsAsyncClient -]) -@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) -def test_workstations_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = WorkstationsClient._DEFAULT_UNIVERSE - default_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WorkstationsClient._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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -def test_workstations_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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", None), -]) -def test_workstations_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_workstations_client_client_options_from_dict(): - with mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WorkstationsClient( - 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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_workstations_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( - "workstations.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="workstations.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationClusterRequest, - dict, -]) -def test_get_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - ) - response = client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -def test_get_workstation_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.GetWorkstationClusterRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_workstation_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationClusterRequest( - name='name_value', - ) - -def test_get_workstation_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation_cluster] = mock_rpc - request = {} - client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods - - # 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_workstation_cluster] = mock_rpc - - request = {} - await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - )) - response = await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -@pytest.mark.asyncio -async def test_get_workstation_cluster_async_from_dict(): - await test_get_workstation_cluster_async(request_type=dict) - -def test_get_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = workstations.WorkstationCluster() - client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) - await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation_cluster( - 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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation_cluster( - 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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationClustersRequest, - dict, -]) -def test_list_workstation_clusters(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_clusters_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListWorkstationClustersRequest( - 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_workstation_clusters), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workstation_clusters(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationClustersRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_workstation_clusters_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_clusters] = mock_rpc - request = {} - client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstation_clusters(request) - - # Establish that a new wrapper 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_workstation_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_clusters in client._client._transport._wrapped_methods - - # 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_workstation_clusters] = mock_rpc - - request = {} - await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workstation_clusters(request) - - # Establish that a new wrapper 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_workstation_clusters_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationClustersRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async_from_dict(): - await test_list_workstation_clusters_async(request_type=dict) - -def test_list_workstation_clusters_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = workstations.ListWorkstationClustersResponse() - client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_clusters_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) - await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_clusters_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstation_clusters( - 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_workstation_clusters_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstation_clusters_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstation_clusters( - 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_workstation_clusters_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - - -def test_list_workstation_clusters_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstation_clusters(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, workstations.WorkstationCluster) - for i in results) -def test_list_workstation_clusters_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstation_clusters(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_workstation_clusters_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstation_clusters(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, workstations.WorkstationCluster) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - 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_workstation_clusters(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", [ - workstations.CreateWorkstationClusterRequest, - dict, -]) -def test_create_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.CreateWorkstationClusterRequest( - parent='parent_value', - workstation_cluster_id='workstation_cluster_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_workstation_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationClusterRequest( - parent='parent_value', - workstation_cluster_id='workstation_cluster_id_value', - ) - -def test_create_workstation_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - request = {} - client.create_workstation_cluster(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.create_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods - - # 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_workstation_cluster] = mock_rpc - - request = {} - await client.create_workstation_cluster(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.create_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationClusterRequest() - 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_create_workstation_cluster_async_from_dict(): - await test_create_workstation_cluster_async(request_type=dict) - -def test_create_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_workstation_cluster( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_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].workstation_cluster - mock_val = workstations.WorkstationCluster(name='name_value') - assert arg == mock_val - arg = args[0].workstation_cluster_id - mock_val = 'workstation_cluster_id_value' - assert arg == mock_val - - -def test_create_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_workstation_cluster( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_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].workstation_cluster - mock_val = workstations.WorkstationCluster(name='name_value') - assert arg == mock_val - arg = args[0].workstation_cluster_id - mock_val = 'workstation_cluster_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationClusterRequest, - dict, -]) -def test_update_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.UpdateWorkstationClusterRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_workstation_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationClusterRequest( - ) - -def test_update_workstation_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - request = {} - client.update_workstation_cluster(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.update_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods - - # 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_workstation_cluster] = mock_rpc - - request = {} - await client.update_workstation_cluster(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.update_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationClusterRequest() - 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_update_workstation_cluster_async_from_dict(): - await test_update_workstation_cluster_async(request_type=dict) - -def test_update_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationClusterRequest() - - request.workstation_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_cluster.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationClusterRequest() - - request.workstation_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_cluster.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_workstation_cluster( - workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster - mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_workstation_cluster( - workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster - mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationClusterRequest, - dict, -]) -def test_delete_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.DeleteWorkstationClusterRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_workstation_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationClusterRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_workstation_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - request = {} - client.delete_workstation_cluster(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.delete_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods - - # 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_workstation_cluster] = mock_rpc - - request = {} - await client.delete_workstation_cluster(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.delete_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationClusterRequest() - 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_delete_workstation_cluster_async_from_dict(): - await test_delete_workstation_cluster_async(request_type=dict) - -def test_delete_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_workstation_cluster( - 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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_workstation_cluster( - 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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationConfigRequest, - dict, -]) -def test_get_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - replica_zones=['replica_zones_value'], - degraded=True, - ) - response = client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.replica_zones == ['replica_zones_value'] - assert response.degraded is True - - -def test_get_workstation_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.GetWorkstationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_workstation_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationConfigRequest( - name='name_value', - ) - -def test_get_workstation_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation_config] = mock_rpc - request = {} - client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_config in client._client._transport._wrapped_methods - - # 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_workstation_config] = mock_rpc - - request = {} - await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - replica_zones=['replica_zones_value'], - degraded=True, - )) - response = await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.replica_zones == ['replica_zones_value'] - assert response.degraded is True - - -@pytest.mark.asyncio -async def test_get_workstation_config_async_from_dict(): - await test_get_workstation_config_async(request_type=dict) - -def test_get_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = workstations.WorkstationConfig() - client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) - await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation_config( - 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_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation_config( - 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_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationConfigsRequest, - dict, -]) -def test_list_workstation_configs(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_configs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListWorkstationConfigsRequest( - 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_workstation_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workstation_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_workstation_configs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_configs] = mock_rpc - request = {} - client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstation_configs(request) - - # Establish that a new wrapper 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_workstation_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_configs in client._client._transport._wrapped_methods - - # 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_workstation_configs] = mock_rpc - - request = {} - await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workstation_configs(request) - - # Establish that a new wrapper 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_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationConfigsRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstation_configs_async_from_dict(): - await test_list_workstation_configs_async(request_type=dict) - -def test_list_workstation_configs_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListWorkstationConfigsResponse() - client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_configs_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) - await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_configs_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstation_configs( - 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_workstation_configs_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstation_configs_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstation_configs( - 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_workstation_configs_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_workstation_configs_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstation_configs(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, workstations.WorkstationConfig) - for i in results) -def test_list_workstation_configs_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstation_configs(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_workstation_configs_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstation_configs(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, workstations.WorkstationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstation_configs_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - 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_workstation_configs(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", [ - workstations.ListUsableWorkstationConfigsRequest, - dict, -]) -def test_list_usable_workstation_configs(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListUsableWorkstationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstation_configs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListUsableWorkstationConfigsRequest( - 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_usable_workstation_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_usable_workstation_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_usable_workstation_configs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_usable_workstation_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_usable_workstation_configs] = mock_rpc - request = {} - client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_usable_workstation_configs(request) - - # Establish that a new wrapper 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_usable_workstation_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_usable_workstation_configs in client._client._transport._wrapped_methods - - # 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_usable_workstation_configs] = mock_rpc - - request = {} - await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_usable_workstation_configs(request) - - # Establish that a new wrapper 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_usable_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationConfigsRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListUsableWorkstationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async_from_dict(): - await test_list_usable_workstation_configs_async(request_type=dict) - -def test_list_usable_workstation_configs_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_usable_workstation_configs_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) - await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_usable_workstation_configs_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_usable_workstation_configs( - 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_usable_workstation_configs_flattened_error(): - client = WorkstationsClient( - credentials=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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_usable_workstation_configs( - 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_usable_workstation_configs_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstation_configs_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_usable_workstation_configs(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, workstations.WorkstationConfig) - for i in results) -def test_list_usable_workstation_configs_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_usable_workstation_configs(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_usable_workstation_configs_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_usable_workstation_configs(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, workstations.WorkstationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - 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_usable_workstation_configs(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", [ - workstations.CreateWorkstationConfigRequest, - dict, -]) -def test_create_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.CreateWorkstationConfigRequest( - parent='parent_value', - workstation_config_id='workstation_config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_workstation_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationConfigRequest( - parent='parent_value', - workstation_config_id='workstation_config_id_value', - ) - -def test_create_workstation_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - request = {} - client.create_workstation_config(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.create_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_config in client._client._transport._wrapped_methods - - # 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_workstation_config] = mock_rpc - - request = {} - await client.create_workstation_config(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.create_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationConfigRequest() - 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_create_workstation_config_async_from_dict(): - await test_create_workstation_config_async(request_type=dict) - -def test_create_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_workstation_config( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_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].workstation_config - mock_val = workstations.WorkstationConfig(name='name_value') - assert arg == mock_val - arg = args[0].workstation_config_id - mock_val = 'workstation_config_id_value' - assert arg == mock_val - - -def test_create_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_workstation_config( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_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].workstation_config - mock_val = workstations.WorkstationConfig(name='name_value') - assert arg == mock_val - arg = args[0].workstation_config_id - mock_val = 'workstation_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationConfigRequest, - dict, -]) -def test_update_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.UpdateWorkstationConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_workstation_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationConfigRequest( - ) - -def test_update_workstation_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - request = {} - client.update_workstation_config(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.update_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_config in client._client._transport._wrapped_methods - - # 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_workstation_config] = mock_rpc - - request = {} - await client.update_workstation_config(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.update_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationConfigRequest() - 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_update_workstation_config_async_from_dict(): - await test_update_workstation_config_async(request_type=dict) - -def test_update_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationConfigRequest() - - request.workstation_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationConfigRequest() - - request.workstation_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_config.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_workstation_config( - workstation_config=workstations.WorkstationConfig(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].workstation_config - mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_workstation_config( - workstation_config=workstations.WorkstationConfig(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].workstation_config - mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationConfigRequest, - dict, -]) -def test_delete_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.DeleteWorkstationConfigRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_workstation_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationConfigRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_workstation_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - request = {} - client.delete_workstation_config(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.delete_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_config in client._client._transport._wrapped_methods - - # 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_workstation_config] = mock_rpc - - request = {} - await client.delete_workstation_config(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.delete_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationConfigRequest() - 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_delete_workstation_config_async_from_dict(): - await test_delete_workstation_config_async(request_type=dict) - -def test_delete_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_workstation_config( - 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_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_workstation_config( - 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_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationRequest, - dict, -]) -def test_get_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - ) - response = client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -def test_get_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.GetWorkstationRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationRequest( - name='name_value', - ) - -def test_get_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation] = mock_rpc - request = {} - client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation(request) - - # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation in client._client._transport._wrapped_methods - - # 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_workstation] = mock_rpc - - request = {} - await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_workstation(request) - - # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - )) - response = await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -@pytest.mark.asyncio -async def test_get_workstation_async_from_dict(): - await test_get_workstation_async(request_type=dict) - -def test_get_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = workstations.Workstation() - client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) - await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation( - 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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation( - 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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationsRequest, - dict, -]) -def test_list_workstations(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstations_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListWorkstationsRequest( - 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_workstations), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workstations(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_workstations_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstations in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstations] = mock_rpc - request = {} - client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstations(request) - - # Establish that a new wrapper 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_workstations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstations in client._client._transport._wrapped_methods - - # 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_workstations] = mock_rpc - - request = {} - await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workstations(request) - - # Establish that a new wrapper 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_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationsRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstations_async_from_dict(): - await test_list_workstations_async(request_type=dict) - -def test_list_workstations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = workstations.ListWorkstationsResponse() - client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) - await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstations_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstations( - 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_workstations_flattened_error(): - client = WorkstationsClient( - credentials=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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstations_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstations( - 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_workstations_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_workstations_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstations(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, workstations.Workstation) - for i in results) -def test_list_workstations_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstations(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_workstations_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstations(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, workstations.Workstation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstations_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - 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_workstations(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", [ - workstations.ListUsableWorkstationsRequest, - dict, -]) -def test_list_usable_workstations(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListUsableWorkstationsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstations_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListUsableWorkstationsRequest( - 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_usable_workstations), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_usable_workstations(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_usable_workstations_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_usable_workstations in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_usable_workstations] = mock_rpc - request = {} - client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_usable_workstations(request) - - # Establish that a new wrapper 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_usable_workstations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_usable_workstations in client._client._transport._wrapped_methods - - # 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_usable_workstations] = mock_rpc - - request = {} - await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_usable_workstations(request) - - # Establish that a new wrapper 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_usable_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationsRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListUsableWorkstationsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_usable_workstations_async_from_dict(): - await test_list_usable_workstations_async(request_type=dict) - -def test_list_usable_workstations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationsResponse() - client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_usable_workstations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) - await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_usable_workstations_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_usable_workstations( - 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_usable_workstations_flattened_error(): - client = WorkstationsClient( - credentials=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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_usable_workstations_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_usable_workstations( - 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_usable_workstations_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstations_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_usable_workstations(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, workstations.Workstation) - for i in results) -def test_list_usable_workstations_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_usable_workstations(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_usable_workstations_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_usable_workstations(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, workstations.Workstation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_usable_workstations_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - 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_usable_workstations(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", [ - workstations.CreateWorkstationRequest, - dict, -]) -def test_create_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.CreateWorkstationRequest( - parent='parent_value', - workstation_id='workstation_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationRequest( - parent='parent_value', - workstation_id='workstation_id_value', - ) - -def test_create_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - request = {} - client.create_workstation(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.create_workstation(request) - - # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation in client._client._transport._wrapped_methods - - # 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_workstation] = mock_rpc - - request = {} - await client.create_workstation(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.create_workstation(request) - - # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationRequest() - 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_create_workstation_async_from_dict(): - await test_create_workstation_async(request_type=dict) - -def test_create_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_workstation( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_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].workstation - mock_val = workstations.Workstation(name='name_value') - assert arg == mock_val - arg = args[0].workstation_id - mock_val = 'workstation_id_value' - assert arg == mock_val - - -def test_create_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_workstation( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_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].workstation - mock_val = workstations.Workstation(name='name_value') - assert arg == mock_val - arg = args[0].workstation_id - mock_val = 'workstation_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationRequest, - dict, -]) -def test_update_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.UpdateWorkstationRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationRequest( - ) - -def test_update_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - request = {} - client.update_workstation(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.update_workstation(request) - - # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation in client._client._transport._wrapped_methods - - # 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_workstation] = mock_rpc - - request = {} - await client.update_workstation(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.update_workstation(request) - - # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationRequest() - 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_update_workstation_async_from_dict(): - await test_update_workstation_async(request_type=dict) - -def test_update_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationRequest() - - request.workstation.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationRequest() - - request.workstation.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_workstation( - workstation=workstations.Workstation(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].workstation - mock_val = workstations.Workstation(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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_workstation( - workstation=workstations.Workstation(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].workstation - mock_val = workstations.Workstation(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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationRequest, - dict, -]) -def test_delete_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.DeleteWorkstationRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - request = {} - client.delete_workstation(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.delete_workstation(request) - - # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation in client._client._transport._wrapped_methods - - # 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_workstation] = mock_rpc - - request = {} - await client.delete_workstation(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.delete_workstation(request) - - # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationRequest() - 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_delete_workstation_async_from_dict(): - await test_delete_workstation_async(request_type=dict) - -def test_delete_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_workstation( - 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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_workstation( - 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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StartWorkstationRequest, - dict, -]) -def test_start_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.StartWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_start_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.StartWorkstationRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.start_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StartWorkstationRequest( - name='name_value', - etag='etag_value', - ) - -def test_start_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_workstation] = mock_rpc - request = {} - client.start_workstation(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.start_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.start_workstation in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.start_workstation] = mock_rpc - - request = {} - await client.start_workstation(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.start_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StartWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.StartWorkstationRequest() - 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_start_workstation_async_from_dict(): - await test_start_workstation_async(request_type=dict) - -def test_start_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StartWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StartWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.start_workstation( - 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_start_workstation_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_start_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.start_workstation( - 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_start_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StopWorkstationRequest, - dict, -]) -def test_stop_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.StopWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_stop_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.StopWorkstationRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.stop_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StopWorkstationRequest( - name='name_value', - etag='etag_value', - ) - -def test_stop_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_workstation] = mock_rpc - request = {} - client.stop_workstation(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.stop_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.stop_workstation in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.stop_workstation] = mock_rpc - - request = {} - await client.stop_workstation(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.stop_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StopWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.StopWorkstationRequest() - 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_stop_workstation_async_from_dict(): - await test_stop_workstation_async(request_type=dict) - -def test_stop_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StopWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StopWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.stop_workstation( - 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_stop_workstation_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_stop_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.stop_workstation( - 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_stop_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - ) - response = client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.GenerateAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -def test_generate_access_token_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.GenerateAccessTokenRequest( - workstation='workstation_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_access_token(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GenerateAccessTokenRequest( - workstation='workstation_value', - ) - -def test_generate_access_token_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc - request = {} - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_access_token in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_access_token] = mock_rpc - - request = {} - await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=workstations.GenerateAccessTokenRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - )) - response = await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.GenerateAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.asyncio -async def test_generate_access_token_async_from_dict(): - await test_generate_access_token_async(request_type=dict) - -def test_generate_access_token_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GenerateAccessTokenRequest() - - request.workstation = 'workstation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = workstations.GenerateAccessTokenResponse() - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation=workstation_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_access_token_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GenerateAccessTokenRequest() - - request.workstation = 'workstation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) - await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation=workstation_value', - ) in kw['metadata'] - - -def test_generate_access_token_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_access_token( - workstation='workstation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].workstation - mock_val = 'workstation_value' - assert arg == mock_val - - -def test_generate_access_token_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_access_token( - workstation='workstation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].workstation - mock_val = 'workstation_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - - -def test_get_workstation_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation_cluster] = mock_rpc - - request = {} - client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation_cluster(request) - - # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.GetWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation_cluster._get_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_workstation_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.WorkstationCluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.WorkstationCluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_workstation_cluster(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_get_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - - -def test_list_workstation_clusters_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_clusters] = mock_rpc - - request = {} - client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstation_clusters(request) - - # Establish 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_workstation_clusters_rest_required_fields(request_type=workstations.ListWorkstationClustersRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_clusters._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_workstation_clusters._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListWorkstationClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_workstation_clusters(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstation_clusters_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstation_clusters._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workstation_clusters_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/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 = workstations.ListWorkstationClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_workstation_clusters(**mock_args) - - # Establish that the underlying call 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/*/locations/*}/workstationClusters" % client.transport._host, args[1]) - - -def test_list_workstation_clusters_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - - -def test_list_workstation_clusters_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationClustersResponse.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/locations/sample2'} - - pager = client.list_workstation_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationCluster) - for i in results) - - pages = list(client.list_workstation_clusters(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_workstation_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - - request = {} - client.create_workstation_cluster(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.create_workstation_cluster(request) - - # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.CreateWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_cluster_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 "workstationClusterId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationClusterId" in jsonified_request - assert jsonified_request["workstationClusterId"] == request_init["workstation_cluster_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationClusterId"] = 'workstation_cluster_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only", "workstation_cluster_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 "workstationClusterId" in jsonified_request - assert jsonified_request["workstationClusterId"] == 'workstation_cluster_id_value' - - client = WorkstationsClient( - 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 - - response = client.create_workstation_cluster(request) - - expected_params = [ - ( - "workstationClusterId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationClusterId", )) & set(("parent", "workstationClusterId", "workstationCluster", ))) - - -def test_create_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation_cluster(**mock_args) - - # Establish that the underlying call 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/*/locations/*}/workstationClusters" % client.transport._host, args[1]) - - -def test_create_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - -def test_update_workstation_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - - request = {} - client.update_workstation_cluster(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.update_workstation_cluster(request) - - # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.UpdateWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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': "patch", - '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 - - response = client.update_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationCluster", "updateMask", ))) - - -def test_update_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation_cluster=workstations.WorkstationCluster(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_workstation_cluster(**mock_args) - - # Establish that the underlying call 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/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_update_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_workstation_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - - request = {} - client.delete_workstation_cluster(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.delete_workstation_cluster(request) - - # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.DeleteWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation_cluster._get_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_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "force", "validate_only", )) - jsonified_request.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 = WorkstationsClient( - 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': "delete", - '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 - - response = client.delete_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) - - -def test_delete_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation_cluster(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - - -def test_get_workstation_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation_config] = mock_rpc - - request = {} - client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation_config(request) - - # Establish 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_workstation_config_rest_required_fields(request_type=workstations.GetWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation_config._get_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_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.WorkstationConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # 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 = workstations.WorkstationConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_workstation_config(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - - -def test_list_workstation_configs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_configs] = mock_rpc - - request = {} - client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstation_configs(request) - - # Establish 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_workstation_configs_rest_required_fields(request_type=workstations.ListWorkstationConfigsRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_configs._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_workstation_configs._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_workstation_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstation_configs_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstation_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workstation_configs_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # 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 = workstations.ListWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_workstation_configs(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) - - -def test_list_workstation_configs_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_workstation_configs_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationConfigsResponse.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/locations/sample2/workstationClusters/sample3'} - - pager = client.list_workstation_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) - - pages = list(client.list_workstation_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_usable_workstation_configs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_usable_workstation_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_usable_workstation_configs] = mock_rpc - - request = {} - client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_usable_workstation_configs(request) - - # Establish 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_usable_workstation_configs_rest_required_fields(request_type=workstations.ListUsableWorkstationConfigsRequest): - transport_class = transports.WorkstationsRestTransport - - 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_usable_workstation_configs._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_usable_workstation_configs._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_usable_workstation_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_usable_workstation_configs_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_usable_workstation_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_usable_workstation_configs_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # 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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_usable_workstation_configs(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable" % client.transport._host, args[1]) - - -def test_list_usable_workstation_configs_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstation_configs_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListUsableWorkstationConfigsResponse.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/locations/sample2/workstationClusters/sample3'} - - pager = client.list_usable_workstation_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) - - pages = list(client.list_usable_workstation_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_workstation_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - - request = {} - client.create_workstation_config(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.create_workstation_config(request) - - # Establish 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_workstation_config_rest_required_fields(request_type=workstations.CreateWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_config_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 "workstationConfigId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationConfigId" in jsonified_request - assert jsonified_request["workstationConfigId"] == request_init["workstation_config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationConfigId"] = 'workstation_config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only", "workstation_config_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 "workstationConfigId" in jsonified_request - assert jsonified_request["workstationConfigId"] == 'workstation_config_id_value' - - client = WorkstationsClient( - 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 - - response = client.create_workstation_config(request) - - expected_params = [ - ( - "workstationConfigId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationConfigId", )) & set(("parent", "workstationConfigId", "workstationConfig", ))) - - -def test_create_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation_config(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) - - -def test_create_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - -def test_update_workstation_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - - request = {} - client.update_workstation_config(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.update_workstation_config(request) - - # Establish 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_workstation_config_rest_required_fields(request_type=workstations.UpdateWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_config._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_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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': "patch", - '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 - - response = client.update_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationConfig", "updateMask", ))) - - -def test_update_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation_config=workstations.WorkstationConfig(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_workstation_config(**mock_args) - - # Establish that the underlying call 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/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_workstation_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - - request = {} - client.delete_workstation_config(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.delete_workstation_config(request) - - # Establish 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_workstation_config_rest_required_fields(request_type=workstations.DeleteWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation_config._get_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_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "force", "validate_only", )) - jsonified_request.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 = WorkstationsClient( - 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': "delete", - '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 - - response = client.delete_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) - - -def test_delete_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # 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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation_config(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - - -def test_get_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation] = mock_rpc - - request = {} - client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation(request) - - # Establish 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_workstation_rest_required_fields(request_type=workstations.GetWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation._get_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_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.Workstation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # 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 = workstations.Workstation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_workstation(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_get_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - - -def test_list_workstations_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstations in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstations] = mock_rpc - - request = {} - client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstations(request) - - # Establish 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_workstations_rest_required_fields(request_type=workstations.ListWorkstationsRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstations._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_workstations._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_workstations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstations_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workstations_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # 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 = workstations.ListWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_workstations(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) - - -def test_list_workstations_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_workstations_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationsResponse.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/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - pager = client.list_workstations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) - - pages = list(client.list_workstations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_usable_workstations_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_usable_workstations in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_usable_workstations] = mock_rpc - - request = {} - client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_usable_workstations(request) - - # Establish 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_usable_workstations_rest_required_fields(request_type=workstations.ListUsableWorkstationsRequest): - transport_class = transports.WorkstationsRestTransport - - 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_usable_workstations._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_usable_workstations._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListUsableWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_usable_workstations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_usable_workstations_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_usable_workstations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_usable_workstations_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # 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 = workstations.ListUsableWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_usable_workstations(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable" % client.transport._host, args[1]) - - -def test_list_usable_workstations_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstations_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListUsableWorkstationsResponse.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/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - pager = client.list_usable_workstations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) - - pages = list(client.list_usable_workstations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - - request = {} - client.create_workstation(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.create_workstation(request) - - # Establish 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_workstation_rest_required_fields(request_type=workstations.CreateWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_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 "workstationId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationId" in jsonified_request - assert jsonified_request["workstationId"] == request_init["workstation_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationId"] = 'workstation_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only", "workstation_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 "workstationId" in jsonified_request - assert jsonified_request["workstationId"] == 'workstation_id_value' - - client = WorkstationsClient( - 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 - - response = client.create_workstation(request) - - expected_params = [ - ( - "workstationId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationId", )) & set(("parent", "workstationId", "workstation", ))) - - -def test_create_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) - - -def test_create_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - -def test_update_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - - request = {} - client.update_workstation(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.update_workstation(request) - - # Establish 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_workstation_rest_required_fields(request_type=workstations.UpdateWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation._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_workstation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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': "patch", - '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 - - response = client.update_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstation", "updateMask", ))) - - -def test_update_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation=workstations.Workstation(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_workstation(**mock_args) - - # Establish that the underlying call 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/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_update_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - - request = {} - client.delete_workstation(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.delete_workstation(request) - - # Establish 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_workstation_rest_required_fields(request_type=workstations.DeleteWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation._get_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_workstation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "validate_only", )) - jsonified_request.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 = WorkstationsClient( - 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': "delete", - '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 - - response = client.delete_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) - - -def test_delete_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # 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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - - -def test_start_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_workstation] = mock_rpc - - request = {} - client.start_workstation(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.start_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_start_workstation_rest_required_fields(request_type=workstations.StartWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).start_workstation._get_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()).start_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - 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 - - response = client.start_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_start_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.start_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_start_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # 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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.start_workstation(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start" % client.transport._host, args[1]) - - -def test_start_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - - -def test_stop_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_workstation] = mock_rpc - - request = {} - client.stop_workstation(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.stop_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_stop_workstation_rest_required_fields(request_type=workstations.StopWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).stop_workstation._get_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()).stop_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - 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 - - response = client.stop_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_stop_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.stop_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_stop_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # 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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.stop_workstation(**mock_args) - - # Establish that the underlying call 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/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop" % client.transport._host, args[1]) - - -def test_stop_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - - -def test_generate_access_token_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc - - request = {} - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_access_token_rest_required_fields(request_type=workstations.GenerateAccessTokenRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["workstation"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["workstation"] = 'workstation_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "workstation" in jsonified_request - assert jsonified_request["workstation"] == 'workstation_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = workstations.GenerateAccessTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.generate_access_token(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_access_token_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_access_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("workstation", ))) - - -def test_generate_access_token_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - workstation='workstation_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = workstations.GenerateAccessTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.generate_access_token(**mock_args) - - # Establish that the underlying call 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/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken" % client.transport._host, args[1]) - - -def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WorkstationsClient( - 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 = WorkstationsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WorkstationsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WorkstationsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - transports.WorkstationsRestTransport, -]) -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 = WorkstationsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = WorkstationsClient( - 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_workstation_cluster_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = workstations.WorkstationCluster() - client.get_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_clusters_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = workstations.ListWorkstationClustersResponse() - client.list_workstation_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationClustersRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = workstations.WorkstationConfig() - client.get_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_configs_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListWorkstationConfigsResponse() - client.list_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This 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_usable_workstation_configs_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - client.list_usable_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = workstations.Workstation() - client.get_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstations_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = workstations.ListWorkstationsResponse() - client.list_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationsRequest() - - assert args[0] == request_msg - - -# This 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_usable_workstations_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationsResponse() - client.list_usable_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationsRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.start_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StartWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.stop_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StopWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_access_token_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = workstations.GenerateAccessTokenResponse() - client.generate_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GenerateAccessTokenRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = WorkstationsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = WorkstationsAsyncClient( - 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_workstation_cluster_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - )) - await client.get_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_clusters_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_workstation_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__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.create_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__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.update_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__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.delete_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - replica_zones=['replica_zones_value'], - degraded=True, - )) - await client.get_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_configs_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_usable_workstation_configs_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_usable_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__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.create_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__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.update_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__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.delete_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - )) - await client.get_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstations_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_usable_workstations_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_usable_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__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.create_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__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.update_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__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.delete_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_start_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StartWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_stop_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StopWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_access_token_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - )) - await client.generate_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GenerateAccessTokenRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = WorkstationsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_workstation_cluster_rest_bad_request(request_type=workstations.GetWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 - client.get_workstation_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationClusterRequest, - dict, -]) -def test_get_workstation_cluster_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=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 = workstations.WorkstationCluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationClusterRequest.pb(workstations.GetWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.WorkstationCluster.to_json(workstations.WorkstationCluster()) - req.return_value.content = return_value - - request = workstations.GetWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.WorkstationCluster() - - client.get_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstation_clusters_rest_bad_request(request_type=workstations.ListWorkstationClustersRequest): - client = WorkstationsClient( - 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 - client.list_workstation_clusters(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationClustersRequest, - dict, -]) -def test_list_workstation_clusters_rest_call_success(request_type): - client = WorkstationsClient( - 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 = workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListWorkstationClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_workstation_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstation_clusters_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_clusters") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_clusters") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationClustersRequest.pb(workstations.ListWorkstationClustersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListWorkstationClustersResponse.to_json(workstations.ListWorkstationClustersResponse()) - req.return_value.content = return_value - - request = workstations.ListWorkstationClustersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationClustersResponse() - - client.list_workstation_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_cluster_rest_bad_request(request_type=workstations.CreateWorkstationClusterRequest): - client = WorkstationsClient( - 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 - client.create_workstation_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationClusterRequest, - dict, -]) -def test_create_workstation_cluster_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = workstations.CreateWorkstationClusterRequest.meta.fields["workstation_cluster"] - - 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["workstation_cluster"].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["workstation_cluster"][field])): - del request_init["workstation_cluster"][field][i][subfield] - else: - del request_init["workstation_cluster"][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 = 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 - response = client.create_workstation_cluster(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_create_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationClusterRequest.pb(workstations.CreateWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.CreateWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_cluster_rest_bad_request(request_type=workstations.UpdateWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/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 - client.update_workstation_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationClusterRequest, - dict, -]) -def test_update_workstation_cluster_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = workstations.UpdateWorkstationClusterRequest.meta.fields["workstation_cluster"] - - 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["workstation_cluster"].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["workstation_cluster"][field])): - del request_init["workstation_cluster"][field][i][subfield] - else: - del request_init["workstation_cluster"][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 = 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 - response = client.update_workstation_cluster(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_update_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationClusterRequest.pb(workstations.UpdateWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.UpdateWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_cluster_rest_bad_request(request_type=workstations.DeleteWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 - client.delete_workstation_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationClusterRequest, - dict, -]) -def test_delete_workstation_cluster_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = 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 - response = client.delete_workstation_cluster(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_delete_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationClusterRequest.pb(workstations.DeleteWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.DeleteWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_config_rest_bad_request(request_type=workstations.GetWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_workstation_config(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationConfigRequest, - dict, -]) -def test_get_workstation_config_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - replica_zones=['replica_zones_value'], - degraded=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 = workstations.WorkstationConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_workstation_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.replica_zones == ['replica_zones_value'] - assert response.degraded is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationConfigRequest.pb(workstations.GetWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.WorkstationConfig.to_json(workstations.WorkstationConfig()) - req.return_value.content = return_value - - request = workstations.GetWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.WorkstationConfig() - - client.get_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstation_configs_rest_bad_request(request_type=workstations.ListWorkstationConfigsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 - client.list_workstation_configs(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationConfigsRequest, - dict, -]) -def test_list_workstation_configs_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_workstation_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstation_configs_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_configs") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationConfigsRequest.pb(workstations.ListWorkstationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListWorkstationConfigsResponse.to_json(workstations.ListWorkstationConfigsResponse()) - req.return_value.content = return_value - - request = workstations.ListWorkstationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationConfigsResponse() - - client.list_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_usable_workstation_configs_rest_bad_request(request_type=workstations.ListUsableWorkstationConfigsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 - client.list_usable_workstation_configs(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListUsableWorkstationConfigsRequest, - dict, -]) -def test_list_usable_workstation_configs_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_usable_workstation_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_usable_workstation_configs_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstation_configs") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstation_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListUsableWorkstationConfigsRequest.pb(workstations.ListUsableWorkstationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListUsableWorkstationConfigsResponse.to_json(workstations.ListUsableWorkstationConfigsResponse()) - req.return_value.content = return_value - - request = workstations.ListUsableWorkstationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListUsableWorkstationConfigsResponse() - - client.list_usable_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_config_rest_bad_request(request_type=workstations.CreateWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 - client.create_workstation_config(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationConfigRequest, - dict, -]) -def test_create_workstation_config_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'service_account_scopes': ['service_account_scopes_value1', 'service_account_scopes_value2'], 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'replica_zones': ['replica_zones_value1', 'replica_zones_value2'], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = workstations.CreateWorkstationConfigRequest.meta.fields["workstation_config"] - - 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["workstation_config"].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["workstation_config"][field])): - del request_init["workstation_config"][field][i][subfield] - else: - del request_init["workstation_config"][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 = 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 - response = client.create_workstation_config(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_create_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationConfigRequest.pb(workstations.CreateWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.CreateWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_config_rest_bad_request(request_type=workstations.UpdateWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_workstation_config(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationConfigRequest, - dict, -]) -def test_update_workstation_config_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'service_account_scopes': ['service_account_scopes_value1', 'service_account_scopes_value2'], 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'replica_zones': ['replica_zones_value1', 'replica_zones_value2'], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = workstations.UpdateWorkstationConfigRequest.meta.fields["workstation_config"] - - 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["workstation_config"].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["workstation_config"][field])): - del request_init["workstation_config"][field][i][subfield] - else: - del request_init["workstation_config"][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 = 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 - response = client.update_workstation_config(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_update_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationConfigRequest.pb(workstations.UpdateWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.UpdateWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_config_rest_bad_request(request_type=workstations.DeleteWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.delete_workstation_config(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationConfigRequest, - dict, -]) -def test_delete_workstation_config_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # 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 - response = client.delete_workstation_config(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_delete_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationConfigRequest.pb(workstations.DeleteWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.DeleteWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_rest_bad_request(request_type=workstations.GetWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationRequest, - dict, -]) -def test_get_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_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 = workstations.Workstation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_workstation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationRequest.pb(workstations.GetWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.Workstation.to_json(workstations.Workstation()) - req.return_value.content = return_value - - request = workstations.GetWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.Workstation() - - client.get_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstations_rest_bad_request(request_type=workstations.ListWorkstationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_workstations(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationsRequest, - dict, -]) -def test_list_workstations_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_workstations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstations_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstations") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationsRequest.pb(workstations.ListWorkstationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListWorkstationsResponse.to_json(workstations.ListWorkstationsResponse()) - req.return_value.content = return_value - - request = workstations.ListWorkstationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationsResponse() - - client.list_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_usable_workstations_rest_bad_request(request_type=workstations.ListUsableWorkstationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_usable_workstations(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListUsableWorkstationsRequest, - dict, -]) -def test_list_usable_workstations_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListUsableWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_usable_workstations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_usable_workstations_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstations") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListUsableWorkstationsRequest.pb(workstations.ListUsableWorkstationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListUsableWorkstationsResponse.to_json(workstations.ListUsableWorkstationsResponse()) - req.return_value.content = return_value - - request = workstations.ListUsableWorkstationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListUsableWorkstationsResponse() - - client.list_usable_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_rest_bad_request(request_type=workstations.CreateWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationRequest, - dict, -]) -def test_create_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'start_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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 = workstations.CreateWorkstationRequest.meta.fields["workstation"] - - 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["workstation"].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["workstation"][field])): - del request_init["workstation"][field][i][subfield] - else: - del request_init["workstation"][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 = 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 - response = client.create_workstation(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_create_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationRequest.pb(workstations.CreateWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.CreateWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_rest_bad_request(request_type=workstations.UpdateWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationRequest, - dict, -]) -def test_update_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'start_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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 = workstations.UpdateWorkstationRequest.meta.fields["workstation"] - - 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["workstation"].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["workstation"][field])): - del request_init["workstation"][field][i][subfield] - else: - del request_init["workstation"][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 = 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 - response = client.update_workstation(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_update_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationRequest.pb(workstations.UpdateWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.UpdateWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_rest_bad_request(request_type=workstations.DeleteWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.delete_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationRequest, - dict, -]) -def test_delete_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and 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 - response = client.delete_workstation(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_delete_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationRequest.pb(workstations.DeleteWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.DeleteWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_start_workstation_rest_bad_request(request_type=workstations.StartWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.start_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.StartWorkstationRequest, - dict, -]) -def test_start_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and 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 - response = client.start_workstation(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_start_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_start_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_start_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.StartWorkstationRequest.pb(workstations.StartWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.StartWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.start_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_stop_workstation_rest_bad_request(request_type=workstations.StopWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.stop_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.StopWorkstationRequest, - dict, -]) -def test_stop_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and 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 - response = client.stop_workstation(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_stop_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_stop_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_stop_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.StopWorkstationRequest.pb(workstations.StopWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.StopWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.stop_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_access_token_rest_bad_request(request_type=workstations.GenerateAccessTokenRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.generate_access_token(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse( - access_token='access_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 = workstations.GenerateAccessTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.generate_access_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_access_token_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_generate_access_token") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_generate_access_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GenerateAccessTokenRequest.pb(workstations.GenerateAccessTokenRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.GenerateAccessTokenResponse.to_json(workstations.GenerateAccessTokenResponse()) - req.return_value.content = return_value - - request = workstations.GenerateAccessTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.GenerateAccessTokenResponse() - - client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - 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 = policy_pb2.Policy() - - # 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 - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - 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 = policy_pb2.Policy() - - # 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 - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - 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 = iam_policy_pb2.TestIamPermissionsResponse() - - # 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 - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = WorkstationsClient( - 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 - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = WorkstationsClient( - 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 = 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 - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = WorkstationsClient( - 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 - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = WorkstationsClient( - 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 = 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 - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = WorkstationsClient( - 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 - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = WorkstationsClient( - 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 - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # 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 - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': '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(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # 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 - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_initialize_client_w_rest(): - client = WorkstationsClient( - 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_workstation_cluster_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - client.get_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_clusters_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - client.list_workstation_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationClustersRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - client.create_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - client.update_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - client.delete_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - client.get_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_configs_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - client.list_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This 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_usable_workstation_configs_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - client.list_usable_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - client.create_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - client.update_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - client.delete_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - client.get_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstations_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - client.list_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationsRequest() - - assert args[0] == request_msg - - -# This 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_usable_workstations_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - client.list_usable_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationsRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - client.create_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - client.update_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - client.delete_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - client.start_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StartWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - client.stop_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StopWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_access_token_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - client.generate_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GenerateAccessTokenRequest() - - assert args[0] == request_msg - - -def test_workstations_rest_lro_client(): - client = WorkstationsClient( - 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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WorkstationsGrpcTransport, - ) - -def test_workstations_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WorkstationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_workstations_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WorkstationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_workstation_cluster', - 'list_workstation_clusters', - 'create_workstation_cluster', - 'update_workstation_cluster', - 'delete_workstation_cluster', - 'get_workstation_config', - 'list_workstation_configs', - 'list_usable_workstation_configs', - 'create_workstation_config', - 'update_workstation_config', - 'delete_workstation_config', - 'get_workstation', - 'list_workstations', - 'list_usable_workstations', - 'create_workstation', - 'update_workstation', - 'delete_workstation', - 'start_workstation', - 'stop_workstation', - 'generate_access_token', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - 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_workstations_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkstationsTransport( - 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_workstations_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkstationsTransport() - adc.assert_called_once() - - -def test_workstations_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) - WorkstationsClient() - 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.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - ], -) -def test_workstations_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.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - transports.WorkstationsRestTransport, - ], -) -def test_workstations_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.WorkstationsGrpcTransport, grpc_helpers), - (transports.WorkstationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_workstations_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( - "workstations.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="workstations.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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_workstations_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.WorkstationsRestTransport ( - 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_workstations_host_no_port(transport_name): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workstations.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_workstations_host_with_port(transport_name): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workstations.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workstations.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_workstations_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = WorkstationsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = WorkstationsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_workstation_cluster._session - session2 = client2.transport.get_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.list_workstation_clusters._session - session2 = client2.transport.list_workstation_clusters._session - assert session1 != session2 - session1 = client1.transport.create_workstation_cluster._session - session2 = client2.transport.create_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.update_workstation_cluster._session - session2 = client2.transport.update_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.delete_workstation_cluster._session - session2 = client2.transport.delete_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.get_workstation_config._session - session2 = client2.transport.get_workstation_config._session - assert session1 != session2 - session1 = client1.transport.list_workstation_configs._session - session2 = client2.transport.list_workstation_configs._session - assert session1 != session2 - session1 = client1.transport.list_usable_workstation_configs._session - session2 = client2.transport.list_usable_workstation_configs._session - assert session1 != session2 - session1 = client1.transport.create_workstation_config._session - session2 = client2.transport.create_workstation_config._session - assert session1 != session2 - session1 = client1.transport.update_workstation_config._session - session2 = client2.transport.update_workstation_config._session - assert session1 != session2 - session1 = client1.transport.delete_workstation_config._session - session2 = client2.transport.delete_workstation_config._session - assert session1 != session2 - session1 = client1.transport.get_workstation._session - session2 = client2.transport.get_workstation._session - assert session1 != session2 - session1 = client1.transport.list_workstations._session - session2 = client2.transport.list_workstations._session - assert session1 != session2 - session1 = client1.transport.list_usable_workstations._session - session2 = client2.transport.list_usable_workstations._session - assert session1 != session2 - session1 = client1.transport.create_workstation._session - session2 = client2.transport.create_workstation._session - assert session1 != session2 - session1 = client1.transport.update_workstation._session - session2 = client2.transport.update_workstation._session - assert session1 != session2 - session1 = client1.transport.delete_workstation._session - session2 = client2.transport.delete_workstation._session - assert session1 != session2 - session1 = client1.transport.start_workstation._session - session2 = client2.transport.start_workstation._session - assert session1 != session2 - session1 = client1.transport.stop_workstation._session - session2 = client2.transport.stop_workstation._session - assert session1 != session2 - session1 = client1.transport.generate_access_token._session - session2 = client2.transport.generate_access_token._session - assert session1 != session2 -def test_workstations_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkstationsGrpcTransport( - 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_workstations_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkstationsGrpcAsyncIOTransport( - 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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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_workstations_grpc_lro_client(): - client = WorkstationsClient( - 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_workstations_grpc_lro_async_client(): - client = WorkstationsAsyncClient( - 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_workstation_path(): - project = "squid" - location = "clam" - workstation_cluster = "whelk" - workstation_config = "octopus" - workstation = "oyster" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) - actual = WorkstationsClient.workstation_path(project, location, workstation_cluster, workstation_config, workstation) - assert expected == actual - - -def test_parse_workstation_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "workstation_cluster": "mussel", - "workstation_config": "winkle", - "workstation": "nautilus", - } - path = WorkstationsClient.workstation_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_path(path) - assert expected == actual - -def test_workstation_cluster_path(): - project = "scallop" - location = "abalone" - workstation_cluster = "squid" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) - actual = WorkstationsClient.workstation_cluster_path(project, location, workstation_cluster) - assert expected == actual - - -def test_parse_workstation_cluster_path(): - expected = { - "project": "clam", - "location": "whelk", - "workstation_cluster": "octopus", - } - path = WorkstationsClient.workstation_cluster_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_cluster_path(path) - assert expected == actual - -def test_workstation_config_path(): - project = "oyster" - location = "nudibranch" - workstation_cluster = "cuttlefish" - workstation_config = "mussel" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) - actual = WorkstationsClient.workstation_config_path(project, location, workstation_cluster, workstation_config) - assert expected == actual - - -def test_parse_workstation_config_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "workstation_cluster": "scallop", - "workstation_config": "abalone", - } - path = WorkstationsClient.workstation_config_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WorkstationsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = WorkstationsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = WorkstationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = WorkstationsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WorkstationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = WorkstationsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = WorkstationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = WorkstationsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.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 = WorkstationsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = WorkstationsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.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.WorkstationsTransport, '_prep_wrapped_messages') as prep: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WorkstationsTransport, '_prep_wrapped_messages') as prep: - transport_class = WorkstationsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_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 response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_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 response is None - -def test_delete_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_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_delete_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_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_delete_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_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 response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_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 response is None - -def test_cancel_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_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_cancel_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_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_cancel_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = WorkstationsClient( - 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 = WorkstationsAsyncClient( - 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_list_operations(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the 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.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the 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.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_list_operations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_list_operations_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_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 response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_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 response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_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", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_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", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_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 response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_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 response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_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", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_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", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = WorkstationsClient( - 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 = WorkstationsAsyncClient( - 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 = WorkstationsClient( - 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 = WorkstationsClient( - 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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport), -]) -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-cloud-workstations/v1beta/.coveragerc b/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc deleted file mode 100644 index ee1a17c3e2ca..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/workstations/__init__.py - google/cloud/workstations/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-cloud-workstations/v1beta/.flake8 b/owl-bot-staging/google-cloud-workstations/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in deleted file mode 100644 index ebef07fddb1d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/workstations *.py -recursive-include google/cloud/workstations_v1beta *.py diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/README.rst b/owl-bot-staging/google-cloud-workstations/v1beta/README.rst deleted file mode 100644 index 48a711be018f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Workstations 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 Cloud Workstations 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-cloud-workstations/v1beta/docs/_static/custom.css b/owl-bot-staging/google-cloud-workstations/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py deleted file mode 100644 index 65ff2ad5ae85..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations 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-cloud-workstations" -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 Cloud 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-cloud-workstations-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-cloud-workstations.tex", - u"google-cloud-workstations 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-cloud-workstations", - u"Google Cloud Workstations 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-cloud-workstations", - u"google-cloud-workstations Documentation", - author, - "google-cloud-workstations", - "GAPIC library for Google Cloud Workstations 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-cloud-workstations/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst deleted file mode 100644 index 4550acabdaad..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - workstations_v1beta/services_ - workstations_v1beta/types_ diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services_.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services_.rst deleted file mode 100644 index 77aed9f52d7a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Workstations v1beta API -================================================= -.. toctree:: - :maxdepth: 2 - - workstations diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types_.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types_.rst deleted file mode 100644 index af7f36fbcb60..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Workstations v1beta API -============================================== - -.. automodule:: google.cloud.workstations_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst deleted file mode 100644 index 5839880c918a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst +++ /dev/null @@ -1,10 +0,0 @@ -Workstations ------------------------------- - -.. automodule:: google.cloud.workstations_v1beta.services.workstations - :members: - :inherited-members: - -.. automodule:: google.cloud.workstations_v1beta.services.workstations.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py deleted file mode 100644 index 39b1cbb59f51..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workstations import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.workstations_v1beta.services.workstations.client import WorkstationsClient -from google.cloud.workstations_v1beta.services.workstations.async_client import WorkstationsAsyncClient - -from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationClusterRequest -from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationConfigRequest -from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationClusterRequest -from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationConfigRequest -from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import GenerateAccessTokenRequest -from google.cloud.workstations_v1beta.types.workstations import GenerateAccessTokenResponse -from google.cloud.workstations_v1beta.types.workstations import GetWorkstationClusterRequest -from google.cloud.workstations_v1beta.types.workstations import GetWorkstationConfigRequest -from google.cloud.workstations_v1beta.types.workstations import GetWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationConfigsRequest -from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationConfigsResponse -from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationsRequest -from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationsResponse -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationClustersRequest -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationClustersResponse -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationConfigsRequest -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationConfigsResponse -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationsRequest -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationsResponse -from google.cloud.workstations_v1beta.types.workstations import OperationMetadata -from google.cloud.workstations_v1beta.types.workstations import StartWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import StopWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationClusterRequest -from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationConfigRequest -from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import Workstation -from google.cloud.workstations_v1beta.types.workstations import WorkstationCluster -from google.cloud.workstations_v1beta.types.workstations import WorkstationConfig - -__all__ = ('WorkstationsClient', - 'WorkstationsAsyncClient', - 'CreateWorkstationClusterRequest', - 'CreateWorkstationConfigRequest', - 'CreateWorkstationRequest', - 'DeleteWorkstationClusterRequest', - 'DeleteWorkstationConfigRequest', - 'DeleteWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GetWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'OperationMetadata', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'UpdateWorkstationClusterRequest', - 'UpdateWorkstationConfigRequest', - 'UpdateWorkstationRequest', - 'Workstation', - 'WorkstationCluster', - 'WorkstationConfig', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/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-cloud-workstations/v1beta/google/cloud/workstations/py.typed b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed deleted file mode 100644 index 04170223dff9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py deleted file mode 100644 index 6a7789157329..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py +++ /dev/null @@ -1,88 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workstations_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.workstations import WorkstationsClient -from .services.workstations import WorkstationsAsyncClient - -from .types.workstations import CreateWorkstationClusterRequest -from .types.workstations import CreateWorkstationConfigRequest -from .types.workstations import CreateWorkstationRequest -from .types.workstations import DeleteWorkstationClusterRequest -from .types.workstations import DeleteWorkstationConfigRequest -from .types.workstations import DeleteWorkstationRequest -from .types.workstations import GenerateAccessTokenRequest -from .types.workstations import GenerateAccessTokenResponse -from .types.workstations import GetWorkstationClusterRequest -from .types.workstations import GetWorkstationConfigRequest -from .types.workstations import GetWorkstationRequest -from .types.workstations import ListUsableWorkstationConfigsRequest -from .types.workstations import ListUsableWorkstationConfigsResponse -from .types.workstations import ListUsableWorkstationsRequest -from .types.workstations import ListUsableWorkstationsResponse -from .types.workstations import ListWorkstationClustersRequest -from .types.workstations import ListWorkstationClustersResponse -from .types.workstations import ListWorkstationConfigsRequest -from .types.workstations import ListWorkstationConfigsResponse -from .types.workstations import ListWorkstationsRequest -from .types.workstations import ListWorkstationsResponse -from .types.workstations import OperationMetadata -from .types.workstations import StartWorkstationRequest -from .types.workstations import StopWorkstationRequest -from .types.workstations import UpdateWorkstationClusterRequest -from .types.workstations import UpdateWorkstationConfigRequest -from .types.workstations import UpdateWorkstationRequest -from .types.workstations import Workstation -from .types.workstations import WorkstationCluster -from .types.workstations import WorkstationConfig - -__all__ = ( - 'WorkstationsAsyncClient', -'CreateWorkstationClusterRequest', -'CreateWorkstationConfigRequest', -'CreateWorkstationRequest', -'DeleteWorkstationClusterRequest', -'DeleteWorkstationConfigRequest', -'DeleteWorkstationRequest', -'GenerateAccessTokenRequest', -'GenerateAccessTokenResponse', -'GetWorkstationClusterRequest', -'GetWorkstationConfigRequest', -'GetWorkstationRequest', -'ListUsableWorkstationConfigsRequest', -'ListUsableWorkstationConfigsResponse', -'ListUsableWorkstationsRequest', -'ListUsableWorkstationsResponse', -'ListWorkstationClustersRequest', -'ListWorkstationClustersResponse', -'ListWorkstationConfigsRequest', -'ListWorkstationConfigsResponse', -'ListWorkstationsRequest', -'ListWorkstationsResponse', -'OperationMetadata', -'StartWorkstationRequest', -'StopWorkstationRequest', -'UpdateWorkstationClusterRequest', -'UpdateWorkstationConfigRequest', -'UpdateWorkstationRequest', -'Workstation', -'WorkstationCluster', -'WorkstationConfig', -'WorkstationsClient', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json deleted file mode 100644 index cf8a80968ec1..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json +++ /dev/null @@ -1,328 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.workstations_v1beta", - "protoPackage": "google.cloud.workstations.v1beta", - "schema": "1.0", - "services": { - "Workstations": { - "clients": { - "grpc": { - "libraryClient": "WorkstationsClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WorkstationsAsyncClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - }, - "rest": { - "libraryClient": "WorkstationsClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_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-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed deleted file mode 100644 index 04170223dff9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_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-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py deleted file mode 100644 index e8958d8c0d6d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__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 WorkstationsClient -from .async_client import WorkstationsAsyncClient - -__all__ = ( - 'WorkstationsClient', - 'WorkstationsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py deleted file mode 100644 index d71d80c082ca..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py +++ /dev/null @@ -1,3183 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.workstations_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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.services.workstations import pagers -from google.cloud.workstations_v1beta.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .client import WorkstationsClient - - -class WorkstationsAsyncClient: - """Service for interacting with Cloud Workstations.""" - - _client: WorkstationsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = WorkstationsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WorkstationsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = WorkstationsClient._DEFAULT_UNIVERSE - - workstation_path = staticmethod(WorkstationsClient.workstation_path) - parse_workstation_path = staticmethod(WorkstationsClient.parse_workstation_path) - workstation_cluster_path = staticmethod(WorkstationsClient.workstation_cluster_path) - parse_workstation_cluster_path = staticmethod(WorkstationsClient.parse_workstation_cluster_path) - workstation_config_path = staticmethod(WorkstationsClient.workstation_config_path) - parse_workstation_config_path = staticmethod(WorkstationsClient.parse_workstation_config_path) - common_billing_account_path = staticmethod(WorkstationsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WorkstationsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WorkstationsClient.common_folder_path) - parse_common_folder_path = staticmethod(WorkstationsClient.parse_common_folder_path) - common_organization_path = staticmethod(WorkstationsClient.common_organization_path) - parse_common_organization_path = staticmethod(WorkstationsClient.parse_common_organization_path) - common_project_path = staticmethod(WorkstationsClient.common_project_path) - parse_common_project_path = staticmethod(WorkstationsClient.parse_common_project_path) - common_location_path = staticmethod(WorkstationsClient.common_location_path) - parse_common_location_path = staticmethod(WorkstationsClient.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: - WorkstationsAsyncClient: The constructed client. - """ - return WorkstationsClient.from_service_account_info.__func__(WorkstationsAsyncClient, 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: - WorkstationsAsyncClient: The constructed client. - """ - return WorkstationsClient.from_service_account_file.__func__(WorkstationsAsyncClient, 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 WorkstationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> WorkstationsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkstationsTransport: 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 = WorkstationsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, WorkstationsTransport, Callable[..., WorkstationsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workstations 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,WorkstationsTransport,Callable[..., WorkstationsTransport]]]): - 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 WorkstationsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WorkstationsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_workstation_cluster(self, - request: Optional[Union[workstations.GetWorkstationClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.WorkstationCluster: - r"""Returns the requested workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest, dict]]): - The request object. Request message for - GetWorkstationCluster. - name (:class:`str`): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.types.WorkstationCluster: - A workstation cluster resource in the - Cloud Workstations API. - Defines a group of workstations in a - particular region and the VPC network - they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationClusterRequest): - request = workstations.GetWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_cluster] - - # Certain fields should be provided within 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_workstation_clusters(self, - request: Optional[Union[workstations.ListWorkstationClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationClustersAsyncPager: - r"""Returns all workstation clusters in the specified - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest, dict]]): - The request object. Request message for - ListWorkstationClusters. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersAsyncPager: - Response message for - ListWorkstationClusters. - 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, workstations.ListWorkstationClustersRequest): - request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] - - # Certain fields should be provided within 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.ListWorkstationClustersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation_cluster(self, - request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_cluster: Optional[workstations.WorkstationCluster] = None, - workstation_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest, dict]]): - The request object. Message for creating a - CreateWorkstationCluster. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster (:class:`google.cloud.workstations_v1beta.types.WorkstationCluster`): - Required. Workstation cluster to - create. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster_id (:class:`str`): - Required. ID to use for the - workstation cluster. - - This corresponds to the ``workstation_cluster_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation_cluster, workstation_cluster_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, workstations.CreateWorkstationClusterRequest): - request = workstations.CreateWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - if workstation_cluster_id is not None: - request.workstation_cluster_id = workstation_cluster_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_workstation_cluster] - - # Certain fields should be provided within 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation_cluster(self, - request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, - *, - workstation_cluster: Optional[workstations.WorkstationCluster] = 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, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an existing workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest, dict]]): - The request object. Request message for - UpdateWorkstationCluster. - workstation_cluster (:class:`google.cloud.workstations_v1beta.types.WorkstationCluster`): - Required. Workstation cluster to - update. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask that specifies which - fields in the workstation cluster should - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_cluster, 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, workstations.UpdateWorkstationClusterRequest): - request = workstations.UpdateWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - 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_workstation_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_cluster.name", request.workstation_cluster.name), - )), - ) - - # 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation_cluster(self, - request: Optional[Union[workstations.DeleteWorkstationClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest, dict]]): - The request object. Message for deleting a workstation - cluster. - name (:class:`str`): - Required. Name of the workstation - cluster to delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationClusterRequest): - request = workstations.DeleteWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_cluster] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_workstation_config(self, - request: Optional[Union[workstations.GetWorkstationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.WorkstationConfig: - r"""Returns the requested workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_get_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest, dict]]): - The request object. Request message for - GetWorkstationConfig. - name (:class:`str`): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.types.WorkstationConfig: - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationConfigRequest): - request = workstations.GetWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_config] - - # Certain fields should be provided within 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_workstation_configs(self, - request: Optional[Union[workstations.ListWorkstationConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationConfigsAsyncPager: - r"""Returns all workstation configurations in the - specified cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest, dict]]): - The request object. Request message for - ListWorkstationConfigs. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsAsyncPager: - Response message for - ListWorkstationConfigs. - 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, workstations.ListWorkstationConfigsRequest): - request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] - - # Certain fields should be provided within 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.ListWorkstationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_usable_workstation_configs(self, - request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUsableWorkstationConfigsAsyncPager: - r"""Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest, dict]]): - The request object. Request message for - ListUsableWorkstationConfigs. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager: - Response message for - ListUsableWorkstationConfigs. - 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, workstations.ListUsableWorkstationConfigsRequest): - request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] - - # Certain fields should be provided within 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.ListUsableWorkstationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation_config(self, - request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_config: Optional[workstations.WorkstationConfig] = None, - workstation_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_create_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest, dict]]): - The request object. Message for creating a - CreateWorkstationConfig. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config (:class:`google.cloud.workstations_v1beta.types.WorkstationConfig`): - Required. Config to create. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config_id (:class:`str`): - Required. ID to use for the - workstation configuration. - - This corresponds to the ``workstation_config_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation_config, workstation_config_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, workstations.CreateWorkstationConfigRequest): - request = workstations.CreateWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_config is not None: - request.workstation_config = workstation_config - if workstation_config_id is not None: - request.workstation_config_id = workstation_config_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_workstation_config] - - # Certain fields should be provided within 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation_config(self, - request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, - *, - workstation_config: Optional[workstations.WorkstationConfig] = 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, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an existing workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_update_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest, dict]]): - The request object. Request message for - UpdateWorkstationConfig. - workstation_config (:class:`google.cloud.workstations_v1beta.types.WorkstationConfig`): - Required. Config to update. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask specifying which - fields in the workstation configuration - should 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_config, 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, workstations.UpdateWorkstationConfigRequest): - request = workstations.UpdateWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_config is not None: - request.workstation_config = workstation_config - 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_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_config.name", request.workstation_config.name), - )), - ) - - # 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation_config(self, - request: Optional[Union[workstations.DeleteWorkstationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_delete_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest, dict]]): - The request object. Message for deleting a workstation - configuration. - name (:class:`str`): - Required. Name of the workstation - configuration to delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationConfigRequest): - request = workstations.DeleteWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_config] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_workstation(self, - request: Optional[Union[workstations.GetWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.Workstation: - r"""Returns the requested workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_get_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationRequest, dict]]): - The request object. Request message for GetWorkstation. - name (:class:`str`): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.types.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationRequest): - request = workstations.GetWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation] - - # Certain fields should be provided within 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_workstations(self, - request: Optional[Union[workstations.ListWorkstationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationsAsyncPager: - r"""Returns all Workstations using the specified - workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationsRequest, dict]]): - The request object. Request message for ListWorkstations. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationsAsyncPager: - Response message for - ListWorkstations. - 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, workstations.ListWorkstationsRequest): - request = workstations.ListWorkstationsRequest(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_workstations] - - # Certain fields should be provided within 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.ListWorkstationsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_usable_workstations(self, - request: Optional[Union[workstations.ListUsableWorkstationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUsableWorkstationsAsyncPager: - r"""Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_usable_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest, dict]]): - The request object. Request message for - ListUsableWorkstations. - parent (:class:`str`): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsAsyncPager: - Response message for - ListUsableWorkstations. - 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, workstations.ListUsableWorkstationsRequest): - request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] - - # Certain fields should be provided within 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.ListUsableWorkstationsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation(self, - request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation: Optional[workstations.Workstation] = None, - workstation_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_create_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationRequest, dict]]): - The request object. Message for creating a - CreateWorkstation. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation (:class:`google.cloud.workstations_v1beta.types.Workstation`): - Required. Workstation to create. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_id (:class:`str`): - Required. ID to use for the - workstation. - - This corresponds to the ``workstation_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation, workstation_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, workstations.CreateWorkstationRequest): - request = workstations.CreateWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation is not None: - request.workstation = workstation - if workstation_id is not None: - request.workstation_id = workstation_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_workstation] - - # Certain fields should be provided within 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation(self, - request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, - *, - workstation: Optional[workstations.Workstation] = 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, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an existing workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_update_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationRequest, dict]]): - The request object. Request message for - UpdateWorkstation. - workstation (:class:`google.cloud.workstations_v1beta.types.Workstation`): - Required. Workstation to update. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask specifying which - fields in the workstation configuration - should 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation, 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, workstations.UpdateWorkstationRequest): - request = workstations.UpdateWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - 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_workstation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation.name", request.workstation.name), - )), - ) - - # 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation(self, - request: Optional[Union[workstations.DeleteWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_delete_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationRequest, dict]]): - The request object. Request message for - DeleteWorkstation. - name (:class:`str`): - Required. Name of the workstation to - delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationRequest): - request = workstations.DeleteWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def start_workstation(self, - request: Optional[Union[workstations.StartWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Starts running a workstation so that users can - connect to it. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_start_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.StartWorkstationRequest, dict]]): - The request object. Request message for StartWorkstation. - name (:class:`str`): - Required. Name of the workstation to - start. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.StartWorkstationRequest): - request = workstations.StartWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.start_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def stop_workstation(self, - request: Optional[Union[workstations.StopWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Stops running a workstation, reducing costs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_stop_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.StopWorkstationRequest, dict]]): - The request object. Request message for StopWorkstation. - name (:class:`str`): - Required. Name of the workstation to - stop. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.StopWorkstationRequest): - request = workstations.StopWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.stop_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def generate_access_token(self, - request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, - *, - workstation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.GenerateAccessTokenResponse: - r"""Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_generate_access_token(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest, dict]]): - The request object. Request message for - GenerateAccessToken. - workstation (:class:`str`): - Required. Name of the workstation for - which the access token should be - generated. - - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_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. - - Returns: - google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, workstations.GenerateAccessTokenRequest): - request = workstations.GenerateAccessTokenRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation", request.workstation), - )), - ) - - # Validate the universe domain. - self._client._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_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # 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.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_operations] - - # Certain fields should be provided within 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_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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # 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.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.delete_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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # 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.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.cancel_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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._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_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._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) -> "WorkstationsAsyncClient": - 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__ = ( - "WorkstationsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py deleted file mode 100644 index ab254329c5e9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py +++ /dev/null @@ -1,3536 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.workstations_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 - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.services.workstations import pagers -from google.cloud.workstations_v1beta.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WorkstationsGrpcTransport -from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .transports.rest import WorkstationsRestTransport - - -class WorkstationsClientMeta(type): - """Metaclass for the Workstations 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[WorkstationsTransport]] - _transport_registry["grpc"] = WorkstationsGrpcTransport - _transport_registry["grpc_asyncio"] = WorkstationsGrpcAsyncIOTransport - _transport_registry["rest"] = WorkstationsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[WorkstationsTransport]: - """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 WorkstationsClient(metaclass=WorkstationsClientMeta): - """Service for interacting with Cloud Workstations.""" - - @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 = "workstations.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "workstations.{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: - WorkstationsClient: 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: - WorkstationsClient: 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) -> WorkstationsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkstationsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def workstation_path(project: str,location: str,workstation_cluster: str,workstation_config: str,workstation: str,) -> str: - """Returns a fully-qualified workstation string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) - - @staticmethod - def parse_workstation_path(path: str) -> Dict[str,str]: - """Parses a workstation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?P.+?)/workstations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workstation_cluster_path(project: str,location: str,workstation_cluster: str,) -> str: - """Returns a fully-qualified workstation_cluster string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) - - @staticmethod - def parse_workstation_cluster_path(path: str) -> Dict[str,str]: - """Parses a workstation_cluster path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workstation_config_path(project: str,location: str,workstation_cluster: str,workstation_config: str,) -> str: - """Returns a fully-qualified workstation_config string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) - - @staticmethod - def parse_workstation_config_path(path: str) -> Dict[str,str]: - """Parses a workstation_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?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 = WorkstationsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = WorkstationsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = WorkstationsClient._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 = WorkstationsClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = WorkstationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - WorkstationsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, WorkstationsTransport, Callable[..., WorkstationsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workstations client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,WorkstationsTransport,Callable[..., WorkstationsTransport]]]): - 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 WorkstationsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = WorkstationsClient._read_environment_variables() - self._client_cert_source = WorkstationsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = WorkstationsClient._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 - - 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, WorkstationsTransport) - if transport_provided: - # transport is a WorkstationsTransport 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(WorkstationsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - WorkstationsClient._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[WorkstationsTransport], Callable[..., WorkstationsTransport]] = ( - WorkstationsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., WorkstationsTransport], 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, - ) - - def get_workstation_cluster(self, - request: Optional[Union[workstations.GetWorkstationClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.WorkstationCluster: - r"""Returns the requested workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest, dict]): - The request object. Request message for - GetWorkstationCluster. - name (str): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.types.WorkstationCluster: - A workstation cluster resource in the - Cloud Workstations API. - Defines a group of workstations in a - particular region and the VPC network - they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationClusterRequest): - request = workstations.GetWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_cluster] - - # Certain fields should be provided within 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_workstation_clusters(self, - request: Optional[Union[workstations.ListWorkstationClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationClustersPager: - r"""Returns all workstation clusters in the specified - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest, dict]): - The request object. Request message for - ListWorkstationClusters. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersPager: - Response message for - ListWorkstationClusters. - 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, workstations.ListWorkstationClustersRequest): - request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] - - # Certain fields should be provided within 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.ListWorkstationClustersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation_cluster(self, - request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_cluster: Optional[workstations.WorkstationCluster] = None, - workstation_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest, dict]): - The request object. Message for creating a - CreateWorkstationCluster. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): - Required. Workstation cluster to - create. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster_id (str): - Required. ID to use for the - workstation cluster. - - This corresponds to the ``workstation_cluster_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation_cluster, workstation_cluster_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, workstations.CreateWorkstationClusterRequest): - request = workstations.CreateWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - if workstation_cluster_id is not None: - request.workstation_cluster_id = workstation_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation_cluster] - - # Certain fields should be provided within 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation_cluster(self, - request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, - *, - workstation_cluster: Optional[workstations.WorkstationCluster] = 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, str]] = (), - ) -> operation.Operation: - r"""Updates an existing workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest, dict]): - The request object. Request message for - UpdateWorkstationCluster. - workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): - Required. Workstation cluster to - update. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask that specifies which - fields in the workstation cluster should - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_cluster, 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, workstations.UpdateWorkstationClusterRequest): - request = workstations.UpdateWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - 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_workstation_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_cluster.name", request.workstation_cluster.name), - )), - ) - - # 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation_cluster(self, - request: Optional[Union[workstations.DeleteWorkstationClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest, dict]): - The request object. Message for deleting a workstation - cluster. - name (str): - Required. Name of the workstation - cluster to delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` - A workstation cluster resource in the Cloud Workstations - API. - - Defines a group of workstations in a particular - region and the VPC network they're attached to. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationClusterRequest): - request = workstations.DeleteWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_cluster] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_workstation_config(self, - request: Optional[Union[workstations.GetWorkstationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.WorkstationConfig: - r"""Returns the requested workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_get_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest, dict]): - The request object. Request message for - GetWorkstationConfig. - name (str): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.types.WorkstationConfig: - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationConfigRequest): - request = workstations.GetWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_config] - - # Certain fields should be provided within 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_workstation_configs(self, - request: Optional[Union[workstations.ListWorkstationConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationConfigsPager: - r"""Returns all workstation configurations in the - specified cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest, dict]): - The request object. Request message for - ListWorkstationConfigs. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsPager: - Response message for - ListWorkstationConfigs. - 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, workstations.ListWorkstationConfigsRequest): - request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] - - # Certain fields should be provided within 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.ListWorkstationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_usable_workstation_configs(self, - request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUsableWorkstationConfigsPager: - r"""Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest, dict]): - The request object. Request message for - ListUsableWorkstationConfigs. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsPager: - Response message for - ListUsableWorkstationConfigs. - 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, workstations.ListUsableWorkstationConfigsRequest): - request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] - - # Certain fields should be provided within 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.ListUsableWorkstationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation_config(self, - request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_config: Optional[workstations.WorkstationConfig] = None, - workstation_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_create_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest, dict]): - The request object. Message for creating a - CreateWorkstationConfig. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): - Required. Config to create. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config_id (str): - Required. ID to use for the - workstation configuration. - - This corresponds to the ``workstation_config_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation_config, workstation_config_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, workstations.CreateWorkstationConfigRequest): - request = workstations.CreateWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_config is not None: - request.workstation_config = workstation_config - if workstation_config_id is not None: - request.workstation_config_id = workstation_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation_config] - - # Certain fields should be provided within 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation_config(self, - request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, - *, - workstation_config: Optional[workstations.WorkstationConfig] = 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, str]] = (), - ) -> operation.Operation: - r"""Updates an existing workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_update_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest, dict]): - The request object. Request message for - UpdateWorkstationConfig. - workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): - Required. Config to update. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which - fields in the workstation configuration - should 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_config, 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, workstations.UpdateWorkstationConfigRequest): - request = workstations.UpdateWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_config is not None: - request.workstation_config = workstation_config - 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_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_config.name", request.workstation_config.name), - )), - ) - - # 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation_config(self, - request: Optional[Union[workstations.DeleteWorkstationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_delete_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest, dict]): - The request object. Message for deleting a workstation - configuration. - name (str): - Required. Name of the workstation - configuration to delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to - use, and more. Administrators and platform teams can - also use [Identity and Access Management - (IAM)](https://cloud.google.com/iam/docs/overview) - rules to grant access to teams or to individual - developers. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationConfigRequest): - request = workstations.DeleteWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation_config] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_workstation(self, - request: Optional[Union[workstations.GetWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.Workstation: - r"""Returns the requested workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_get_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.GetWorkstationRequest, dict]): - The request object. Request message for GetWorkstation. - name (str): - Required. Name of the requested - resource. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.types.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.GetWorkstationRequest): - request = workstations.GetWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation] - - # Certain fields should be provided within 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_workstations(self, - request: Optional[Union[workstations.ListWorkstationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWorkstationsPager: - r"""Returns all Workstations using the specified - workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListWorkstationsRequest, dict]): - The request object. Request message for ListWorkstations. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationsPager: - Response message for - ListWorkstations. - 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, workstations.ListWorkstationsRequest): - request = workstations.ListWorkstationsRequest(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_workstations] - - # Certain fields should be provided within 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.ListWorkstationsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_usable_workstations(self, - request: Optional[Union[workstations.ListUsableWorkstationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUsableWorkstationsPager: - r"""Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_usable_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest, dict]): - The request object. Request message for - ListUsableWorkstations. - parent (str): - Required. Parent resource name. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsPager: - Response message for - ListUsableWorkstations. - 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, workstations.ListUsableWorkstationsRequest): - request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] - - # Certain fields should be provided within 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.ListUsableWorkstationsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation(self, - request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation: Optional[workstations.Workstation] = None, - workstation_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_create_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationRequest, dict]): - The request object. Message for creating a - CreateWorkstation. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation (google.cloud.workstations_v1beta.types.Workstation): - Required. Workstation to create. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_id (str): - Required. ID to use for the - workstation. - - This corresponds to the ``workstation_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstation, workstation_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, workstations.CreateWorkstationRequest): - request = workstations.CreateWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation is not None: - request.workstation = workstation - if workstation_id is not None: - request.workstation_id = workstation_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation] - - # Certain fields should be provided within 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation(self, - request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, - *, - workstation: Optional[workstations.Workstation] = 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, str]] = (), - ) -> operation.Operation: - r"""Updates an existing workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_update_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationRequest, dict]): - The request object. Request message for - UpdateWorkstation. - workstation (google.cloud.workstations_v1beta.types.Workstation): - Required. Workstation to update. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which - fields in the workstation configuration - should 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation, 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, workstations.UpdateWorkstationRequest): - request = workstations.UpdateWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - 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_workstation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation.name", request.workstation.name), - )), - ) - - # 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation(self, - request: Optional[Union[workstations.DeleteWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_delete_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationRequest, dict]): - The request object. Request message for - DeleteWorkstation. - name (str): - Required. Name of the workstation to - delete. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.DeleteWorkstationRequest): - request = workstations.DeleteWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def start_workstation(self, - request: Optional[Union[workstations.StartWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Starts running a workstation so that users can - connect to it. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_start_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.StartWorkstationRequest, dict]): - The request object. Request message for StartWorkstation. - name (str): - Required. Name of the workstation to - start. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.StartWorkstationRequest): - request = workstations.StartWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.start_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def stop_workstation(self, - request: Optional[Union[workstations.StopWorkstationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Stops running a workstation, reducing costs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_stop_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.StopWorkstationRequest, dict]): - The request object. Request message for StopWorkstation. - name (str): - Required. Name of the workstation to - stop. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, workstations.StopWorkstationRequest): - request = workstations.StopWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.stop_workstation] - - # Certain fields should be provided within 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def generate_access_token(self, - request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, - *, - workstation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.GenerateAccessTokenResponse: - r"""Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_generate_access_token(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest, dict]): - The request object. Request message for - GenerateAccessToken. - workstation (str): - Required. Name of the workstation for - which the access token should be - generated. - - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.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. - - Returns: - google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, workstations.GenerateAccessTokenRequest): - request = workstations.GenerateAccessTokenRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation", request.workstation), - )), - ) - - # Validate the universe 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) -> "WorkstationsClient": - 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 list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.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. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # 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.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_operations] - - # Certain fields should be provided within 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_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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.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. - Returns: - None - """ - # 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.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.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. - Returns: - None - """ - # 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.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.cancel_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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.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. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe 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_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.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. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.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. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the 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__ = ( - "WorkstationsClient", -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py deleted file mode 100644 index 35c0d313cec9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py +++ /dev/null @@ -1,702 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.workstations_v1beta.types import workstations - - -class ListWorkstationClustersPager: - """A pager for iterating through ``list_workstation_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_clusters`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstationClusters`` requests and continue to iterate - through the ``workstation_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListWorkstationClustersResponse], - request: workstations.ListWorkstationClustersRequest, - response: workstations.ListWorkstationClustersResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationClustersRequest(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[workstations.ListWorkstationClustersResponse]: - 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[workstations.WorkstationCluster]: - for page in self.pages: - yield from page.workstation_clusters - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationClustersAsyncPager: - """A pager for iterating through ``list_workstation_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_clusters`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstationClusters`` requests and continue to iterate - through the ``workstation_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` - attributes are available on the 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[workstations.ListWorkstationClustersResponse]], - request: workstations.ListWorkstationClustersRequest, - response: workstations.ListWorkstationClustersResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationClustersRequest(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[workstations.ListWorkstationClustersResponse]: - 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[workstations.WorkstationCluster]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_clusters: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationConfigsPager: - """A pager for iterating through ``list_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListWorkstationConfigsResponse], - request: workstations.ListWorkstationConfigsRequest, - response: workstations.ListWorkstationConfigsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationConfigsRequest(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[workstations.ListWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - for page in self.pages: - yield from page.workstation_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationConfigsAsyncPager: - """A pager for iterating through ``list_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` - attributes are available on the 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[workstations.ListWorkstationConfigsResponse]], - request: workstations.ListWorkstationConfigsRequest, - response: workstations.ListWorkstationConfigsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationConfigsRequest(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[workstations.ListWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationConfigsPager: - """A pager for iterating through ``list_usable_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsableWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListUsableWorkstationConfigsResponse], - request: workstations.ListUsableWorkstationConfigsRequest, - response: workstations.ListUsableWorkstationConfigsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListUsableWorkstationConfigsRequest(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[workstations.ListUsableWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - for page in self.pages: - yield from page.workstation_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationConfigsAsyncPager: - """A pager for iterating through ``list_usable_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsableWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` - attributes are available on the 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[workstations.ListUsableWorkstationConfigsResponse]], - request: workstations.ListUsableWorkstationConfigsRequest, - response: workstations.ListUsableWorkstationConfigsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListUsableWorkstationConfigsRequest(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[workstations.ListUsableWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationsPager: - """A pager for iterating through ``list_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListWorkstationsResponse], - request: workstations.ListWorkstationsRequest, - response: workstations.ListWorkstationsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationsRequest(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[workstations.ListWorkstationsResponse]: - 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[workstations.Workstation]: - for page in self.pages: - yield from page.workstations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationsAsyncPager: - """A pager for iterating through ``list_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` - attributes are available on the 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[workstations.ListWorkstationsResponse]], - request: workstations.ListWorkstationsRequest, - response: workstations.ListWorkstationsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListWorkstationsRequest(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[workstations.ListWorkstationsResponse]: - 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[workstations.Workstation]: - async def async_generator(): - async for page in self.pages: - for response in page.workstations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationsPager: - """A pager for iterating through ``list_usable_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsableWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., workstations.ListUsableWorkstationsResponse], - request: workstations.ListUsableWorkstationsRequest, - response: workstations.ListUsableWorkstationsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListUsableWorkstationsRequest(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[workstations.ListUsableWorkstationsResponse]: - 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[workstations.Workstation]: - for page in self.pages: - yield from page.workstations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationsAsyncPager: - """A pager for iterating through ``list_usable_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsableWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` - attributes are available on the 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[workstations.ListUsableWorkstationsResponse]], - request: workstations.ListUsableWorkstationsRequest, - response: workstations.ListUsableWorkstationsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = workstations.ListUsableWorkstationsRequest(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[workstations.ListUsableWorkstationsResponse]: - 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[workstations.Workstation]: - async def async_generator(): - async for page in self.pages: - for response in page.workstations: - 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-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/README.rst b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/README.rst deleted file mode 100644 index e25a7cc4b1cf..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`WorkstationsTransport` is the ABC for all transports. -- public child `WorkstationsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `WorkstationsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseWorkstationsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `WorkstationsRestTransport` 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-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py deleted file mode 100644 index 3ae547e57985..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/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 WorkstationsTransport -from .grpc import WorkstationsGrpcTransport -from .grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .rest import WorkstationsRestTransport -from .rest import WorkstationsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WorkstationsTransport]] -_transport_registry['grpc'] = WorkstationsGrpcTransport -_transport_registry['grpc_asyncio'] = WorkstationsGrpcAsyncIOTransport -_transport_registry['rest'] = WorkstationsRestTransport - -__all__ = ( - 'WorkstationsTransport', - 'WorkstationsGrpcTransport', - 'WorkstationsGrpcAsyncIOTransport', - 'WorkstationsRestTransport', - 'WorkstationsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py deleted file mode 100644 index 7b2c872c486e..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.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 abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.workstations_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.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.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class WorkstationsTransport(abc.ABC): - """Abstract transport class for Workstations.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'workstations.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: 'workstations.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_workstation_cluster: gapic_v1.method.wrap_method( - self.get_workstation_cluster, - 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_workstation_clusters: gapic_v1.method.wrap_method( - self.list_workstation_clusters, - 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.create_workstation_cluster: gapic_v1.method.wrap_method( - self.create_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_cluster: gapic_v1.method.wrap_method( - self.update_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_cluster: gapic_v1.method.wrap_method( - self.delete_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation_config: gapic_v1.method.wrap_method( - self.get_workstation_config, - 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_workstation_configs: gapic_v1.method.wrap_method( - self.list_workstation_configs, - 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_usable_workstation_configs: gapic_v1.method.wrap_method( - self.list_usable_workstation_configs, - 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.create_workstation_config: gapic_v1.method.wrap_method( - self.create_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_config: gapic_v1.method.wrap_method( - self.update_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_config: gapic_v1.method.wrap_method( - self.delete_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation: gapic_v1.method.wrap_method( - self.get_workstation, - 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_workstations: gapic_v1.method.wrap_method( - self.list_workstations, - 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_usable_workstations: gapic_v1.method.wrap_method( - self.list_usable_workstations, - 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.create_workstation: gapic_v1.method.wrap_method( - self.create_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation: gapic_v1.method.wrap_method( - self.update_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation: gapic_v1.method.wrap_method( - self.delete_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.start_workstation: gapic_v1.method.wrap_method( - self.start_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.stop_workstation: gapic_v1.method.wrap_method( - self.stop_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_access_token: gapic_v1.method.wrap_method( - self.generate_access_token, - 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_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - 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, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - 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 get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - Union[ - workstations.WorkstationCluster, - Awaitable[workstations.WorkstationCluster] - ]]: - raise NotImplementedError() - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - Union[ - workstations.ListWorkstationClustersResponse, - Awaitable[workstations.ListWorkstationClustersResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - Union[ - workstations.WorkstationConfig, - Awaitable[workstations.WorkstationConfig] - ]]: - raise NotImplementedError() - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - Union[ - workstations.ListWorkstationConfigsResponse, - Awaitable[workstations.ListWorkstationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - Union[ - workstations.ListUsableWorkstationConfigsResponse, - Awaitable[workstations.ListUsableWorkstationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - Union[ - workstations.Workstation, - Awaitable[workstations.Workstation] - ]]: - raise NotImplementedError() - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - Union[ - workstations.ListWorkstationsResponse, - Awaitable[workstations.ListWorkstationsResponse] - ]]: - raise NotImplementedError() - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - Union[ - workstations.ListUsableWorkstationsResponse, - Awaitable[workstations.ListUsableWorkstationsResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - Union[ - workstations.GenerateAccessTokenResponse, - Awaitable[workstations.GenerateAccessTokenResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'WorkstationsTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py deleted file mode 100644 index 7432aac344da..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py +++ /dev/null @@ -1,948 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO - - -class WorkstationsGrpcTransport(WorkstationsTransport): - """gRPC backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workstations.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: 'workstations.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'workstations.googleapis.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.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - workstations.WorkstationCluster]: - r"""Return a callable for the get workstation cluster method over gRPC. - - Returns the requested workstation cluster. - - Returns: - Callable[[~.GetWorkstationClusterRequest], - ~.WorkstationCluster]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstationCluster', - request_serializer=workstations.GetWorkstationClusterRequest.serialize, - response_deserializer=workstations.WorkstationCluster.deserialize, - ) - return self._stubs['get_workstation_cluster'] - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - workstations.ListWorkstationClustersResponse]: - r"""Return a callable for the list workstation clusters method over gRPC. - - Returns all workstation clusters in the specified - location. - - Returns: - Callable[[~.ListWorkstationClustersRequest], - ~.ListWorkstationClustersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: - self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstationClusters', - request_serializer=workstations.ListWorkstationClustersRequest.serialize, - response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, - ) - return self._stubs['list_workstation_clusters'] - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation cluster method over gRPC. - - Creates a new workstation cluster. - - Returns: - Callable[[~.CreateWorkstationClusterRequest], - ~.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 'create_workstation_cluster' not in self._stubs: - self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationCluster', - request_serializer=workstations.CreateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_cluster'] - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation cluster method over gRPC. - - Updates an existing workstation cluster. - - Returns: - Callable[[~.UpdateWorkstationClusterRequest], - ~.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 'update_workstation_cluster' not in self._stubs: - self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationCluster', - request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_cluster'] - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation cluster method over gRPC. - - Deletes the specified workstation cluster. - - Returns: - Callable[[~.DeleteWorkstationClusterRequest], - ~.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 'delete_workstation_cluster' not in self._stubs: - self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationCluster', - request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_cluster'] - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - workstations.WorkstationConfig]: - r"""Return a callable for the get workstation config method over gRPC. - - Returns the requested workstation configuration. - - Returns: - Callable[[~.GetWorkstationConfigRequest], - ~.WorkstationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstationConfig', - request_serializer=workstations.GetWorkstationConfigRequest.serialize, - response_deserializer=workstations.WorkstationConfig.deserialize, - ) - return self._stubs['get_workstation_config'] - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - workstations.ListWorkstationConfigsResponse]: - r"""Return a callable for the list workstation configs method over gRPC. - - Returns all workstation configurations in the - specified cluster. - - Returns: - Callable[[~.ListWorkstationConfigsRequest], - ~.ListWorkstationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: - self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstationConfigs', - request_serializer=workstations.ListWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_workstation_configs'] - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - workstations.ListUsableWorkstationConfigsResponse]: - r"""Return a callable for the list usable workstation - configs method over gRPC. - - Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - Returns: - Callable[[~.ListUsableWorkstationConfigsRequest], - ~.ListUsableWorkstationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: - self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstationConfigs', - request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_usable_workstation_configs'] - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation config method over gRPC. - - Creates a new workstation configuration. - - Returns: - Callable[[~.CreateWorkstationConfigRequest], - ~.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 'create_workstation_config' not in self._stubs: - self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationConfig', - request_serializer=workstations.CreateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_config'] - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation config method over gRPC. - - Updates an existing workstation configuration. - - Returns: - Callable[[~.UpdateWorkstationConfigRequest], - ~.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 'update_workstation_config' not in self._stubs: - self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationConfig', - request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_config'] - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation config method over gRPC. - - Deletes the specified workstation configuration. - - Returns: - Callable[[~.DeleteWorkstationConfigRequest], - ~.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 'delete_workstation_config' not in self._stubs: - self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationConfig', - request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_config'] - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - workstations.Workstation]: - r"""Return a callable for the get workstation method over gRPC. - - Returns the requested workstation. - - Returns: - Callable[[~.GetWorkstationRequest], - ~.Workstation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['get_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstation', - request_serializer=workstations.GetWorkstationRequest.serialize, - response_deserializer=workstations.Workstation.deserialize, - ) - return self._stubs['get_workstation'] - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - workstations.ListWorkstationsResponse]: - r"""Return a callable for the list workstations method over gRPC. - - Returns all Workstations using the specified - workstation configuration. - - Returns: - Callable[[~.ListWorkstationsRequest], - ~.ListWorkstationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstations' not in self._stubs: - self._stubs['list_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstations', - request_serializer=workstations.ListWorkstationsRequest.serialize, - response_deserializer=workstations.ListWorkstationsResponse.deserialize, - ) - return self._stubs['list_workstations'] - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - workstations.ListUsableWorkstationsResponse]: - r"""Return a callable for the list usable workstations method over gRPC. - - Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - Returns: - Callable[[~.ListUsableWorkstationsRequest], - ~.ListUsableWorkstationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: - self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstations', - request_serializer=workstations.ListUsableWorkstationsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, - ) - return self._stubs['list_usable_workstations'] - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation method over gRPC. - - Creates a new workstation. - - Returns: - Callable[[~.CreateWorkstationRequest], - ~.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 'create_workstation' not in self._stubs: - self._stubs['create_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstation', - request_serializer=workstations.CreateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation'] - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation method over gRPC. - - Updates an existing workstation. - - Returns: - Callable[[~.UpdateWorkstationRequest], - ~.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 'update_workstation' not in self._stubs: - self._stubs['update_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstation', - request_serializer=workstations.UpdateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation'] - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation method over gRPC. - - Deletes the specified workstation. - - Returns: - Callable[[~.DeleteWorkstationRequest], - ~.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 'delete_workstation' not in self._stubs: - self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstation', - request_serializer=workstations.DeleteWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation'] - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the start workstation method over gRPC. - - Starts running a workstation so that users can - connect to it. - - Returns: - Callable[[~.StartWorkstationRequest], - ~.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 'start_workstation' not in self._stubs: - self._stubs['start_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/StartWorkstation', - request_serializer=workstations.StartWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['start_workstation'] - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the stop workstation method over gRPC. - - Stops running a workstation, reducing costs. - - Returns: - Callable[[~.StopWorkstationRequest], - ~.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 'stop_workstation' not in self._stubs: - self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/StopWorkstation', - request_serializer=workstations.StopWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['stop_workstation'] - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - workstations.GenerateAccessTokenResponse]: - r"""Return a callable for the generate access token method over gRPC. - - Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - ~.GenerateAccessTokenResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GenerateAccessToken', - request_serializer=workstations.GenerateAccessTokenRequest.serialize, - response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @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.grpc_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 list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'WorkstationsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py deleted file mode 100644 index 168cd94b888d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py +++ /dev/null @@ -1,1180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .grpc import WorkstationsGrpcTransport - - -class WorkstationsGrpcAsyncIOTransport(WorkstationsTransport): - """gRPC AsyncIO backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'workstations.googleapis.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 = 'workstations.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: 'workstations.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - Awaitable[workstations.WorkstationCluster]]: - r"""Return a callable for the get workstation cluster method over gRPC. - - Returns the requested workstation cluster. - - Returns: - Callable[[~.GetWorkstationClusterRequest], - Awaitable[~.WorkstationCluster]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstationCluster', - request_serializer=workstations.GetWorkstationClusterRequest.serialize, - response_deserializer=workstations.WorkstationCluster.deserialize, - ) - return self._stubs['get_workstation_cluster'] - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - Awaitable[workstations.ListWorkstationClustersResponse]]: - r"""Return a callable for the list workstation clusters method over gRPC. - - Returns all workstation clusters in the specified - location. - - Returns: - Callable[[~.ListWorkstationClustersRequest], - Awaitable[~.ListWorkstationClustersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: - self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstationClusters', - request_serializer=workstations.ListWorkstationClustersRequest.serialize, - response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, - ) - return self._stubs['list_workstation_clusters'] - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation cluster method over gRPC. - - Creates a new workstation cluster. - - Returns: - Callable[[~.CreateWorkstationClusterRequest], - 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 'create_workstation_cluster' not in self._stubs: - self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationCluster', - request_serializer=workstations.CreateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_cluster'] - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation cluster method over gRPC. - - Updates an existing workstation cluster. - - Returns: - Callable[[~.UpdateWorkstationClusterRequest], - 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 'update_workstation_cluster' not in self._stubs: - self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationCluster', - request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_cluster'] - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation cluster method over gRPC. - - Deletes the specified workstation cluster. - - Returns: - Callable[[~.DeleteWorkstationClusterRequest], - 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 'delete_workstation_cluster' not in self._stubs: - self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationCluster', - request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_cluster'] - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - Awaitable[workstations.WorkstationConfig]]: - r"""Return a callable for the get workstation config method over gRPC. - - Returns the requested workstation configuration. - - Returns: - Callable[[~.GetWorkstationConfigRequest], - Awaitable[~.WorkstationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstationConfig', - request_serializer=workstations.GetWorkstationConfigRequest.serialize, - response_deserializer=workstations.WorkstationConfig.deserialize, - ) - return self._stubs['get_workstation_config'] - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - Awaitable[workstations.ListWorkstationConfigsResponse]]: - r"""Return a callable for the list workstation configs method over gRPC. - - Returns all workstation configurations in the - specified cluster. - - Returns: - Callable[[~.ListWorkstationConfigsRequest], - Awaitable[~.ListWorkstationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: - self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstationConfigs', - request_serializer=workstations.ListWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_workstation_configs'] - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - Awaitable[workstations.ListUsableWorkstationConfigsResponse]]: - r"""Return a callable for the list usable workstation - configs method over gRPC. - - Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - Returns: - Callable[[~.ListUsableWorkstationConfigsRequest], - Awaitable[~.ListUsableWorkstationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: - self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstationConfigs', - request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_usable_workstation_configs'] - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation config method over gRPC. - - Creates a new workstation configuration. - - Returns: - Callable[[~.CreateWorkstationConfigRequest], - 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 'create_workstation_config' not in self._stubs: - self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationConfig', - request_serializer=workstations.CreateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_config'] - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation config method over gRPC. - - Updates an existing workstation configuration. - - Returns: - Callable[[~.UpdateWorkstationConfigRequest], - 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 'update_workstation_config' not in self._stubs: - self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationConfig', - request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_config'] - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation config method over gRPC. - - Deletes the specified workstation configuration. - - Returns: - Callable[[~.DeleteWorkstationConfigRequest], - 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 'delete_workstation_config' not in self._stubs: - self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationConfig', - request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_config'] - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - Awaitable[workstations.Workstation]]: - r"""Return a callable for the get workstation method over gRPC. - - Returns the requested workstation. - - Returns: - Callable[[~.GetWorkstationRequest], - Awaitable[~.Workstation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['get_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstation', - request_serializer=workstations.GetWorkstationRequest.serialize, - response_deserializer=workstations.Workstation.deserialize, - ) - return self._stubs['get_workstation'] - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - Awaitable[workstations.ListWorkstationsResponse]]: - r"""Return a callable for the list workstations method over gRPC. - - Returns all Workstations using the specified - workstation configuration. - - Returns: - Callable[[~.ListWorkstationsRequest], - Awaitable[~.ListWorkstationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstations' not in self._stubs: - self._stubs['list_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstations', - request_serializer=workstations.ListWorkstationsRequest.serialize, - response_deserializer=workstations.ListWorkstationsResponse.deserialize, - ) - return self._stubs['list_workstations'] - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - Awaitable[workstations.ListUsableWorkstationsResponse]]: - r"""Return a callable for the list usable workstations method over gRPC. - - Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - Returns: - Callable[[~.ListUsableWorkstationsRequest], - Awaitable[~.ListUsableWorkstationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: - self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstations', - request_serializer=workstations.ListUsableWorkstationsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, - ) - return self._stubs['list_usable_workstations'] - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation method over gRPC. - - Creates a new workstation. - - Returns: - Callable[[~.CreateWorkstationRequest], - 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 'create_workstation' not in self._stubs: - self._stubs['create_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstation', - request_serializer=workstations.CreateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation'] - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation method over gRPC. - - Updates an existing workstation. - - Returns: - Callable[[~.UpdateWorkstationRequest], - 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 'update_workstation' not in self._stubs: - self._stubs['update_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstation', - request_serializer=workstations.UpdateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation'] - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation method over gRPC. - - Deletes the specified workstation. - - Returns: - Callable[[~.DeleteWorkstationRequest], - 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 'delete_workstation' not in self._stubs: - self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstation', - request_serializer=workstations.DeleteWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation'] - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the start workstation method over gRPC. - - Starts running a workstation so that users can - connect to it. - - Returns: - Callable[[~.StartWorkstationRequest], - 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 'start_workstation' not in self._stubs: - self._stubs['start_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/StartWorkstation', - request_serializer=workstations.StartWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['start_workstation'] - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the stop workstation method over gRPC. - - Stops running a workstation, reducing costs. - - Returns: - Callable[[~.StopWorkstationRequest], - 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 'stop_workstation' not in self._stubs: - self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/StopWorkstation', - request_serializer=workstations.StopWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['stop_workstation'] - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - Awaitable[workstations.GenerateAccessTokenResponse]]: - r"""Return a callable for the generate access token method over gRPC. - - Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - Awaitable[~.GenerateAccessTokenResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GenerateAccessToken', - request_serializer=workstations.GenerateAccessTokenRequest.serialize, - response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - 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_workstation_cluster: self._wrap_method( - self.get_workstation_cluster, - 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_workstation_clusters: self._wrap_method( - self.list_workstation_clusters, - 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.create_workstation_cluster: self._wrap_method( - self.create_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_cluster: self._wrap_method( - self.update_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_cluster: self._wrap_method( - self.delete_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation_config: self._wrap_method( - self.get_workstation_config, - 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_workstation_configs: self._wrap_method( - self.list_workstation_configs, - 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_usable_workstation_configs: self._wrap_method( - self.list_usable_workstation_configs, - 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.create_workstation_config: self._wrap_method( - self.create_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_config: self._wrap_method( - self.update_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_config: self._wrap_method( - self.delete_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation: self._wrap_method( - self.get_workstation, - 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_workstations: self._wrap_method( - self.list_workstations, - 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_usable_workstations: self._wrap_method( - self.list_usable_workstations, - 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.create_workstation: self._wrap_method( - self.create_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation: self._wrap_method( - self.update_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation: self._wrap_method( - self.delete_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.start_workstation: self._wrap_method( - self.start_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.stop_workstation: self._wrap_method( - self.stop_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_access_token: self._wrap_method( - self.generate_access_token, - 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_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @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.grpc_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 list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'WorkstationsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py deleted file mode 100644 index 66d847554284..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py +++ /dev/null @@ -1,3048 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.workstations_v1beta.types import workstations -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseWorkstationsRestTransport -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 - - -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 WorkstationsRestInterceptor: - """Interceptor for Workstations. - - 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 WorkstationsRestTransport. - - .. code-block:: python - class MyCustomWorkstationsInterceptor(WorkstationsRestInterceptor): - def pre_create_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_access_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_access_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_usable_workstation_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_usable_workstation_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_usable_workstations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_usable_workstations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstation_clusters(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstation_clusters(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstation_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstation_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_start_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_start_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stop_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stop_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - transport = WorkstationsRestTransport(interceptor=MyCustomWorkstationsInterceptor()) - client = WorkstationsClient(transport=transport) - - - """ - def pre_create_workstation(self, request: workstations.CreateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_create_workstation_cluster(self, request: workstations.CreateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_create_workstation_config(self, request: workstations.CreateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_delete_workstation(self, request: workstations.DeleteWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_delete_workstation_cluster(self, request: workstations.DeleteWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_delete_workstation_config(self, request: workstations.DeleteWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_generate_access_token(self, request: workstations.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_generate_access_token(self, response: workstations.GenerateAccessTokenResponse) -> workstations.GenerateAccessTokenResponse: - """Post-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_workstation(self, request: workstations.GetWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation(self, response: workstations.Workstation) -> workstations.Workstation: - """Post-rpc interceptor for get_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_workstation_cluster(self, request: workstations.GetWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation_cluster(self, response: workstations.WorkstationCluster) -> workstations.WorkstationCluster: - """Post-rpc interceptor for get_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_workstation_config(self, request: workstations.GetWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation_config(self, response: workstations.WorkstationConfig) -> workstations.WorkstationConfig: - """Post-rpc interceptor for get_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_usable_workstation_configs(self, request: workstations.ListUsableWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_usable_workstation_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_usable_workstation_configs(self, response: workstations.ListUsableWorkstationConfigsResponse) -> workstations.ListUsableWorkstationConfigsResponse: - """Post-rpc interceptor for list_usable_workstation_configs - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_usable_workstations(self, request: workstations.ListUsableWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_usable_workstations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_usable_workstations(self, response: workstations.ListUsableWorkstationsResponse) -> workstations.ListUsableWorkstationsResponse: - """Post-rpc interceptor for list_usable_workstations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_workstation_clusters(self, request: workstations.ListWorkstationClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationClustersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstation_clusters - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstation_clusters(self, response: workstations.ListWorkstationClustersResponse) -> workstations.ListWorkstationClustersResponse: - """Post-rpc interceptor for list_workstation_clusters - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_workstation_configs(self, request: workstations.ListWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstation_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstation_configs(self, response: workstations.ListWorkstationConfigsResponse) -> workstations.ListWorkstationConfigsResponse: - """Post-rpc interceptor for list_workstation_configs - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_workstations(self, request: workstations.ListWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstations(self, response: workstations.ListWorkstationsResponse) -> workstations.ListWorkstationsResponse: - """Post-rpc interceptor for list_workstations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_start_workstation(self, request: workstations.StartWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StartWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for start_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_start_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for start_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_stop_workstation(self, request: workstations.StopWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StopWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for stop_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_stop_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for stop_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_update_workstation(self, request: workstations.UpdateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_update_workstation_cluster(self, request: workstations.UpdateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_update_workstation_config(self, request: workstations.UpdateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations 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 Workstations server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class WorkstationsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: WorkstationsRestInterceptor - - -class WorkstationsRestTransport(_BaseWorkstationsRestTransport): - """REST backend synchronous transport for Workstations. - - Service for interacting with Cloud Workstations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'workstations.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[WorkstationsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'workstations.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 WorkstationsRestInterceptor() - 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.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta/{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="v1beta") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateWorkstation(_BaseWorkstationsRestTransport._BaseCreateWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.CreateWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.CreateWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation method over HTTP. - - Args: - request (~.workstations.CreateWorkstationRequest): - The request object. Message for creating a - CreateWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_http_options() - request, metadata = self._interceptor.pre_create_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._CreateWorkstation._get_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_create_workstation(resp) - return resp - - class _CreateWorkstationCluster(_BaseWorkstationsRestTransport._BaseCreateWorkstationCluster, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.CreateWorkstationCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.CreateWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation - cluster method over HTTP. - - Args: - request (~.workstations.CreateWorkstationClusterRequest): - The request object. Message for creating a - CreateWorkstationCluster. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_http_options() - request, metadata = self._interceptor.pre_create_workstation_cluster(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._CreateWorkstationCluster._get_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_create_workstation_cluster(resp) - return resp - - class _CreateWorkstationConfig(_BaseWorkstationsRestTransport._BaseCreateWorkstationConfig, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.CreateWorkstationConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.CreateWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation config method over HTTP. - - Args: - request (~.workstations.CreateWorkstationConfigRequest): - The request object. Message for creating a - CreateWorkstationConfig. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_http_options() - request, metadata = self._interceptor.pre_create_workstation_config(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._CreateWorkstationConfig._get_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_create_workstation_config(resp) - return resp - - class _DeleteWorkstation(_BaseWorkstationsRestTransport._BaseDeleteWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.DeleteWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.DeleteWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationRequest): - The request object. Request message for - DeleteWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_http_options() - request, metadata = self._interceptor.pre_delete_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._DeleteWorkstation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, 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_delete_workstation(resp) - return resp - - class _DeleteWorkstationCluster(_BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.DeleteWorkstationCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.DeleteWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation - cluster method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationClusterRequest): - The request object. Message for deleting a workstation - cluster. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_http_options() - request, metadata = self._interceptor.pre_delete_workstation_cluster(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._DeleteWorkstationCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, 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_delete_workstation_cluster(resp) - return resp - - class _DeleteWorkstationConfig(_BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.DeleteWorkstationConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.DeleteWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation config method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationConfigRequest): - The request object. Message for deleting a workstation - configuration. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_http_options() - request, metadata = self._interceptor.pre_delete_workstation_config(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._DeleteWorkstationConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, 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_delete_workstation_config(resp) - return resp - - class _GenerateAccessToken(_BaseWorkstationsRestTransport._BaseGenerateAccessToken, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GenerateAccessToken") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.GenerateAccessTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.GenerateAccessTokenResponse: - r"""Call the generate access token method over HTTP. - - Args: - request (~.workstations.GenerateAccessTokenRequest): - The request object. Request message for - GenerateAccessToken. - retry (google.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. - - Returns: - ~.workstations.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_http_options() - request, metadata = self._interceptor.pre_generate_access_token(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GenerateAccessToken._get_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 = workstations.GenerateAccessTokenResponse() - pb_resp = workstations.GenerateAccessTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_access_token(resp) - return resp - - class _GetWorkstation(_BaseWorkstationsRestTransport._BaseGetWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GetWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.GetWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.Workstation: - r"""Call the get workstation method over HTTP. - - Args: - request (~.workstations.GetWorkstationRequest): - The request object. Request message for GetWorkstation. - retry (google.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. - - Returns: - ~.workstations.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_http_options() - request, metadata = self._interceptor.pre_get_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GetWorkstation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.Workstation() - pb_resp = workstations.Workstation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation(resp) - return resp - - class _GetWorkstationCluster(_BaseWorkstationsRestTransport._BaseGetWorkstationCluster, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GetWorkstationCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.GetWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.WorkstationCluster: - r"""Call the get workstation cluster method over HTTP. - - Args: - request (~.workstations.GetWorkstationClusterRequest): - The request object. Request message for - GetWorkstationCluster. - retry (google.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. - - Returns: - ~.workstations.WorkstationCluster: - A workstation cluster resource in the - Cloud Workstations API. - Defines a group of workstations in a - particular region and the VPC network - they're attached to. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_http_options() - request, metadata = self._interceptor.pre_get_workstation_cluster(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GetWorkstationCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.WorkstationCluster() - pb_resp = workstations.WorkstationCluster.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation_cluster(resp) - return resp - - class _GetWorkstationConfig(_BaseWorkstationsRestTransport._BaseGetWorkstationConfig, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GetWorkstationConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.GetWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.WorkstationConfig: - r"""Call the get workstation config method over HTTP. - - Args: - request (~.workstations.GetWorkstationConfigRequest): - The request object. Request message for - GetWorkstationConfig. - retry (google.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. - - Returns: - ~.workstations.WorkstationConfig: - A workstation configuration resource in the Cloud - Workstations API. - - Workstation configurations act as templates for - workstations. The workstation configuration defines - details such as the workstation virtual machine (VM) - instance type, persistent storage, container image - defining environment, which IDE or Code Editor to use, - and more. Administrators and platform teams can also use - `Identity and Access Management - (IAM) `__ - rules to grant access to teams or to individual - developers. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_http_options() - request, metadata = self._interceptor.pre_get_workstation_config(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GetWorkstationConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.WorkstationConfig() - pb_resp = workstations.WorkstationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation_config(resp) - return resp - - class _ListUsableWorkstationConfigs(_BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListUsableWorkstationConfigs") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListUsableWorkstationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListUsableWorkstationConfigsResponse: - r"""Call the list usable workstation - configs method over HTTP. - - Args: - request (~.workstations.ListUsableWorkstationConfigsRequest): - The request object. Request message for - ListUsableWorkstationConfigs. - retry (google.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. - - Returns: - ~.workstations.ListUsableWorkstationConfigsResponse: - Response message for - ListUsableWorkstationConfigs. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_http_options() - request, metadata = self._interceptor.pre_list_usable_workstation_configs(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListUsableWorkstationConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListUsableWorkstationConfigsResponse() - pb_resp = workstations.ListUsableWorkstationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_usable_workstation_configs(resp) - return resp - - class _ListUsableWorkstations(_BaseWorkstationsRestTransport._BaseListUsableWorkstations, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListUsableWorkstations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListUsableWorkstationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListUsableWorkstationsResponse: - r"""Call the list usable workstations method over HTTP. - - Args: - request (~.workstations.ListUsableWorkstationsRequest): - The request object. Request message for - ListUsableWorkstations. - retry (google.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. - - Returns: - ~.workstations.ListUsableWorkstationsResponse: - Response message for - ListUsableWorkstations. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_http_options() - request, metadata = self._interceptor.pre_list_usable_workstations(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListUsableWorkstations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListUsableWorkstationsResponse() - pb_resp = workstations.ListUsableWorkstationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_usable_workstations(resp) - return resp - - class _ListWorkstationClusters(_BaseWorkstationsRestTransport._BaseListWorkstationClusters, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListWorkstationClusters") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListWorkstationClustersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationClustersResponse: - r"""Call the list workstation clusters method over HTTP. - - Args: - request (~.workstations.ListWorkstationClustersRequest): - The request object. Request message for - ListWorkstationClusters. - retry (google.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. - - Returns: - ~.workstations.ListWorkstationClustersResponse: - Response message for - ListWorkstationClusters. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_http_options() - request, metadata = self._interceptor.pre_list_workstation_clusters(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListWorkstationClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListWorkstationClustersResponse() - pb_resp = workstations.ListWorkstationClustersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstation_clusters(resp) - return resp - - class _ListWorkstationConfigs(_BaseWorkstationsRestTransport._BaseListWorkstationConfigs, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListWorkstationConfigs") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListWorkstationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationConfigsResponse: - r"""Call the list workstation configs method over HTTP. - - Args: - request (~.workstations.ListWorkstationConfigsRequest): - The request object. Request message for - ListWorkstationConfigs. - retry (google.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. - - Returns: - ~.workstations.ListWorkstationConfigsResponse: - Response message for - ListWorkstationConfigs. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_http_options() - request, metadata = self._interceptor.pre_list_workstation_configs(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListWorkstationConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListWorkstationConfigsResponse() - pb_resp = workstations.ListWorkstationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstation_configs(resp) - return resp - - class _ListWorkstations(_BaseWorkstationsRestTransport._BaseListWorkstations, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListWorkstations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: workstations.ListWorkstationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationsResponse: - r"""Call the list workstations method over HTTP. - - Args: - request (~.workstations.ListWorkstationsRequest): - The request object. Request message for ListWorkstations. - retry (google.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. - - Returns: - ~.workstations.ListWorkstationsResponse: - Response message for - ListWorkstations. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseListWorkstations._get_http_options() - request, metadata = self._interceptor.pre_list_workstations(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListWorkstations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListWorkstations._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListWorkstations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = workstations.ListWorkstationsResponse() - pb_resp = workstations.ListWorkstationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstations(resp) - return resp - - class _StartWorkstation(_BaseWorkstationsRestTransport._BaseStartWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.StartWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.StartWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the start workstation method over HTTP. - - Args: - request (~.workstations.StartWorkstationRequest): - The request object. Request message for StartWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_http_options() - request, metadata = self._interceptor.pre_start_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseStartWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._StartWorkstation._get_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_start_workstation(resp) - return resp - - class _StopWorkstation(_BaseWorkstationsRestTransport._BaseStopWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.StopWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.StopWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the stop workstation method over HTTP. - - Args: - request (~.workstations.StopWorkstationRequest): - The request object. Request message for StopWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_http_options() - request, metadata = self._interceptor.pre_stop_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseStopWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._StopWorkstation._get_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_stop_workstation(resp) - return resp - - class _UpdateWorkstation(_BaseWorkstationsRestTransport._BaseUpdateWorkstation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.UpdateWorkstation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.UpdateWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationRequest): - The request object. Request message for - UpdateWorkstation. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_http_options() - request, metadata = self._interceptor.pre_update_workstation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._UpdateWorkstation._get_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_update_workstation(resp) - return resp - - class _UpdateWorkstationCluster(_BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.UpdateWorkstationCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.UpdateWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation - cluster method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationClusterRequest): - The request object. Request message for - UpdateWorkstationCluster. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_http_options() - request, metadata = self._interceptor.pre_update_workstation_cluster(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._UpdateWorkstationCluster._get_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_update_workstation_cluster(resp) - return resp - - class _UpdateWorkstationConfig(_BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.UpdateWorkstationConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: workstations.UpdateWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation config method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationConfigRequest): - The request object. Request message for - UpdateWorkstationConfig. - retry (google.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. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_http_options() - request, metadata = self._interceptor.pre_update_workstation_config(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._UpdateWorkstationConfig._get_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_update_workstation_config(resp) - return resp - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - 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._CreateWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - 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._CreateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - 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._CreateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - 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._DeleteWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - 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._DeleteWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - 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._DeleteWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - workstations.GenerateAccessTokenResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - workstations.Workstation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - workstations.WorkstationCluster]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - workstations.WorkstationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - workstations.ListUsableWorkstationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListUsableWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - workstations.ListUsableWorkstationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListUsableWorkstations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - workstations.ListWorkstationClustersResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstationClusters(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - workstations.ListWorkstationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - workstations.ListWorkstationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstations(self._session, self._host, self._interceptor) # type: ignore - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - 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._StartWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - 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._StopWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - 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._UpdateWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - 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._UpdateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - 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._UpdateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseWorkstationsRestTransport._BaseGetIamPolicy, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.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. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseWorkstationsRestTransport._BaseSetIamPolicy, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.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. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._SetIamPolicy._get_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) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseWorkstationsRestTransport._BaseTestIamPermissions, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.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. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._TestIamPermissions._get_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) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseWorkstationsRestTransport._BaseCancelOperation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.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. - """ - - http_options = _BaseWorkstationsRestTransport._BaseCancelOperation._get_http_options() - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseWorkstationsRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._CancelOperation._get_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 self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseWorkstationsRestTransport._BaseDeleteOperation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(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.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.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. - """ - - http_options = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseWorkstationsRestTransport._BaseGetOperation, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._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) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseWorkstationsRestTransport._BaseListOperations, WorkstationsRestStub): - def __hash__(self): - return hash("WorkstationsRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(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.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.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. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseWorkstationsRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseWorkstationsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseWorkstationsRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - # Send the request - response = WorkstationsRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'WorkstationsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest_base.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest_base.py deleted file mode 100644 index 80e432e7895d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest_base.py +++ /dev/null @@ -1,1129 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.workstations_v1beta.types import workstations -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseWorkstationsRestTransport(WorkstationsTransport): - """Base REST backend transport for Workstations. - - 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 = 'workstations.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: 'workstations.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 _BaseCreateWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', - 'body': 'workstation', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.CreateWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateWorkstationCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationClusterId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{parent=projects/*/locations/*}/workstationClusters', - 'body': 'workstation_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.CreateWorkstationClusterRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstationCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateWorkstationConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationConfigId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', - 'body': 'workstation_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.CreateWorkstationConfigRequest.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(_BaseWorkstationsRestTransport._BaseCreateWorkstationConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.DeleteWorkstationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteWorkstationCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.DeleteWorkstationClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstationCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteWorkstationConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.DeleteWorkstationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseDeleteWorkstationConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGenerateAccessToken: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.GenerateAccessTokenRequest.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(_BaseWorkstationsRestTransport._BaseGenerateAccessToken._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.GetWorkstationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetWorkstationCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.GetWorkstationClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstationCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetWorkstationConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.GetWorkstationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseGetWorkstationConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListUsableWorkstationConfigs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListUsableWorkstationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListUsableWorkstationConfigs._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListUsableWorkstations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListUsableWorkstationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListUsableWorkstations._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkstationClusters: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*}/workstationClusters', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListWorkstationClustersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstationClusters._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkstationConfigs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListWorkstationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstationConfigs._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkstations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.ListWorkstationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseWorkstationsRestTransport._BaseListWorkstations._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStartWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.StartWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseStartWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStopWorkstation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.StopWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseStopWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateWorkstation: - 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': '/v1beta/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - 'body': 'workstation', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.UpdateWorkstationRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstation._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateWorkstationCluster: - 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': '/v1beta/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}', - 'body': 'workstation_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.UpdateWorkstationClusterRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstationCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateWorkstationConfig: - 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': '/v1beta/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - 'body': 'workstation_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = workstations.UpdateWorkstationConfigRequest.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(_BaseWorkstationsRestTransport._BaseUpdateWorkstationConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetIamPolicy: - 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': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:getIamPolicy', - }, - ] - 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 - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:setIamPolicy', - 'body': '*', - }, - ] - 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_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:testIamPermissions', - 'body': '*', - }, - ] - 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_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - 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_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseDeleteOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta/{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 - - 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': '/v1beta/{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 - - class _BaseListOperations: - 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': '/v1beta/{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__=( - '_BaseWorkstationsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py deleted file mode 100644 index 74244c2b3708..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .workstations import ( - CreateWorkstationClusterRequest, - CreateWorkstationConfigRequest, - CreateWorkstationRequest, - DeleteWorkstationClusterRequest, - DeleteWorkstationConfigRequest, - DeleteWorkstationRequest, - GenerateAccessTokenRequest, - GenerateAccessTokenResponse, - GetWorkstationClusterRequest, - GetWorkstationConfigRequest, - GetWorkstationRequest, - ListUsableWorkstationConfigsRequest, - ListUsableWorkstationConfigsResponse, - ListUsableWorkstationsRequest, - ListUsableWorkstationsResponse, - ListWorkstationClustersRequest, - ListWorkstationClustersResponse, - ListWorkstationConfigsRequest, - ListWorkstationConfigsResponse, - ListWorkstationsRequest, - ListWorkstationsResponse, - OperationMetadata, - StartWorkstationRequest, - StopWorkstationRequest, - UpdateWorkstationClusterRequest, - UpdateWorkstationConfigRequest, - UpdateWorkstationRequest, - Workstation, - WorkstationCluster, - WorkstationConfig, -) - -__all__ = ( - 'CreateWorkstationClusterRequest', - 'CreateWorkstationConfigRequest', - 'CreateWorkstationRequest', - 'DeleteWorkstationClusterRequest', - 'DeleteWorkstationConfigRequest', - 'DeleteWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GetWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'OperationMetadata', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'UpdateWorkstationClusterRequest', - 'UpdateWorkstationConfigRequest', - 'UpdateWorkstationRequest', - 'Workstation', - 'WorkstationCluster', - 'WorkstationConfig', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py deleted file mode 100644 index 3e1612aafe34..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py +++ /dev/null @@ -1,2087 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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 field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.workstations.v1beta', - manifest={ - 'WorkstationCluster', - 'WorkstationConfig', - 'Workstation', - 'GetWorkstationClusterRequest', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'CreateWorkstationClusterRequest', - 'UpdateWorkstationClusterRequest', - 'DeleteWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'CreateWorkstationConfigRequest', - 'UpdateWorkstationConfigRequest', - 'DeleteWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'CreateWorkstationRequest', - 'UpdateWorkstationRequest', - 'DeleteWorkstationRequest', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'OperationMetadata', - }, -) - - -class WorkstationCluster(proto.Message): - r"""A workstation cluster resource in the Cloud Workstations API. - - Defines a group of workstations in a particular region and the - VPC network they're attached to. - - Attributes: - name (str): - Full name of this workstation cluster. - display_name (str): - Optional. Human-readable name for this - workstation cluster. - uid (str): - Output only. A system-assigned unique - identifier for this workstation cluster. - reconciling (bool): - Output only. Indicates whether this - workstation cluster is currently being updated - to match its intended state. - annotations (MutableMapping[str, str]): - Optional. Client-specified annotations. - labels (MutableMapping[str, str]): - Optional. - `Labels `__ - that are applied to the workstation cluster and that are - also propagated to the underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - cluster was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - cluster was most recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - cluster was soft-deleted. - etag (str): - Optional. Checksum computed by the server. - May be sent on update and delete requests to - make sure that the client has an up-to-date - value before proceeding. - network (str): - Immutable. Name of the Compute Engine network - in which instances associated with this - workstation cluster will be created. - subnetwork (str): - Immutable. Name of the Compute Engine - subnetwork in which instances associated with - this workstation cluster will be created. Must - be part of the subnetwork specified for this - workstation cluster. - control_plane_ip (str): - Output only. The private IP address of the - control plane for this workstation cluster. - Workstation VMs need access to this IP address - to work with the service, so make sure that your - firewall rules allow egress from the workstation - VMs to this address. - private_cluster_config (google.cloud.workstations_v1beta.types.WorkstationCluster.PrivateClusterConfig): - Optional. Configuration for private - workstation cluster. - degraded (bool): - Output only. Whether this workstation cluster is in degraded - mode, in which case it may require user action to restore - full functionality. Details can be found in - [conditions][google.cloud.workstations.v1beta.WorkstationCluster.conditions]. - conditions (MutableSequence[google.rpc.status_pb2.Status]): - Output only. Status conditions describing the - workstation cluster's current state. - """ - - class PrivateClusterConfig(proto.Message): - r"""Configuration options for private workstation clusters. - - Attributes: - enable_private_endpoint (bool): - Immutable. Whether Workstations endpoint is - private. - cluster_hostname (str): - Output only. Hostname for the workstation - cluster. This field will be populated only when - private endpoint is enabled. To access - workstations in the workstation cluster, create - a new DNS zone mapping this domain name to an - internal IP address and a forwarding rule - mapping that address to the service attachment. - service_attachment_uri (str): - Output only. Service attachment URI for the workstation - cluster. The service attachemnt is created when private - endpoint is enabled. To access workstations in the - workstation cluster, configure access to the managed service - using `Private Service - Connect `__. - allowed_projects (MutableSequence[str]): - Optional. Additional projects that are - allowed to attach to the workstation cluster's - service attachment. By default, the workstation - cluster's project and the VPC host project (if - different) are allowed. - """ - - enable_private_endpoint: bool = proto.Field( - proto.BOOL, - number=1, - ) - cluster_hostname: str = proto.Field( - proto.STRING, - number=2, - ) - service_attachment_uri: str = proto.Field( - proto.STRING, - number=3, - ) - allowed_projects: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - 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, - ) - delete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=9, - ) - network: str = proto.Field( - proto.STRING, - number=10, - ) - subnetwork: str = proto.Field( - proto.STRING, - number=11, - ) - control_plane_ip: str = proto.Field( - proto.STRING, - number=16, - ) - private_cluster_config: PrivateClusterConfig = proto.Field( - proto.MESSAGE, - number=12, - message=PrivateClusterConfig, - ) - degraded: bool = proto.Field( - proto.BOOL, - number=13, - ) - conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=status_pb2.Status, - ) - - -class WorkstationConfig(proto.Message): - r"""A workstation configuration resource in the Cloud Workstations API. - - Workstation configurations act as templates for workstations. The - workstation configuration defines details such as the workstation - virtual machine (VM) instance type, persistent storage, container - image defining environment, which IDE or Code Editor to use, and - more. Administrators and platform teams can also use `Identity and - Access Management - (IAM) `__ rules to grant - access to teams or to individual developers. - - Attributes: - name (str): - Full name of this workstation configuration. - display_name (str): - Optional. Human-readable name for this - workstation configuration. - uid (str): - Output only. A system-assigned unique - identifier for this workstation configuration. - reconciling (bool): - Output only. Indicates whether this - workstation configuration is currently being - updated to match its intended state. - annotations (MutableMapping[str, str]): - Optional. Client-specified annotations. - labels (MutableMapping[str, str]): - Optional. - `Labels `__ - that are applied to the workstation configuration and that - are also propagated to the underlying Compute Engine - resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - configuration was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - configuration was most recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation - configuration was soft-deleted. - etag (str): - Optional. Checksum computed by the server. - May be sent on update and delete requests to - make sure that the client has an up-to-date - value before proceeding. - idle_timeout (google.protobuf.duration_pb2.Duration): - Optional. Number of seconds to wait before automatically - stopping a workstation after it last received user traffic. - - A value of ``"0s"`` indicates that Cloud Workstations VMs - created with this configuration should never time out due to - idleness. Provide - `duration `__ - terminated by ``s`` for seconds—for example, ``"7200s"`` (2 - hours). The default is ``"1200s"`` (20 minutes). - running_timeout (google.protobuf.duration_pb2.Duration): - Optional. Number of seconds that a workstation can run until - it is automatically shut down. We recommend that - workstations be shut down daily to reduce costs and so that - security updates can be applied upon restart. The - [idle_timeout][google.cloud.workstations.v1beta.WorkstationConfig.idle_timeout] - and - [running_timeout][google.cloud.workstations.v1beta.WorkstationConfig.running_timeout] - fields are independent of each other. Note that the - [running_timeout][google.cloud.workstations.v1beta.WorkstationConfig.running_timeout] - field shuts down VMs after the specified time, regardless of - whether or not the VMs are idle. - - Provide duration terminated by ``s`` for seconds—for - example, ``"54000s"`` (15 hours). Defaults to ``"43200s"`` - (12 hours). A value of ``"0s"`` indicates that workstations - using this configuration should never time out. If - [encryption_key][google.cloud.workstations.v1beta.WorkstationConfig.encryption_key] - is set, it must be greater than ``"0s"`` and less than - ``"86400s"`` (24 hours). - - Warning: A value of ``"0s"`` indicates that Cloud - Workstations VMs created with this configuration have no - maximum running time. This is strongly discouraged because - you incur costs and will not pick up security updates. - host (google.cloud.workstations_v1beta.types.WorkstationConfig.Host): - Optional. Runtime host for the workstation. - persistent_directories (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory]): - Optional. Directories to persist across - workstation sessions. - ephemeral_directories (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.EphemeralDirectory]): - Optional. Ephemeral directories which won't - persist across workstation sessions. - container (google.cloud.workstations_v1beta.types.WorkstationConfig.Container): - Optional. Container that runs upon startup - for each workstation using this workstation - configuration. - encryption_key (google.cloud.workstations_v1beta.types.WorkstationConfig.CustomerEncryptionKey): - Immutable. Encrypts resources of this - workstation configuration using a - customer-managed encryption key (CMEK). - - If specified, the boot disk of the Compute - Engine instance and the persistent disk are - encrypted using this encryption key. If this - field is not set, the disks are encrypted using - a generated key. Customer-managed encryption - keys do not protect disk metadata. - - If the customer-managed encryption key is - rotated, when the workstation instance is - stopped, the system attempts to recreate the - persistent disk with the new version of the key. - Be sure to keep older versions of the key until - the persistent disk is recreated. Otherwise, - data on the persistent disk might be lost. - - If the encryption key is revoked, the - workstation session automatically stops within 7 - hours. - - Immutable after the workstation configuration is - created. - readiness_checks (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.ReadinessCheck]): - Optional. Readiness checks to perform when - starting a workstation using this workstation - configuration. Mark a workstation as running - only after all specified readiness checks return - 200 status codes. - replica_zones (MutableSequence[str]): - Optional. Immutable. Specifies the zones used to replicate - the VM and disk resources within the region. If set, exactly - two zones within the workstation cluster's region must be - specified—for example, - ``['us-central1-a', 'us-central1-f']``. If this field is - empty, two default zones within the region are used. - - Immutable after the workstation configuration is created. - degraded (bool): - Output only. Whether this resource is degraded, in which - case it may require user action to restore full - functionality. See also the - [conditions][google.cloud.workstations.v1beta.WorkstationConfig.conditions] - field. - conditions (MutableSequence[google.rpc.status_pb2.Status]): - Output only. Status conditions describing the - current resource state. - enable_audit_agent (bool): - Optional. Whether to enable Linux ``auditd`` logging on the - workstation. When enabled, a service account must also be - specified that has ``logging.buckets.write`` permission on - the project. Operating system audit logging is distinct from - `Cloud Audit - Logs `__. - """ - - class Host(proto.Message): - r"""Runtime host for a workstation. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gce_instance (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance): - Specifies a Compute Engine instance as the - host. - - This field is a member of `oneof`_ ``config``. - """ - - class GceInstance(proto.Message): - r"""A runtime using a Compute Engine instance. - - Attributes: - machine_type (str): - Optional. The type of machine to use for VM instances—for - example, ``"e2-standard-4"``. For more information about - machine types that Cloud Workstations supports, see the list - of `available machine - types `__. - service_account (str): - Optional. The email address of the service account for Cloud - Workstations VMs created with this configuration. When - specified, be sure that the service account has - ``logginglogEntries.create`` permission on the project so it - can write logs out to Cloud Logging. If using a custom - container image, the service account must have permissions - to pull the specified image. - - If you as the administrator want to be able to ``ssh`` into - the underlying VM, you need to set this value to a service - account for which you have the ``iam.serviceAccounts.actAs`` - permission. Conversely, if you don't want anyone to be able - to ``ssh`` into the underlying VM, use a service account - where no one has that permission. - - If not set, VMs run with a service account provided by the - Cloud Workstations service, and the image must be publicly - accessible. - service_account_scopes (MutableSequence[str]): - Optional. Scopes to grant to the - [service_account][google.cloud.workstations.v1beta.WorkstationConfig.Host.GceInstance.service_account]. - Various scopes are automatically added based on feature - usage. When specified, users of workstations under this - configuration must have ``iam.serviceAccounts.actAs`` on the - service account. - tags (MutableSequence[str]): - Optional. Network tags to add to the Compute Engine VMs - backing the workstations. This option applies `network - tags `__ - to VMs created with this configuration. These network tags - enable the creation of `firewall - rules `__. - pool_size (int): - Optional. The number of VMs that the system should keep idle - so that new workstations can be started quickly for new - users. Defaults to ``0`` in the API. - pooled_instances (int): - Output only. Number of instances currently - available in the pool for faster workstation - startup. - disable_public_ip_addresses (bool): - Optional. When set to true, disables public IP addresses for - VMs. If you disable public IP addresses, you must set up - Private Google Access or Cloud NAT on your network. If you - use Private Google Access and you use - ``private.googleapis.com`` or ``restricted.googleapis.com`` - for Container Registry and Artifact Registry, make sure that - you set up DNS records for domains ``*.gcr.io`` and - ``*.pkg.dev``. Defaults to false (VMs have public IP - addresses). - enable_nested_virtualization (bool): - Optional. Whether to enable nested virtualization on Cloud - Workstations VMs created under this workstation - configuration. - - Nested virtualization lets you run virtual machine (VM) - instances inside your workstation. Before enabling nested - virtualization, consider the following important - considerations. Cloud Workstations instances are subject to - the `same restrictions as Compute Engine - instances `__: - - - **Organization policy**: projects, folders, or - organizations may be restricted from creating nested VMs - if the **Disable VM nested virtualization** constraint is - enforced in the organization policy. For more - information, see the Compute Engine section, `Checking - whether nested virtualization is - allowed `__. - - **Performance**: nested VMs might experience a 10% or - greater decrease in performance for workloads that are - CPU-bound and possibly greater than a 10% decrease for - workloads that are input/output bound. - - **Machine Type**: nested virtualization can only be - enabled on workstation configurations that specify a - [machine_type][google.cloud.workstations.v1beta.WorkstationConfig.Host.GceInstance.machine_type] - in the N1 or N2 machine series. - - **GPUs**: nested virtualization may not be enabled on - workstation configurations with accelerators. - - **Operating System**: Because `Container-Optimized - OS `__ - does not support nested virtualization, when nested - virtualization is enabled, the underlying Compute Engine - VM instances boot from an `Ubuntu - LTS `__ - image. - shielded_instance_config (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig): - Optional. A set of Compute Engine Shielded - instance options. - confidential_instance_config (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig): - Optional. A set of Compute Engine - Confidential VM instance options. - boot_disk_size_gb (int): - Optional. The size of the boot disk for the VM in gigabytes - (GB). The minimum boot disk size is ``30`` GB. Defaults to - ``50`` GB. - accelerators (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.Accelerator]): - Optional. A list of the type and count of - accelerator cards attached to the instance. - """ - - class GceShieldedInstanceConfig(proto.Message): - r"""A set of Compute Engine Shielded instance options. - - Attributes: - enable_secure_boot (bool): - Optional. Whether the instance has Secure - Boot enabled. - enable_vtpm (bool): - Optional. Whether the instance has the vTPM - enabled. - enable_integrity_monitoring (bool): - Optional. Whether the instance has integrity - monitoring enabled. - """ - - enable_secure_boot: bool = proto.Field( - proto.BOOL, - number=1, - ) - enable_vtpm: bool = proto.Field( - proto.BOOL, - number=2, - ) - enable_integrity_monitoring: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class GceConfidentialInstanceConfig(proto.Message): - r"""A set of Compute Engine Confidential VM instance options. - - Attributes: - enable_confidential_compute (bool): - Optional. Whether the instance has - confidential compute enabled. - """ - - enable_confidential_compute: bool = proto.Field( - proto.BOOL, - number=1, - ) - - class Accelerator(proto.Message): - r"""An accelerator card attached to the instance. - - Attributes: - type_ (str): - Optional. Type of accelerator resource to attach to the - instance, for example, ``"nvidia-tesla-p100"``. - count (int): - Optional. Number of accelerator cards exposed - to the instance. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - count: int = proto.Field( - proto.INT32, - number=2, - ) - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - service_account: str = proto.Field( - proto.STRING, - number=2, - ) - service_account_scopes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - pool_size: int = proto.Field( - proto.INT32, - number=5, - ) - pooled_instances: int = proto.Field( - proto.INT32, - number=12, - ) - disable_public_ip_addresses: bool = proto.Field( - proto.BOOL, - number=6, - ) - enable_nested_virtualization: bool = proto.Field( - proto.BOOL, - number=7, - ) - shielded_instance_config: 'WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig' = proto.Field( - proto.MESSAGE, - number=8, - message='WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig', - ) - confidential_instance_config: 'WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig', - ) - boot_disk_size_gb: int = proto.Field( - proto.INT32, - number=9, - ) - accelerators: MutableSequence['WorkstationConfig.Host.GceInstance.Accelerator'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='WorkstationConfig.Host.GceInstance.Accelerator', - ) - - gce_instance: 'WorkstationConfig.Host.GceInstance' = proto.Field( - proto.MESSAGE, - number=1, - oneof='config', - message='WorkstationConfig.Host.GceInstance', - ) - - class PersistentDirectory(proto.Message): - r"""A directory to persist across workstation sessions. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gce_pd (google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk): - A PersistentDirectory backed by a Compute - Engine persistent disk. - - This field is a member of `oneof`_ ``directory_type``. - mount_path (str): - Optional. Location of this directory in the - running workstation. - """ - - class GceRegionalPersistentDisk(proto.Message): - r"""A PersistentDirectory backed by a Compute Engine regional persistent - disk. The - [persistent_directories][google.cloud.workstations.v1beta.WorkstationConfig.persistent_directories] - field is repeated, but it may contain only one entry. It creates a - `persistent - disk `__ - that mounts to the workstation VM at ``/home`` when the session - starts and detaches when the session ends. If this field is empty, - workstations created with this configuration do not have a - persistent home directory. - - Attributes: - size_gb (int): - Optional. The GB capacity of a persistent home directory for - each workstation created with this configuration. Must be - empty if - [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.source_snapshot] - is set. - - Valid values are ``10``, ``50``, ``100``, ``200``, ``500``, - or ``1000``. Defaults to ``200``. If less than ``200`` GB, - the - [disk_type][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.disk_type] - must be ``"pd-balanced"`` or ``"pd-ssd"``. - fs_type (str): - Optional. Type of file system that the disk should be - formatted with. The workstation image must support this file - system type. Must be empty if - [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.source_snapshot] - is set. Defaults to ``"ext4"``. - disk_type (str): - Optional. The `type of the persistent - disk `__ - for the home directory. Defaults to ``"pd-standard"``. - source_snapshot (str): - Optional. Name of the snapshot to use as the source for the - disk. If set, - [size_gb][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.size_gb] - and - [fs_type][google.cloud.workstations.v1beta.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.fs_type] - must be empty. - reclaim_policy (google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy): - Optional. Whether the persistent disk should be deleted when - the workstation is deleted. Valid values are ``DELETE`` and - ``RETAIN``. Defaults to ``DELETE``. - """ - class ReclaimPolicy(proto.Enum): - r"""Value representing what should happen to the disk after the - workstation is deleted. - - Values: - RECLAIM_POLICY_UNSPECIFIED (0): - Do not use. - DELETE (1): - Delete the persistent disk when deleting the - workstation. - RETAIN (2): - Keep the persistent disk when deleting the - workstation. An administrator must manually - delete the disk. - """ - RECLAIM_POLICY_UNSPECIFIED = 0 - DELETE = 1 - RETAIN = 2 - - size_gb: int = proto.Field( - proto.INT32, - number=1, - ) - fs_type: str = proto.Field( - proto.STRING, - number=2, - ) - disk_type: str = proto.Field( - proto.STRING, - number=3, - ) - source_snapshot: str = proto.Field( - proto.STRING, - number=5, - ) - reclaim_policy: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy' = proto.Field( - proto.ENUM, - number=4, - enum='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy', - ) - - gce_pd: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk' = proto.Field( - proto.MESSAGE, - number=2, - oneof='directory_type', - message='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk', - ) - mount_path: str = proto.Field( - proto.STRING, - number=1, - ) - - class EphemeralDirectory(proto.Message): - r"""An ephemeral directory which won't persist across workstation - sessions. It is freshly created on every workstation start - operation. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gce_pd (google.cloud.workstations_v1beta.types.WorkstationConfig.EphemeralDirectory.GcePersistentDisk): - An EphemeralDirectory backed by a Compute - Engine persistent disk. - - This field is a member of `oneof`_ ``directory_type``. - mount_path (str): - Required. Location of this directory in the - running workstation. - """ - - class GcePersistentDisk(proto.Message): - r"""An EphemeralDirectory is backed by a Compute Engine - persistent disk. - - Attributes: - disk_type (str): - Optional. Type of the disk to use. Defaults to - ``"pd-standard"``. - source_snapshot (str): - Optional. Name of the snapshot to use as the source for the - disk. Must be empty if - [source_image][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_image] - is set. Updating - [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_snapshot] - will update content in the ephemeral directory after the - workstation is restarted. This field is mutable. - source_image (str): - Optional. Name of the disk image to use as the source for - the disk. Must be empty if - [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_snapshot] - is set. Updating - [source_image][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_image] - will update content in the ephemeral directory after the - workstation is restarted. This field is mutable. - read_only (bool): - Optional. Whether the disk is read only. If true, the disk - may be shared by multiple VMs and - [source_snapshot][google.cloud.workstations.v1beta.WorkstationConfig.EphemeralDirectory.GcePersistentDisk.source_snapshot] - must be set. - """ - - disk_type: str = proto.Field( - proto.STRING, - number=1, - ) - source_snapshot: str = proto.Field( - proto.STRING, - number=2, - ) - source_image: str = proto.Field( - proto.STRING, - number=3, - ) - read_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - gce_pd: 'WorkstationConfig.EphemeralDirectory.GcePersistentDisk' = proto.Field( - proto.MESSAGE, - number=3, - oneof='directory_type', - message='WorkstationConfig.EphemeralDirectory.GcePersistentDisk', - ) - mount_path: str = proto.Field( - proto.STRING, - number=1, - ) - - class Container(proto.Message): - r"""A Docker container. - - Attributes: - image (str): - Optional. A Docker container image that defines a custom - environment. - - Cloud Workstations provides a number of `preconfigured - images `__, - but you can create your own `custom container - images `__. - If using a private image, the - ``host.gceInstance.serviceAccount`` field must be specified - in the workstation configuration and must have permission to - pull the specified image. Otherwise, the image must be - publicly accessible. - command (MutableSequence[str]): - Optional. If set, overrides the default - ENTRYPOINT specified by the image. - args (MutableSequence[str]): - Optional. Arguments passed to the entrypoint. - env (MutableMapping[str, str]): - Optional. Environment variables passed to the - container's entrypoint. - working_dir (str): - Optional. If set, overrides the default DIR - specified by the image. - run_as_user (int): - Optional. If set, overrides the USER - specified in the image with the given uid. - """ - - image: str = proto.Field( - proto.STRING, - number=1, - ) - command: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - env: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - working_dir: str = proto.Field( - proto.STRING, - number=5, - ) - run_as_user: int = proto.Field( - proto.INT32, - number=6, - ) - - class CustomerEncryptionKey(proto.Message): - r"""A customer-managed encryption key (CMEK) for the Compute Engine - resources of the associated workstation configuration. Specify the - name of your Cloud KMS encryption key and the default service - account. We recommend that you use a separate service account and - follow `Cloud KMS best - practices `__. - - Attributes: - kms_key (str): - Immutable. The name of the Google Cloud KMS encryption key. - For example, - ``"projects/PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY_NAME"``. - The key must be in the same region as the workstation - configuration. - kms_key_service_account (str): - Immutable. The service account to use with the specified KMS - key. We recommend that you use a separate service account - and follow KMS best practices. For more information, see - `Separation of - duties `__ - and ``gcloud kms keys add-iam-policy-binding`` - ```--member`` `__. - """ - - kms_key: str = proto.Field( - proto.STRING, - number=1, - ) - kms_key_service_account: str = proto.Field( - proto.STRING, - number=2, - ) - - class ReadinessCheck(proto.Message): - r"""A readiness check to be performed on a workstation. - - Attributes: - path (str): - Optional. Path to which the request should be - sent. - port (int): - Optional. Port to which the request should be - sent. - """ - - path: str = proto.Field( - proto.STRING, - number=1, - ) - port: int = proto.Field( - proto.INT32, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=18, - ) - 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, - ) - delete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=9, - ) - idle_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=10, - message=duration_pb2.Duration, - ) - running_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=11, - message=duration_pb2.Duration, - ) - host: Host = proto.Field( - proto.MESSAGE, - number=12, - message=Host, - ) - persistent_directories: MutableSequence[PersistentDirectory] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=PersistentDirectory, - ) - ephemeral_directories: MutableSequence[EphemeralDirectory] = proto.RepeatedField( - proto.MESSAGE, - number=22, - message=EphemeralDirectory, - ) - container: Container = proto.Field( - proto.MESSAGE, - number=14, - message=Container, - ) - encryption_key: CustomerEncryptionKey = proto.Field( - proto.MESSAGE, - number=17, - message=CustomerEncryptionKey, - ) - readiness_checks: MutableSequence[ReadinessCheck] = proto.RepeatedField( - proto.MESSAGE, - number=19, - message=ReadinessCheck, - ) - replica_zones: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=23, - ) - degraded: bool = proto.Field( - proto.BOOL, - number=15, - ) - conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=16, - message=status_pb2.Status, - ) - enable_audit_agent: bool = proto.Field( - proto.BOOL, - number=20, - ) - - -class Workstation(proto.Message): - r"""A single instance of a developer workstation with its own - persistent storage. - - Attributes: - name (str): - Full name of this workstation. - display_name (str): - Optional. Human-readable name for this - workstation. - uid (str): - Output only. A system-assigned unique - identifier for this workstation. - reconciling (bool): - Output only. Indicates whether this - workstation is currently being updated to match - its intended state. - annotations (MutableMapping[str, str]): - Optional. Client-specified annotations. - labels (MutableMapping[str, str]): - Optional. - `Labels `__ - that are applied to the workstation and that are also - propagated to the underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation was - most recently updated. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation was - most recently successfully started, regardless - of the workstation's initial state. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this workstation was - soft-deleted. - etag (str): - Optional. Checksum computed by the server. - May be sent on update and delete requests to - make sure that the client has an up-to-date - value before proceeding. - state (google.cloud.workstations_v1beta.types.Workstation.State): - Output only. Current state of the - workstation. - host (str): - Output only. Host to which clients can send HTTPS traffic - that will be received by the workstation. Authorized traffic - will be received to the workstation as HTTP on port 80. To - send traffic to a different port, clients may prefix the - host with the destination port in the format - ``{port}-{host}``. - env (MutableMapping[str, str]): - Optional. Environment variables passed to the - workstation container's entrypoint. - """ - class State(proto.Enum): - r"""Whether a workstation is running and ready to receive user - requests. - - Values: - STATE_UNSPECIFIED (0): - Do not use. - STATE_STARTING (1): - The workstation is not yet ready to accept - requests from users but will be soon. - STATE_RUNNING (2): - The workstation is ready to accept requests - from users. - STATE_STOPPING (3): - The workstation is being stopped. - STATE_STOPPED (4): - The workstation is stopped and will not be - able to receive requests until it is started. - """ - STATE_UNSPECIFIED = 0 - STATE_STARTING = 1 - STATE_RUNNING = 2 - STATE_STOPPING = 3 - STATE_STOPPED = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=13, - ) - 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, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=14, - message=timestamp_pb2.Timestamp, - ) - delete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=9, - ) - state: State = proto.Field( - proto.ENUM, - number=10, - enum=State, - ) - host: str = proto.Field( - proto.STRING, - number=11, - ) - env: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=12, - ) - - -class GetWorkstationClusterRequest(proto.Message): - r"""Request message for GetWorkstationCluster. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationClustersRequest(proto.Message): - r"""Request message for ListWorkstationClusters. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListWorkstationClustersResponse(proto.Message): - r"""Response message for ListWorkstationClusters. - - Attributes: - workstation_clusters (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationCluster]): - The requested workstation clusters. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_clusters: MutableSequence['WorkstationCluster'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationCluster', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationClusterRequest(proto.Message): - r"""Message for creating a CreateWorkstationCluster. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_cluster_id (str): - Required. ID to use for the workstation - cluster. - workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): - Required. Workstation cluster to create. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_cluster_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation_cluster: 'WorkstationCluster' = proto.Field( - proto.MESSAGE, - number=3, - message='WorkstationCluster', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationClusterRequest(proto.Message): - r"""Request message for UpdateWorkstationCluster. - - Attributes: - workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): - Required. Workstation cluster to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask that specifies which fields in - the workstation cluster should be updated. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - allow_missing (bool): - Optional. If set, and the workstation cluster is not found, - a new workstation cluster will be created. In this - situation, update_mask is ignored. - """ - - workstation_cluster: 'WorkstationCluster' = proto.Field( - proto.MESSAGE, - number=1, - message='WorkstationCluster', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationClusterRequest(proto.Message): - r"""Message for deleting a workstation cluster. - - Attributes: - name (str): - Required. Name of the workstation cluster to - delete. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not apply it. - etag (str): - Optional. If set, the request will be - rejected if the latest version of the - workstation cluster on the server does not have - this ETag. - force (bool): - Optional. If set, any workstation - configurations and workstations in the - workstation cluster are also deleted. Otherwise, - the request only works if the workstation - cluster has no configurations or workstations. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - force: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetWorkstationConfigRequest(proto.Message): - r"""Request message for GetWorkstationConfig. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationConfigsRequest(proto.Message): - r"""Request message for ListWorkstationConfigs. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListWorkstationConfigsResponse(proto.Message): - r"""Response message for ListWorkstationConfigs. - - Attributes: - workstation_configs (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig]): - The requested configs. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationConfigsRequest(proto.Message): - r"""Request message for ListUsableWorkstationConfigs. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListUsableWorkstationConfigsResponse(proto.Message): - r"""Response message for ListUsableWorkstationConfigs. - - Attributes: - workstation_configs (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig]): - The requested configs. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationConfigRequest(proto.Message): - r"""Message for creating a CreateWorkstationConfig. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_config_id (str): - Required. ID to use for the workstation - configuration. - workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): - Required. Config to create. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_config_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation_config: 'WorkstationConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='WorkstationConfig', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationConfigRequest(proto.Message): - r"""Request message for UpdateWorkstationConfig. - - Attributes: - workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): - Required. Config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which fields in the - workstation configuration should be updated. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - allow_missing (bool): - Optional. If set and the workstation configuration is not - found, a new workstation configuration will be created. In - this situation, update_mask is ignored. - """ - - workstation_config: 'WorkstationConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationConfigRequest(proto.Message): - r"""Message for deleting a workstation configuration. - - Attributes: - name (str): - Required. Name of the workstation - configuration to delete. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - etag (str): - Optional. If set, the request is rejected if - the latest version of the workstation - configuration on the server does not have this - ETag. - force (bool): - Optional. If set, any workstations in the - workstation configuration are also deleted. - Otherwise, the request works only if the - workstation configuration has no workstations. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - force: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetWorkstationRequest(proto.Message): - r"""Request message for GetWorkstation. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationsRequest(proto.Message): - r"""Request message for ListWorkstations. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListWorkstationsResponse(proto.Message): - r"""Response message for ListWorkstations. - - Attributes: - workstations (MutableSequence[google.cloud.workstations_v1beta.types.Workstation]): - The requested workstations. - next_page_token (str): - Optional. Token to retrieve the next page of - results, or empty if there are no more results - in the list. - unreachable (MutableSequence[str]): - Optional. Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstations: MutableSequence['Workstation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workstation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationsRequest(proto.Message): - r"""Request message for ListUsableWorkstations. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Optional. Maximum number of items to return. - page_token (str): - Optional. next_page_token value returned from a previous - List request, if any. - """ - - 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 ListUsableWorkstationsResponse(proto.Message): - r"""Response message for ListUsableWorkstations. - - Attributes: - workstations (MutableSequence[google.cloud.workstations_v1beta.types.Workstation]): - The requested workstations. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstations: MutableSequence['Workstation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workstation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationRequest(proto.Message): - r"""Message for creating a CreateWorkstation. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_id (str): - Required. ID to use for the workstation. - workstation (google.cloud.workstations_v1beta.types.Workstation): - Required. Workstation to create. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation: 'Workstation' = proto.Field( - proto.MESSAGE, - number=3, - message='Workstation', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationRequest(proto.Message): - r"""Request message for UpdateWorkstation. - - Attributes: - workstation (google.cloud.workstations_v1beta.types.Workstation): - Required. Workstation to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which fields in the - workstation configuration should be updated. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - allow_missing (bool): - Optional. If set and the workstation configuration is not - found, a new workstation configuration is created. In this - situation, update_mask is ignored. - """ - - workstation: 'Workstation' = proto.Field( - proto.MESSAGE, - number=1, - message='Workstation', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationRequest(proto.Message): - r"""Request message for DeleteWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to delete. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - etag (str): - Optional. If set, the request will be - rejected if the latest version of the - workstation on the server does not have this - ETag. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - - -class StartWorkstationRequest(proto.Message): - r"""Request message for StartWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to start. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - etag (str): - Optional. If set, the request will be - rejected if the latest version of the - workstation on the server does not have this - ETag. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - - -class StopWorkstationRequest(proto.Message): - r"""Request message for StopWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to stop. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not actually apply - it. - etag (str): - Optional. If set, the request will be - rejected if the latest version of the - workstation on the server does not have this - ETag. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GenerateAccessTokenRequest(proto.Message): - r"""Request message for GenerateAccessToken. - - 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: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Desired expiration time of the access token. - This value must be at most 24 hours in the - future. If a value is not specified, the token's - expiration time will be set to a default value - of 1 hour in the future. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Desired lifetime duration of the access - token. This value must be at most 24 hours. If a - value is not specified, the token's lifetime - will be set to a default value of 1 hour. - - This field is a member of `oneof`_ ``expiration``. - workstation (str): - Required. Name of the workstation for which - the access token should be generated. - """ - - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - oneof='expiration', - message=duration_pb2.Duration, - ) - workstation: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateAccessTokenResponse(proto.Message): - r"""Response message for GenerateAccessToken. - - Attributes: - access_token (str): - The generated bearer access token. To use this token, - include it in an Authorization header of an HTTP request - sent to the associated workstation's hostname—for example, - ``Authorization: Bearer ``. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the generated token will - expire. - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class OperationMetadata(proto.Message): - r"""Metadata for long-running operations. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time that the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time that the operation finished - running. - target (str): - Output only. Server-defined resource path for - the target of the operation. - verb (str): - Output only. Name of the verb executed by the - operation. - status_message (str): - Output only. Human-readable status of the - operation, if any. - requested_cancellation (bool): - Output only. Identifies whether the user has - requested cancellation of the operation. - api_version (str): - Output only. API version used to start the - operation. - """ - - create_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, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini b/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py b/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py deleted file mode 100644 index 387cadc75af2..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations' - -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/cloud/workstations_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/cloud/workstations_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-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json deleted file mode 100644 index 8afcd1793b5c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json +++ /dev/null @@ -1,3307 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.workstations.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-cloud-workstations", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" - }, - { - "name": "workstation_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation_cluster" - }, - "description": "Sample for CreateWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_create_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_create_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" - }, - { - "name": "workstation_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation_cluster" - }, - "description": "Sample for CreateWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" - }, - { - "name": "workstation_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation_config" - }, - "description": "Sample for CreateWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_create_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_create_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" - }, - { - "name": "workstation_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation_config" - }, - "description": "Sample for CreateWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_create_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_create_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1beta.types.Workstation" - }, - { - "name": "workstation_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation" - }, - "description": "Sample for CreateWorkstation", - "file": "workstations_v1beta_generated_workstations_create_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstation_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_create_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1beta.types.Workstation" - }, - { - "name": "workstation_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation" - }, - "description": "Sample for CreateWorkstation", - "file": "workstations_v1beta_generated_workstations_create_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstation_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_create_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_workstation_cluster" - }, - "description": "Sample for DeleteWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_workstation_cluster" - }, - "description": "Sample for DeleteWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_workstation_config" - }, - "description": "Sample for DeleteWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_delete_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_delete_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_workstation_config" - }, - "description": "Sample for DeleteWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_delete_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_delete_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_workstation" - }, - "description": "Sample for DeleteWorkstation", - "file": "workstations_v1beta_generated_workstations_delete_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstation_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_delete_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_workstation" - }, - "description": "Sample for DeleteWorkstation", - "file": "workstations_v1beta_generated_workstations_delete_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstation_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_delete_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.generate_access_token", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GenerateAccessToken", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest" - }, - { - "name": "workstation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "workstations_v1beta_generated_workstations_generate_access_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GenerateAccessToken_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": "workstations_v1beta_generated_workstations_generate_access_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.generate_access_token", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GenerateAccessToken", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest" - }, - { - "name": "workstation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "workstations_v1beta_generated_workstations_generate_access_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GenerateAccessToken_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": "workstations_v1beta_generated_workstations_generate_access_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.WorkstationCluster", - "shortName": "get_workstation_cluster" - }, - "description": "Sample for GetWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_get_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationCluster_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": "workstations_v1beta_generated_workstations_get_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.WorkstationCluster", - "shortName": "get_workstation_cluster" - }, - "description": "Sample for GetWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationCluster_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": "workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.WorkstationConfig", - "shortName": "get_workstation_config" - }, - "description": "Sample for GetWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_get_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationConfig_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": "workstations_v1beta_generated_workstations_get_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.WorkstationConfig", - "shortName": "get_workstation_config" - }, - "description": "Sample for GetWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_get_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationConfig_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": "workstations_v1beta_generated_workstations_get_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.Workstation", - "shortName": "get_workstation" - }, - "description": "Sample for GetWorkstation", - "file": "workstations_v1beta_generated_workstations_get_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstation_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": "workstations_v1beta_generated_workstations_get_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.Workstation", - "shortName": "get_workstation" - }, - "description": "Sample for GetWorkstation", - "file": "workstations_v1beta_generated_workstations_get_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstation_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": "workstations_v1beta_generated_workstations_get_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_usable_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager", - "shortName": "list_usable_workstation_configs" - }, - "description": "Sample for ListUsableWorkstationConfigs", - "file": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_usable_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsPager", - "shortName": "list_usable_workstation_configs" - }, - "description": "Sample for ListUsableWorkstationConfigs", - "file": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_usable_workstations", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsAsyncPager", - "shortName": "list_usable_workstations" - }, - "description": "Sample for ListUsableWorkstations", - "file": "workstations_v1beta_generated_workstations_list_usable_workstations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstations_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": "workstations_v1beta_generated_workstations_list_usable_workstations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_usable_workstations", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsPager", - "shortName": "list_usable_workstations" - }, - "description": "Sample for ListUsableWorkstations", - "file": "workstations_v1beta_generated_workstations_list_usable_workstations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstations_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": "workstations_v1beta_generated_workstations_list_usable_workstations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstation_clusters", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationClusters", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersAsyncPager", - "shortName": "list_workstation_clusters" - }, - "description": "Sample for ListWorkstationClusters", - "file": "workstations_v1beta_generated_workstations_list_workstation_clusters_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationClusters_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": "workstations_v1beta_generated_workstations_list_workstation_clusters_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstation_clusters", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationClusters", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersPager", - "shortName": "list_workstation_clusters" - }, - "description": "Sample for ListWorkstationClusters", - "file": "workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationClusters_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": "workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsAsyncPager", - "shortName": "list_workstation_configs" - }, - "description": "Sample for ListWorkstationConfigs", - "file": "workstations_v1beta_generated_workstations_list_workstation_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_workstation_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsPager", - "shortName": "list_workstation_configs" - }, - "description": "Sample for ListWorkstationConfigs", - "file": "workstations_v1beta_generated_workstations_list_workstation_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_workstation_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstations", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationsAsyncPager", - "shortName": "list_workstations" - }, - "description": "Sample for ListWorkstations", - "file": "workstations_v1beta_generated_workstations_list_workstations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstations_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": "workstations_v1beta_generated_workstations_list_workstations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstations", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.services.workstations.pagers.ListWorkstationsPager", - "shortName": "list_workstations" - }, - "description": "Sample for ListWorkstations", - "file": "workstations_v1beta_generated_workstations_list_workstations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstations_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": "workstations_v1beta_generated_workstations_list_workstations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.start_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.StartWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "StartWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.StartWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "start_workstation" - }, - "description": "Sample for StartWorkstation", - "file": "workstations_v1beta_generated_workstations_start_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_StartWorkstation_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_start_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.start_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.StartWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "StartWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.StartWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "start_workstation" - }, - "description": "Sample for StartWorkstation", - "file": "workstations_v1beta_generated_workstations_start_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_StartWorkstation_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_start_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.stop_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.StopWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "StopWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.StopWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "stop_workstation" - }, - "description": "Sample for StopWorkstation", - "file": "workstations_v1beta_generated_workstations_stop_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_StopWorkstation_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_stop_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.stop_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.StopWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "StopWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.StopWorkstationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "stop_workstation" - }, - "description": "Sample for StopWorkstation", - "file": "workstations_v1beta_generated_workstations_stop_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_StopWorkstation_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_stop_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_workstation_cluster" - }, - "description": "Sample for UpdateWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_update_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_update_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_workstation_cluster" - }, - "description": "Sample for UpdateWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_workstation_config" - }, - "description": "Sample for UpdateWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_update_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_update_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_workstation_config" - }, - "description": "Sample for UpdateWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_update_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_update_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationRequest" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1beta.types.Workstation" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_workstation" - }, - "description": "Sample for UpdateWorkstation", - "file": "workstations_v1beta_generated_workstations_update_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstation_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_update_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationRequest" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1beta.types.Workstation" - }, - { - "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, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_workstation" - }, - "description": "Sample for UpdateWorkstation", - "file": "workstations_v1beta_generated_workstations_update_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstation_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "workstations_v1beta_generated_workstations_update_workstation_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py deleted file mode 100644 index 25d6d1cc1386..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_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 CreateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_create_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py deleted file mode 100644 index 4277893c4542..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_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 CreateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py deleted file mode 100644 index 8e08528d07eb..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_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 CreateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py deleted file mode 100644 index adb0fe31f47a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_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 CreateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_create_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py deleted file mode 100644 index d9241dd3b035..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_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 CreateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_create_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py deleted file mode 100644 index 51686d435e86..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_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 CreateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_create_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py deleted file mode 100644 index bbff0682f847..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_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 DeleteWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_delete_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py deleted file mode 100644 index 16ab313463d2..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_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 DeleteWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py deleted file mode 100644 index 390eb9fc620e..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_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 DeleteWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py deleted file mode 100644 index 292a8d5e3206..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_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 DeleteWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_delete_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py deleted file mode 100644 index 12e436dded63..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_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 DeleteWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_delete_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py deleted file mode 100644 index 10d26495a739..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_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 DeleteWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_delete_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py deleted file mode 100644 index 73f954930a43..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_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 GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GenerateAccessToken_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_generate_access_token(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GenerateAccessToken_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py deleted file mode 100644 index 32d570bf51b4..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_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 GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GenerateAccessToken_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_generate_access_token(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GenerateAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py deleted file mode 100644 index 6ba46df98486..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_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 GetWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_get_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py deleted file mode 100644 index 8c9ce3be54d6..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_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 GetWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py deleted file mode 100644 index cd3baaea4660..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_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 GetWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py deleted file mode 100644 index 671253c19d41..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_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 GetWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_get_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_config(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py deleted file mode 100644 index 1c83ac5b50b0..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_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 GetWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_get_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_config(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py deleted file mode 100644 index 3e6624180a0b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_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 GetWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_get_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py deleted file mode 100644 index e177763630e6..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_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 ListUsableWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py deleted file mode 100644 index 366e2c534144..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_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 ListUsableWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py deleted file mode 100644 index f3ec6f0e4786..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_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 ListUsableWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListUsableWorkstations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_usable_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListUsableWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py deleted file mode 100644 index afcb460801be..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_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 ListUsableWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListUsableWorkstations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_usable_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListUsableWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py deleted file mode 100644 index 335db75c2249..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_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 ListWorkstationClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstationClusters_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstationClusters_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py deleted file mode 100644 index 2b80a5c40ef7..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_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 ListWorkstationClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstationClusters_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstationClusters_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py deleted file mode 100644 index 0616e10bc7c6..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_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 ListWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py deleted file mode 100644 index 2c6f221ef80c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_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 ListWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py deleted file mode 100644 index d62698ab6d95..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_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 ListWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py deleted file mode 100644 index c16a71301682..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_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 ListWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py deleted file mode 100644 index 07ed7765cb84..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_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 StartWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_StartWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_start_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_StartWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py deleted file mode 100644 index 682464e81f61..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_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 StartWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_StartWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_start_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_StartWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py deleted file mode 100644 index 963d2cfbdc72..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_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 StopWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_StopWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_stop_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_StopWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py deleted file mode 100644 index 0f3a6326f15a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_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 StopWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_StopWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_stop_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_StopWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py deleted file mode 100644 index 3d2ecb5c9e15..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_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 UpdateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_update_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py deleted file mode 100644 index 5f707487e718..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_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 UpdateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py deleted file mode 100644 index 3cea9c289e5b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_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 UpdateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py deleted file mode 100644 index 0f94cb324602..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_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 UpdateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_update_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py deleted file mode 100644 index 95eb95f64b2c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_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 UpdateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_update_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py deleted file mode 100644 index 74719a00dbc8..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_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 UpdateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_update_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py b/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py deleted file mode 100644 index d5f36b76dcbd..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py +++ /dev/null @@ -1,195 +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 workstationsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_workstation': ('parent', 'workstation_id', 'workstation', 'validate_only', ), - 'create_workstation_cluster': ('parent', 'workstation_cluster_id', 'workstation_cluster', 'validate_only', ), - 'create_workstation_config': ('parent', 'workstation_config_id', 'workstation_config', 'validate_only', ), - 'delete_workstation': ('name', 'validate_only', 'etag', ), - 'delete_workstation_cluster': ('name', 'validate_only', 'etag', 'force', ), - 'delete_workstation_config': ('name', 'validate_only', 'etag', 'force', ), - 'generate_access_token': ('workstation', 'expire_time', 'ttl', ), - 'get_workstation': ('name', ), - 'get_workstation_cluster': ('name', ), - 'get_workstation_config': ('name', ), - 'list_usable_workstation_configs': ('parent', 'page_size', 'page_token', ), - 'list_usable_workstations': ('parent', 'page_size', 'page_token', ), - 'list_workstation_clusters': ('parent', 'page_size', 'page_token', ), - 'list_workstation_configs': ('parent', 'page_size', 'page_token', ), - 'list_workstations': ('parent', 'page_size', 'page_token', ), - 'start_workstation': ('name', 'validate_only', 'etag', ), - 'stop_workstation': ('name', 'validate_only', 'etag', ), - 'update_workstation': ('workstation', 'update_mask', 'validate_only', 'allow_missing', ), - 'update_workstation_cluster': ('workstation_cluster', 'update_mask', 'validate_only', 'allow_missing', ), - 'update_workstation_config': ('workstation_config', 'update_mask', 'validate_only', 'allow_missing', ), - } - - 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=workstationsCallTransformer(), -): - """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 workstations 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-cloud-workstations/v1beta/setup.py b/owl-bot-staging/google-cloud-workstations/v1beta/setup.py deleted file mode 100644 index 6106efcf5486..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations' - - -description = "Google Cloud Workstations API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/workstations/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", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations" - -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-cloud-workstations/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workstations/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-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_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-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py deleted file mode 100644 index 3f801a885d70..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py +++ /dev/null @@ -1,17999 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cloud.location import locations_pb2 -from google.cloud.workstations_v1beta.services.workstations import WorkstationsAsyncClient -from google.cloud.workstations_v1beta.services.workstations import WorkstationsClient -from google.cloud.workstations_v1beta.services.workstations import pagers -from google.cloud.workstations_v1beta.services.workstations import transports -from google.cloud.workstations_v1beta.types import workstations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import google.auth - - -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 WorkstationsClient._get_default_mtls_endpoint(None) is None - assert WorkstationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert WorkstationsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert WorkstationsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert WorkstationsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - WorkstationsClient._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 WorkstationsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert WorkstationsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert WorkstationsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - WorkstationsClient._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 WorkstationsClient._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 WorkstationsClient._get_client_cert_source(None, False) is None - assert WorkstationsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert WorkstationsClient._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 WorkstationsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert WorkstationsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = WorkstationsClient._DEFAULT_UNIVERSE - default_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert WorkstationsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert WorkstationsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT - assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "always") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT - assert WorkstationsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WorkstationsClient.DEFAULT_MTLS_ENDPOINT - assert WorkstationsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert WorkstationsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - WorkstationsClient._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 WorkstationsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert WorkstationsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert WorkstationsClient._get_universe_domain(None, None) == WorkstationsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - WorkstationsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (WorkstationsClient, "grpc"), - (WorkstationsAsyncClient, "grpc_asyncio"), - (WorkstationsClient, "rest"), -]) -def test_workstations_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 == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workstations.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WorkstationsGrpcTransport, "grpc"), - (transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.WorkstationsRestTransport, "rest"), -]) -def test_workstations_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", [ - (WorkstationsClient, "grpc"), - (WorkstationsAsyncClient, "grpc_asyncio"), - (WorkstationsClient, "rest"), -]) -def test_workstations_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 == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workstations.googleapis.com' - ) - - -def test_workstations_client_get_transport_class(): - transport = WorkstationsClient.get_transport_class() - available_transports = [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsRestTransport, - ] - assert transport in available_transports - - transport = WorkstationsClient.get_transport_class("grpc") - assert transport == transports.WorkstationsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) -def test_workstations_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(WorkstationsClient, '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(WorkstationsClient, '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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "true"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "false"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "true"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "false"), -]) -@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_workstations_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", [ - WorkstationsClient, WorkstationsAsyncClient -]) -@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) -def test_workstations_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", [ - WorkstationsClient, WorkstationsAsyncClient -]) -@mock.patch.object(WorkstationsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WorkstationsAsyncClient)) -def test_workstations_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = WorkstationsClient._DEFAULT_UNIVERSE - default_endpoint = WorkstationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = WorkstationsClient._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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -def test_workstations_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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", None), -]) -def test_workstations_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_workstations_client_client_options_from_dict(): - with mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WorkstationsClient( - 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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_workstations_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( - "workstations.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="workstations.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationClusterRequest, - dict, -]) -def test_get_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - ) - response = client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -def test_get_workstation_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.GetWorkstationClusterRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_workstation_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationClusterRequest( - name='name_value', - ) - -def test_get_workstation_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation_cluster] = mock_rpc - request = {} - client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods - - # 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_workstation_cluster] = mock_rpc - - request = {} - await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - )) - response = await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -@pytest.mark.asyncio -async def test_get_workstation_cluster_async_from_dict(): - await test_get_workstation_cluster_async(request_type=dict) - -def test_get_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = workstations.WorkstationCluster() - client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) - await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation_cluster( - 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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation_cluster( - 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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationClustersRequest, - dict, -]) -def test_list_workstation_clusters(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_clusters_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListWorkstationClustersRequest( - 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_workstation_clusters), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workstation_clusters(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationClustersRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_workstation_clusters_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_clusters] = mock_rpc - request = {} - client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstation_clusters(request) - - # Establish that a new wrapper 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_workstation_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_clusters in client._client._transport._wrapped_methods - - # 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_workstation_clusters] = mock_rpc - - request = {} - await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workstation_clusters(request) - - # Establish that a new wrapper 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_workstation_clusters_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationClustersRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async_from_dict(): - await test_list_workstation_clusters_async(request_type=dict) - -def test_list_workstation_clusters_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = workstations.ListWorkstationClustersResponse() - client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_clusters_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) - await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_clusters_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstation_clusters( - 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_workstation_clusters_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstation_clusters_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstation_clusters( - 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_workstation_clusters_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - - -def test_list_workstation_clusters_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstation_clusters(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, workstations.WorkstationCluster) - for i in results) -def test_list_workstation_clusters_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstation_clusters(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_workstation_clusters_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstation_clusters(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, workstations.WorkstationCluster) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - 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_workstation_clusters(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", [ - workstations.CreateWorkstationClusterRequest, - dict, -]) -def test_create_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.CreateWorkstationClusterRequest( - parent='parent_value', - workstation_cluster_id='workstation_cluster_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_workstation_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationClusterRequest( - parent='parent_value', - workstation_cluster_id='workstation_cluster_id_value', - ) - -def test_create_workstation_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - request = {} - client.create_workstation_cluster(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.create_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods - - # 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_workstation_cluster] = mock_rpc - - request = {} - await client.create_workstation_cluster(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.create_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationClusterRequest() - 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_create_workstation_cluster_async_from_dict(): - await test_create_workstation_cluster_async(request_type=dict) - -def test_create_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_workstation_cluster( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_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].workstation_cluster - mock_val = workstations.WorkstationCluster(name='name_value') - assert arg == mock_val - arg = args[0].workstation_cluster_id - mock_val = 'workstation_cluster_id_value' - assert arg == mock_val - - -def test_create_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_workstation_cluster( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_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].workstation_cluster - mock_val = workstations.WorkstationCluster(name='name_value') - assert arg == mock_val - arg = args[0].workstation_cluster_id - mock_val = 'workstation_cluster_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationClusterRequest, - dict, -]) -def test_update_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.UpdateWorkstationClusterRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_workstation_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationClusterRequest( - ) - -def test_update_workstation_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - request = {} - client.update_workstation_cluster(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.update_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods - - # 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_workstation_cluster] = mock_rpc - - request = {} - await client.update_workstation_cluster(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.update_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationClusterRequest() - 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_update_workstation_cluster_async_from_dict(): - await test_update_workstation_cluster_async(request_type=dict) - -def test_update_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationClusterRequest() - - request.workstation_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_cluster.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationClusterRequest() - - request.workstation_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_cluster.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_workstation_cluster( - workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster - mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_workstation_cluster( - workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster - mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationClusterRequest, - dict, -]) -def test_delete_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.DeleteWorkstationClusterRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_workstation_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationClusterRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_workstation_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - request = {} - client.delete_workstation_cluster(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.delete_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_cluster in client._client._transport._wrapped_methods - - # 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_workstation_cluster] = mock_rpc - - request = {} - await client.delete_workstation_cluster(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.delete_workstation_cluster(request) - - # Establish that a new wrapper 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_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationClusterRequest() - 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_delete_workstation_cluster_async_from_dict(): - await test_delete_workstation_cluster_async(request_type=dict) - -def test_delete_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_workstation_cluster( - 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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_workstation_cluster( - 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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationConfigRequest, - dict, -]) -def test_get_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - replica_zones=['replica_zones_value'], - degraded=True, - enable_audit_agent=True, - ) - response = client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.replica_zones == ['replica_zones_value'] - assert response.degraded is True - assert response.enable_audit_agent is True - - -def test_get_workstation_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.GetWorkstationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_workstation_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationConfigRequest( - name='name_value', - ) - -def test_get_workstation_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation_config] = mock_rpc - request = {} - client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_config in client._client._transport._wrapped_methods - - # 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_workstation_config] = mock_rpc - - request = {} - await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - replica_zones=['replica_zones_value'], - degraded=True, - enable_audit_agent=True, - )) - response = await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.replica_zones == ['replica_zones_value'] - assert response.degraded is True - assert response.enable_audit_agent is True - - -@pytest.mark.asyncio -async def test_get_workstation_config_async_from_dict(): - await test_get_workstation_config_async(request_type=dict) - -def test_get_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = workstations.WorkstationConfig() - client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) - await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation_config( - 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_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation_config( - 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_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationConfigsRequest, - dict, -]) -def test_list_workstation_configs(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_configs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListWorkstationConfigsRequest( - 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_workstation_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workstation_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_workstation_configs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_configs] = mock_rpc - request = {} - client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstation_configs(request) - - # Establish that a new wrapper 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_workstation_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_configs in client._client._transport._wrapped_methods - - # 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_workstation_configs] = mock_rpc - - request = {} - await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workstation_configs(request) - - # Establish that a new wrapper 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_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationConfigsRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstation_configs_async_from_dict(): - await test_list_workstation_configs_async(request_type=dict) - -def test_list_workstation_configs_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListWorkstationConfigsResponse() - client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_configs_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) - await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_configs_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstation_configs( - 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_workstation_configs_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstation_configs_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstation_configs( - 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_workstation_configs_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_workstation_configs_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstation_configs(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, workstations.WorkstationConfig) - for i in results) -def test_list_workstation_configs_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstation_configs(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_workstation_configs_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstation_configs(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, workstations.WorkstationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstation_configs_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - 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_workstation_configs(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", [ - workstations.ListUsableWorkstationConfigsRequest, - dict, -]) -def test_list_usable_workstation_configs(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListUsableWorkstationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstation_configs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListUsableWorkstationConfigsRequest( - 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_usable_workstation_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_usable_workstation_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_usable_workstation_configs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_usable_workstation_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_usable_workstation_configs] = mock_rpc - request = {} - client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_usable_workstation_configs(request) - - # Establish that a new wrapper 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_usable_workstation_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_usable_workstation_configs in client._client._transport._wrapped_methods - - # 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_usable_workstation_configs] = mock_rpc - - request = {} - await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_usable_workstation_configs(request) - - # Establish that a new wrapper 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_usable_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationConfigsRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListUsableWorkstationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async_from_dict(): - await test_list_usable_workstation_configs_async(request_type=dict) - -def test_list_usable_workstation_configs_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_usable_workstation_configs_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) - await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_usable_workstation_configs_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_usable_workstation_configs( - 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_usable_workstation_configs_flattened_error(): - client = WorkstationsClient( - credentials=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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_usable_workstation_configs( - 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_usable_workstation_configs_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstation_configs_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_usable_workstation_configs(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, workstations.WorkstationConfig) - for i in results) -def test_list_usable_workstation_configs_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_usable_workstation_configs(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_usable_workstation_configs_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_usable_workstation_configs(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, workstations.WorkstationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - 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_usable_workstation_configs(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", [ - workstations.CreateWorkstationConfigRequest, - dict, -]) -def test_create_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.CreateWorkstationConfigRequest( - parent='parent_value', - workstation_config_id='workstation_config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_workstation_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationConfigRequest( - parent='parent_value', - workstation_config_id='workstation_config_id_value', - ) - -def test_create_workstation_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - request = {} - client.create_workstation_config(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.create_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_config in client._client._transport._wrapped_methods - - # 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_workstation_config] = mock_rpc - - request = {} - await client.create_workstation_config(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.create_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationConfigRequest() - 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_create_workstation_config_async_from_dict(): - await test_create_workstation_config_async(request_type=dict) - -def test_create_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_workstation_config( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_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].workstation_config - mock_val = workstations.WorkstationConfig(name='name_value') - assert arg == mock_val - arg = args[0].workstation_config_id - mock_val = 'workstation_config_id_value' - assert arg == mock_val - - -def test_create_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_workstation_config( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_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].workstation_config - mock_val = workstations.WorkstationConfig(name='name_value') - assert arg == mock_val - arg = args[0].workstation_config_id - mock_val = 'workstation_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationConfigRequest, - dict, -]) -def test_update_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.UpdateWorkstationConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_workstation_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationConfigRequest( - ) - -def test_update_workstation_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - request = {} - client.update_workstation_config(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.update_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_config in client._client._transport._wrapped_methods - - # 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_workstation_config] = mock_rpc - - request = {} - await client.update_workstation_config(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.update_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationConfigRequest() - 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_update_workstation_config_async_from_dict(): - await test_update_workstation_config_async(request_type=dict) - -def test_update_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationConfigRequest() - - request.workstation_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationConfigRequest() - - request.workstation_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_config.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_workstation_config( - workstation_config=workstations.WorkstationConfig(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].workstation_config - mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_workstation_config( - workstation_config=workstations.WorkstationConfig(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].workstation_config - mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationConfigRequest, - dict, -]) -def test_delete_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.DeleteWorkstationConfigRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_workstation_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationConfigRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_workstation_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - request = {} - client.delete_workstation_config(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.delete_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation_config in client._client._transport._wrapped_methods - - # 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_workstation_config] = mock_rpc - - request = {} - await client.delete_workstation_config(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.delete_workstation_config(request) - - # Establish that a new wrapper 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_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationConfigRequest() - 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_delete_workstation_config_async_from_dict(): - await test_delete_workstation_config_async(request_type=dict) - -def test_delete_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_workstation_config( - 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_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_workstation_config( - 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_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationRequest, - dict, -]) -def test_get_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - ) - response = client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -def test_get_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.GetWorkstationRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationRequest( - name='name_value', - ) - -def test_get_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation] = mock_rpc - request = {} - client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation(request) - - # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation in client._client._transport._wrapped_methods - - # 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_workstation] = mock_rpc - - request = {} - await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_workstation(request) - - # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - )) - response = await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.GetWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -@pytest.mark.asyncio -async def test_get_workstation_async_from_dict(): - await test_get_workstation_async(request_type=dict) - -def test_get_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = workstations.Workstation() - client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) - await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation( - 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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation( - 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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationsRequest, - dict, -]) -def test_list_workstations(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstations_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListWorkstationsRequest( - 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_workstations), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workstations(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_workstations_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstations in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstations] = mock_rpc - request = {} - client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstations(request) - - # Establish that a new wrapper 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_workstations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstations in client._client._transport._wrapped_methods - - # 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_workstations] = mock_rpc - - request = {} - await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workstations(request) - - # Establish that a new wrapper 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_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationsRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListWorkstationsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstations_async_from_dict(): - await test_list_workstations_async(request_type=dict) - -def test_list_workstations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = workstations.ListWorkstationsResponse() - client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) - await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstations_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstations( - 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_workstations_flattened_error(): - client = WorkstationsClient( - credentials=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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstations_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstations( - 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_workstations_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_workstations_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstations(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, workstations.Workstation) - for i in results) -def test_list_workstations_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstations(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_workstations_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstations(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, workstations.Workstation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstations_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - 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_workstations(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", [ - workstations.ListUsableWorkstationsRequest, - dict, -]) -def test_list_usable_workstations(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.ListUsableWorkstationsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstations_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.ListUsableWorkstationsRequest( - 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_usable_workstations), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_usable_workstations(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_usable_workstations_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_usable_workstations in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_usable_workstations] = mock_rpc - request = {} - client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_usable_workstations(request) - - # Establish that a new wrapper 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_usable_workstations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_usable_workstations in client._client._transport._wrapped_methods - - # 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_usable_workstations] = mock_rpc - - request = {} - await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_usable_workstations(request) - - # Establish that a new wrapper 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_usable_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationsRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.ListUsableWorkstationsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_usable_workstations_async_from_dict(): - await test_list_usable_workstations_async(request_type=dict) - -def test_list_usable_workstations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationsResponse() - client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_usable_workstations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) - await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_usable_workstations_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_usable_workstations( - 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_usable_workstations_flattened_error(): - client = WorkstationsClient( - credentials=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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_usable_workstations_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_usable_workstations( - 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_usable_workstations_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstations_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_usable_workstations(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, workstations.Workstation) - for i in results) -def test_list_usable_workstations_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_usable_workstations(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_usable_workstations_async_pager(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_usable_workstations(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, workstations.Workstation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_usable_workstations_async_pages(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - 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_usable_workstations(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", [ - workstations.CreateWorkstationRequest, - dict, -]) -def test_create_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.CreateWorkstationRequest( - parent='parent_value', - workstation_id='workstation_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationRequest( - parent='parent_value', - workstation_id='workstation_id_value', - ) - -def test_create_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - request = {} - client.create_workstation(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.create_workstation(request) - - # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation in client._client._transport._wrapped_methods - - # 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_workstation] = mock_rpc - - request = {} - await client.create_workstation(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.create_workstation(request) - - # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.CreateWorkstationRequest() - 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_create_workstation_async_from_dict(): - await test_create_workstation_async(request_type=dict) - -def test_create_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_workstation( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_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].workstation - mock_val = workstations.Workstation(name='name_value') - assert arg == mock_val - arg = args[0].workstation_id - mock_val = 'workstation_id_value' - assert arg == mock_val - - -def test_create_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_workstation( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_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].workstation - mock_val = workstations.Workstation(name='name_value') - assert arg == mock_val - arg = args[0].workstation_id - mock_val = 'workstation_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationRequest, - dict, -]) -def test_update_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.UpdateWorkstationRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationRequest( - ) - -def test_update_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - request = {} - client.update_workstation(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.update_workstation(request) - - # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation in client._client._transport._wrapped_methods - - # 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_workstation] = mock_rpc - - request = {} - await client.update_workstation(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.update_workstation(request) - - # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.UpdateWorkstationRequest() - 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_update_workstation_async_from_dict(): - await test_update_workstation_async(request_type=dict) - -def test_update_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationRequest() - - request.workstation.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationRequest() - - request.workstation.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_workstation( - workstation=workstations.Workstation(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].workstation - mock_val = workstations.Workstation(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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_workstation( - workstation=workstations.Workstation(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].workstation - mock_val = workstations.Workstation(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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationRequest, - dict, -]) -def test_delete_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.DeleteWorkstationRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - request = {} - client.delete_workstation(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.delete_workstation(request) - - # Establish that a new wrapper 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_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_workstation in client._client._transport._wrapped_methods - - # 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_workstation] = mock_rpc - - request = {} - await client.delete_workstation(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.delete_workstation(request) - - # Establish that a new wrapper 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_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.DeleteWorkstationRequest() - 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_delete_workstation_async_from_dict(): - await test_delete_workstation_async(request_type=dict) - -def test_delete_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_workstation( - 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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_workstation( - 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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StartWorkstationRequest, - dict, -]) -def test_start_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.StartWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_start_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.StartWorkstationRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.start_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StartWorkstationRequest( - name='name_value', - etag='etag_value', - ) - -def test_start_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_workstation] = mock_rpc - request = {} - client.start_workstation(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.start_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.start_workstation in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.start_workstation] = mock_rpc - - request = {} - await client.start_workstation(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.start_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_start_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StartWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.StartWorkstationRequest() - 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_start_workstation_async_from_dict(): - await test_start_workstation_async(request_type=dict) - -def test_start_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StartWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StartWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.start_workstation( - 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_start_workstation_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_start_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.start_workstation( - 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_start_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StopWorkstationRequest, - dict, -]) -def test_stop_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.StopWorkstationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_stop_workstation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.StopWorkstationRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.stop_workstation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StopWorkstationRequest( - name='name_value', - etag='etag_value', - ) - -def test_stop_workstation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_workstation] = mock_rpc - request = {} - client.stop_workstation(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.stop_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_workstation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.stop_workstation in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.stop_workstation] = mock_rpc - - request = {} - await client.stop_workstation(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.stop_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StopWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.StopWorkstationRequest() - 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_stop_workstation_async_from_dict(): - await test_stop_workstation_async(request_type=dict) - -def test_stop_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StopWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StopWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.stop_workstation( - 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_stop_workstation_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_stop_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.stop_workstation( - 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_stop_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - ) - response = client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = workstations.GenerateAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -def test_generate_access_token_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = workstations.GenerateAccessTokenRequest( - workstation='workstation_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_access_token(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GenerateAccessTokenRequest( - workstation='workstation_value', - ) - -def test_generate_access_token_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc - request = {} - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_access_token in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_access_token] = mock_rpc - - request = {} - await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=workstations.GenerateAccessTokenRequest): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - )) - response = await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = workstations.GenerateAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.asyncio -async def test_generate_access_token_async_from_dict(): - await test_generate_access_token_async(request_type=dict) - -def test_generate_access_token_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GenerateAccessTokenRequest() - - request.workstation = 'workstation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = workstations.GenerateAccessTokenResponse() - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation=workstation_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_access_token_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GenerateAccessTokenRequest() - - request.workstation = 'workstation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) - await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation=workstation_value', - ) in kw['metadata'] - - -def test_generate_access_token_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_access_token( - workstation='workstation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].workstation - mock_val = 'workstation_value' - assert arg == mock_val - - -def test_generate_access_token_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_access_token( - workstation='workstation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].workstation - mock_val = 'workstation_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_error_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - - -def test_get_workstation_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation_cluster] = mock_rpc - - request = {} - client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation_cluster(request) - - # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.GetWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation_cluster._get_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_workstation_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.WorkstationCluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.WorkstationCluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_get_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - - -def test_list_workstation_clusters_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_clusters] = mock_rpc - - request = {} - client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstation_clusters(request) - - # Establish 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_workstation_clusters_rest_required_fields(request_type=workstations.ListWorkstationClustersRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_clusters._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_workstation_clusters._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListWorkstationClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_workstation_clusters(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstation_clusters_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstation_clusters._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workstation_clusters_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/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 = workstations.ListWorkstationClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_workstation_clusters(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) - - -def test_list_workstation_clusters_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - - -def test_list_workstation_clusters_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationClustersResponse.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/locations/sample2'} - - pager = client.list_workstation_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationCluster) - for i in results) - - pages = list(client.list_workstation_clusters(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_workstation_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - - request = {} - client.create_workstation_cluster(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.create_workstation_cluster(request) - - # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.CreateWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_cluster_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 "workstationClusterId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationClusterId" in jsonified_request - assert jsonified_request["workstationClusterId"] == request_init["workstation_cluster_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationClusterId"] = 'workstation_cluster_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only", "workstation_cluster_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 "workstationClusterId" in jsonified_request - assert jsonified_request["workstationClusterId"] == 'workstation_cluster_id_value' - - client = WorkstationsClient( - 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 - - response = client.create_workstation_cluster(request) - - expected_params = [ - ( - "workstationClusterId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationClusterId", )) & set(("parent", "workstationClusterId", "workstationCluster", ))) - - -def test_create_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) - - -def test_create_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - -def test_update_workstation_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - - request = {} - client.update_workstation_cluster(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.update_workstation_cluster(request) - - # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.UpdateWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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': "patch", - '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 - - response = client.update_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationCluster", "updateMask", ))) - - -def test_update_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation_cluster=workstations.WorkstationCluster(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_update_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_workstation_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_cluster] = mock_rpc - - request = {} - client.delete_workstation_cluster(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.delete_workstation_cluster(request) - - # Establish 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_workstation_cluster_rest_required_fields(request_type=workstations.DeleteWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation_cluster._get_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_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "force", "validate_only", )) - jsonified_request.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 = WorkstationsClient( - 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': "delete", - '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 - - response = client.delete_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) - - -def test_delete_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - - -def test_get_workstation_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation_config] = mock_rpc - - request = {} - client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation_config(request) - - # Establish 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_workstation_config_rest_required_fields(request_type=workstations.GetWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation_config._get_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_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.WorkstationConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # 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 = workstations.WorkstationConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - - -def test_list_workstation_configs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_configs] = mock_rpc - - request = {} - client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstation_configs(request) - - # Establish 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_workstation_configs_rest_required_fields(request_type=workstations.ListWorkstationConfigsRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_configs._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_workstation_configs._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_workstation_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstation_configs_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstation_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workstation_configs_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # 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 = workstations.ListWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_workstation_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) - - -def test_list_workstation_configs_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_workstation_configs_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationConfigsResponse.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/locations/sample2/workstationClusters/sample3'} - - pager = client.list_workstation_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) - - pages = list(client.list_workstation_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_usable_workstation_configs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_usable_workstation_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_usable_workstation_configs] = mock_rpc - - request = {} - client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_usable_workstation_configs(request) - - # Establish 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_usable_workstation_configs_rest_required_fields(request_type=workstations.ListUsableWorkstationConfigsRequest): - transport_class = transports.WorkstationsRestTransport - - 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_usable_workstation_configs._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_usable_workstation_configs._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_usable_workstation_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_usable_workstation_configs_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_usable_workstation_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_usable_workstation_configs_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # 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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_usable_workstation_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable" % client.transport._host, args[1]) - - -def test_list_usable_workstation_configs_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstation_configs_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListUsableWorkstationConfigsResponse.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/locations/sample2/workstationClusters/sample3'} - - pager = client.list_usable_workstation_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) - - pages = list(client.list_usable_workstation_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_workstation_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - - request = {} - client.create_workstation_config(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.create_workstation_config(request) - - # Establish 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_workstation_config_rest_required_fields(request_type=workstations.CreateWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_config_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 "workstationConfigId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationConfigId" in jsonified_request - assert jsonified_request["workstationConfigId"] == request_init["workstation_config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationConfigId"] = 'workstation_config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only", "workstation_config_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 "workstationConfigId" in jsonified_request - assert jsonified_request["workstationConfigId"] == 'workstation_config_id_value' - - client = WorkstationsClient( - 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 - - response = client.create_workstation_config(request) - - expected_params = [ - ( - "workstationConfigId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationConfigId", )) & set(("parent", "workstationConfigId", "workstationConfig", ))) - - -def test_create_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) - - -def test_create_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - -def test_update_workstation_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - - request = {} - client.update_workstation_config(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.update_workstation_config(request) - - # Establish 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_workstation_config_rest_required_fields(request_type=workstations.UpdateWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_config._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_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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': "patch", - '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 - - response = client.update_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationConfig", "updateMask", ))) - - -def test_update_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation_config=workstations.WorkstationConfig(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_workstation_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation_config] = mock_rpc - - request = {} - client.delete_workstation_config(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.delete_workstation_config(request) - - # Establish 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_workstation_config_rest_required_fields(request_type=workstations.DeleteWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation_config._get_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_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "force", "validate_only", )) - jsonified_request.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 = WorkstationsClient( - 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': "delete", - '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 - - response = client.delete_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) - - -def test_delete_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # 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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - - -def test_get_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_workstation] = mock_rpc - - request = {} - client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_workstation(request) - - # Establish 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_workstation_rest_required_fields(request_type=workstations.GetWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation._get_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_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.Workstation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # 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 = workstations.Workstation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_get_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - - -def test_list_workstations_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstations in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstations] = mock_rpc - - request = {} - client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workstations(request) - - # Establish 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_workstations_rest_required_fields(request_type=workstations.ListWorkstationsRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstations._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_workstations._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_workstations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstations_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workstations_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # 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 = workstations.ListWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_workstations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) - - -def test_list_workstations_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_workstations_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationsResponse.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/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - pager = client.list_workstations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) - - pages = list(client.list_workstations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_usable_workstations_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_usable_workstations in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_usable_workstations] = mock_rpc - - request = {} - client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_usable_workstations(request) - - # Establish 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_usable_workstations_rest_required_fields(request_type=workstations.ListUsableWorkstationsRequest): - transport_class = transports.WorkstationsRestTransport - - 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_usable_workstations._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_usable_workstations._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = workstations.ListUsableWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_usable_workstations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_usable_workstations_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_usable_workstations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_usable_workstations_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # 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 = workstations.ListUsableWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_usable_workstations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable" % client.transport._host, args[1]) - - -def test_list_usable_workstations_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstations_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListUsableWorkstationsResponse.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/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - pager = client.list_usable_workstations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) - - pages = list(client.list_usable_workstations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - - request = {} - client.create_workstation(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.create_workstation(request) - - # Establish 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_workstation_rest_required_fields(request_type=workstations.CreateWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_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 "workstationId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationId" in jsonified_request - assert jsonified_request["workstationId"] == request_init["workstation_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationId"] = 'workstation_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only", "workstation_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 "workstationId" in jsonified_request - assert jsonified_request["workstationId"] == 'workstation_id_value' - - client = WorkstationsClient( - 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 - - response = client.create_workstation(request) - - expected_params = [ - ( - "workstationId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationId", )) & set(("parent", "workstationId", "workstation", ))) - - -def test_create_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) - - -def test_create_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - -def test_update_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - - request = {} - client.update_workstation(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.update_workstation(request) - - # Establish 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_workstation_rest_required_fields(request_type=workstations.UpdateWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation._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_workstation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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': "patch", - '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 - - response = client.update_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstation", "updateMask", ))) - - -def test_update_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation=workstations.Workstation(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_update_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_workstation] = mock_rpc - - request = {} - client.delete_workstation(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.delete_workstation(request) - - # Establish 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_workstation_rest_required_fields(request_type=workstations.DeleteWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_workstation._get_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_workstation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "validate_only", )) - jsonified_request.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 = WorkstationsClient( - 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': "delete", - '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 - - response = client.delete_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) - - -def test_delete_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # 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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - - -def test_start_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.start_workstation] = mock_rpc - - request = {} - client.start_workstation(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.start_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_start_workstation_rest_required_fields(request_type=workstations.StartWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).start_workstation._get_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()).start_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - 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 - - response = client.start_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_start_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.start_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_start_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # 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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.start_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start" % client.transport._host, args[1]) - - -def test_start_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - - -def test_stop_workstation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.stop_workstation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.stop_workstation] = mock_rpc - - request = {} - client.stop_workstation(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.stop_workstation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_stop_workstation_rest_required_fields(request_type=workstations.StopWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).stop_workstation._get_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()).stop_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.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 = WorkstationsClient( - 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 - - response = client.stop_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_stop_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.stop_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_stop_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # 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 = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.stop_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop" % client.transport._host, args[1]) - - -def test_stop_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - - -def test_generate_access_token_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc - - request = {} - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_access_token_rest_required_fields(request_type=workstations.GenerateAccessTokenRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["workstation"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["workstation"] = 'workstation_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "workstation" in jsonified_request - assert jsonified_request["workstation"] == 'workstation_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = workstations.GenerateAccessTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.generate_access_token(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_access_token_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_access_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("workstation", ))) - - -def test_generate_access_token_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - workstation='workstation_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = workstations.GenerateAccessTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.generate_access_token(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken" % client.transport._host, args[1]) - - -def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WorkstationsClient( - 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 = WorkstationsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WorkstationsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WorkstationsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - transports.WorkstationsRestTransport, -]) -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 = WorkstationsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = WorkstationsClient( - 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_workstation_cluster_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = workstations.WorkstationCluster() - client.get_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_clusters_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = workstations.ListWorkstationClustersResponse() - client.list_workstation_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationClustersRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = workstations.WorkstationConfig() - client.get_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_configs_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListWorkstationConfigsResponse() - client.list_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This 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_usable_workstation_configs_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - client.list_usable_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = workstations.Workstation() - client.get_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstations_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = workstations.ListWorkstationsResponse() - client.list_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationsRequest() - - assert args[0] == request_msg - - -# This 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_usable_workstations_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationsResponse() - client.list_usable_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationsRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.start_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StartWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_workstation_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.stop_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StopWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_access_token_empty_call_grpc(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = workstations.GenerateAccessTokenResponse() - client.generate_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GenerateAccessTokenRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = WorkstationsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = WorkstationsAsyncClient( - 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_workstation_cluster_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - )) - await client.get_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_clusters_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_workstation_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__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.create_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__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.update_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_cluster_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__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.delete_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - replica_zones=['replica_zones_value'], - degraded=True, - enable_audit_agent=True, - )) - await client.get_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_configs_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_usable_workstation_configs_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_usable_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__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.create_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__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.update_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_config_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__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.delete_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - )) - await client.get_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstations_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_usable_workstations_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_usable_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__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.create_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__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.update_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__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.delete_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_start_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StartWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_stop_workstation_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StopWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_access_token_empty_call_grpc_asyncio(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - )) - await client.generate_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GenerateAccessTokenRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = WorkstationsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_workstation_cluster_rest_bad_request(request_type=workstations.GetWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 - client.get_workstation_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationClusterRequest, - dict, -]) -def test_get_workstation_cluster_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=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 = workstations.WorkstationCluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationClusterRequest.pb(workstations.GetWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.WorkstationCluster.to_json(workstations.WorkstationCluster()) - req.return_value.content = return_value - - request = workstations.GetWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.WorkstationCluster() - - client.get_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstation_clusters_rest_bad_request(request_type=workstations.ListWorkstationClustersRequest): - client = WorkstationsClient( - 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 - client.list_workstation_clusters(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationClustersRequest, - dict, -]) -def test_list_workstation_clusters_rest_call_success(request_type): - client = WorkstationsClient( - 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 = workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListWorkstationClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_workstation_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstation_clusters_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_clusters") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_clusters") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationClustersRequest.pb(workstations.ListWorkstationClustersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListWorkstationClustersResponse.to_json(workstations.ListWorkstationClustersResponse()) - req.return_value.content = return_value - - request = workstations.ListWorkstationClustersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationClustersResponse() - - client.list_workstation_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_cluster_rest_bad_request(request_type=workstations.CreateWorkstationClusterRequest): - client = WorkstationsClient( - 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 - client.create_workstation_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationClusterRequest, - dict, -]) -def test_create_workstation_cluster_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = workstations.CreateWorkstationClusterRequest.meta.fields["workstation_cluster"] - - 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["workstation_cluster"].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["workstation_cluster"][field])): - del request_init["workstation_cluster"][field][i][subfield] - else: - del request_init["workstation_cluster"][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 = 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 - response = client.create_workstation_cluster(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_create_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationClusterRequest.pb(workstations.CreateWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.CreateWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_cluster_rest_bad_request(request_type=workstations.UpdateWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/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 - client.update_workstation_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationClusterRequest, - dict, -]) -def test_update_workstation_cluster_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = workstations.UpdateWorkstationClusterRequest.meta.fields["workstation_cluster"] - - 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["workstation_cluster"].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["workstation_cluster"][field])): - del request_init["workstation_cluster"][field][i][subfield] - else: - del request_init["workstation_cluster"][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 = 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 - response = client.update_workstation_cluster(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_update_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationClusterRequest.pb(workstations.UpdateWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.UpdateWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_cluster_rest_bad_request(request_type=workstations.DeleteWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 - client.delete_workstation_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationClusterRequest, - dict, -]) -def test_delete_workstation_cluster_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/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 = 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 - response = client.delete_workstation_cluster(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_delete_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationClusterRequest.pb(workstations.DeleteWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.DeleteWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_config_rest_bad_request(request_type=workstations.GetWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_workstation_config(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationConfigRequest, - dict, -]) -def test_get_workstation_config_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - replica_zones=['replica_zones_value'], - degraded=True, - enable_audit_agent=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 = workstations.WorkstationConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_workstation_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.replica_zones == ['replica_zones_value'] - assert response.degraded is True - assert response.enable_audit_agent is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationConfigRequest.pb(workstations.GetWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.WorkstationConfig.to_json(workstations.WorkstationConfig()) - req.return_value.content = return_value - - request = workstations.GetWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.WorkstationConfig() - - client.get_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstation_configs_rest_bad_request(request_type=workstations.ListWorkstationConfigsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 - client.list_workstation_configs(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationConfigsRequest, - dict, -]) -def test_list_workstation_configs_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_workstation_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstation_configs_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_configs") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationConfigsRequest.pb(workstations.ListWorkstationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListWorkstationConfigsResponse.to_json(workstations.ListWorkstationConfigsResponse()) - req.return_value.content = return_value - - request = workstations.ListWorkstationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationConfigsResponse() - - client.list_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_usable_workstation_configs_rest_bad_request(request_type=workstations.ListUsableWorkstationConfigsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 - client.list_usable_workstation_configs(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListUsableWorkstationConfigsRequest, - dict, -]) -def test_list_usable_workstation_configs_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 = workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListUsableWorkstationConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_usable_workstation_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_usable_workstation_configs_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstation_configs") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstation_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListUsableWorkstationConfigsRequest.pb(workstations.ListUsableWorkstationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListUsableWorkstationConfigsResponse.to_json(workstations.ListUsableWorkstationConfigsResponse()) - req.return_value.content = return_value - - request = workstations.ListUsableWorkstationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListUsableWorkstationConfigsResponse() - - client.list_usable_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_config_rest_bad_request(request_type=workstations.CreateWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/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 - client.create_workstation_config(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationConfigRequest, - dict, -]) -def test_create_workstation_config_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'service_account_scopes': ['service_account_scopes_value1', 'service_account_scopes_value2'], 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'ephemeral_directories': [{'gce_pd': {'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'source_image': 'source_image_value', 'read_only': True}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'replica_zones': ['replica_zones_value1', 'replica_zones_value2'], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': 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 = workstations.CreateWorkstationConfigRequest.meta.fields["workstation_config"] - - 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["workstation_config"].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["workstation_config"][field])): - del request_init["workstation_config"][field][i][subfield] - else: - del request_init["workstation_config"][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 = 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 - response = client.create_workstation_config(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_create_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationConfigRequest.pb(workstations.CreateWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.CreateWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_config_rest_bad_request(request_type=workstations.UpdateWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_workstation_config(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationConfigRequest, - dict, -]) -def test_update_workstation_config_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'service_account_scopes': ['service_account_scopes_value1', 'service_account_scopes_value2'], 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'ephemeral_directories': [{'gce_pd': {'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'source_image': 'source_image_value', 'read_only': True}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'replica_zones': ['replica_zones_value1', 'replica_zones_value2'], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': 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 = workstations.UpdateWorkstationConfigRequest.meta.fields["workstation_config"] - - 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["workstation_config"].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["workstation_config"][field])): - del request_init["workstation_config"][field][i][subfield] - else: - del request_init["workstation_config"][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 = 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 - response = client.update_workstation_config(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_update_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationConfigRequest.pb(workstations.UpdateWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.UpdateWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_config_rest_bad_request(request_type=workstations.DeleteWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.delete_workstation_config(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationConfigRequest, - dict, -]) -def test_delete_workstation_config_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # 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 - response = client.delete_workstation_config(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_delete_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationConfigRequest.pb(workstations.DeleteWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.DeleteWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_rest_bad_request(request_type=workstations.GetWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationRequest, - dict, -]) -def test_get_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_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 = workstations.Workstation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_workstation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationRequest.pb(workstations.GetWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.Workstation.to_json(workstations.Workstation()) - req.return_value.content = return_value - - request = workstations.GetWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.Workstation() - - client.get_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstations_rest_bad_request(request_type=workstations.ListWorkstationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_workstations(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationsRequest, - dict, -]) -def test_list_workstations_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_workstations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstations_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstations") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationsRequest.pb(workstations.ListWorkstationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListWorkstationsResponse.to_json(workstations.ListWorkstationsResponse()) - req.return_value.content = return_value - - request = workstations.ListWorkstationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationsResponse() - - client.list_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_usable_workstations_rest_bad_request(request_type=workstations.ListUsableWorkstationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_usable_workstations(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListUsableWorkstationsRequest, - dict, -]) -def test_list_usable_workstations_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_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 = workstations.ListUsableWorkstationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_usable_workstations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_usable_workstations_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstations") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListUsableWorkstationsRequest.pb(workstations.ListUsableWorkstationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.ListUsableWorkstationsResponse.to_json(workstations.ListUsableWorkstationsResponse()) - req.return_value.content = return_value - - request = workstations.ListUsableWorkstationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListUsableWorkstationsResponse() - - client.list_usable_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_rest_bad_request(request_type=workstations.CreateWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationRequest, - dict, -]) -def test_create_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'start_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} - # 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 = workstations.CreateWorkstationRequest.meta.fields["workstation"] - - 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["workstation"].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["workstation"][field])): - del request_init["workstation"][field][i][subfield] - else: - del request_init["workstation"][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 = 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 - response = client.create_workstation(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_create_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationRequest.pb(workstations.CreateWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.CreateWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_rest_bad_request(request_type=workstations.UpdateWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationRequest, - dict, -]) -def test_update_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'start_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} - # 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 = workstations.UpdateWorkstationRequest.meta.fields["workstation"] - - 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["workstation"].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["workstation"][field])): - del request_init["workstation"][field][i][subfield] - else: - del request_init["workstation"][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 = 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 - response = client.update_workstation(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_update_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationRequest.pb(workstations.UpdateWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.UpdateWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_rest_bad_request(request_type=workstations.DeleteWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.delete_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationRequest, - dict, -]) -def test_delete_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and 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 - response = client.delete_workstation(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_delete_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationRequest.pb(workstations.DeleteWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.DeleteWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_start_workstation_rest_bad_request(request_type=workstations.StartWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.start_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.StartWorkstationRequest, - dict, -]) -def test_start_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and 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 - response = client.start_workstation(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_start_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_start_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_start_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.StartWorkstationRequest.pb(workstations.StartWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.StartWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.start_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_stop_workstation_rest_bad_request(request_type=workstations.StopWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.stop_workstation(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.StopWorkstationRequest, - dict, -]) -def test_stop_workstation_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and 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 - response = client.stop_workstation(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_stop_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_stop_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_stop_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.StopWorkstationRequest.pb(workstations.StopWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = workstations.StopWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.stop_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_access_token_rest_bad_request(request_type=workstations.GenerateAccessTokenRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.generate_access_token(request) - - -@pytest.mark.parametrize("request_type", [ - workstations.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token_rest_call_success(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse( - access_token='access_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 = workstations.GenerateAccessTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.generate_access_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_access_token_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_generate_access_token") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_generate_access_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GenerateAccessTokenRequest.pb(workstations.GenerateAccessTokenRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = workstations.GenerateAccessTokenResponse.to_json(workstations.GenerateAccessTokenResponse()) - req.return_value.content = return_value - - request = workstations.GenerateAccessTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.GenerateAccessTokenResponse() - - client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - 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 = policy_pb2.Policy() - - # 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 - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - 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 = policy_pb2.Policy() - - # 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 - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, 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 - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - 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 = iam_policy_pb2.TestIamPermissionsResponse() - - # 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 - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = WorkstationsClient( - 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 - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = WorkstationsClient( - 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 = 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 - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = WorkstationsClient( - 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 - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = WorkstationsClient( - 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 = 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 - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = WorkstationsClient( - 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 - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = WorkstationsClient( - 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 - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # 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 - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': '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(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # 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 - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_initialize_client_w_rest(): - client = WorkstationsClient( - 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_workstation_cluster_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - client.get_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_clusters_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - client.list_workstation_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationClustersRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - client.create_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - client.update_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_cluster_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - client.delete_workstation_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationClusterRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - client.get_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_configs_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - client.list_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This 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_usable_workstation_configs_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - client.list_usable_workstation_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationConfigsRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - client.create_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - client.update_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_config_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - client.delete_workstation_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationConfigRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - client.get_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GetWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstations_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - client.list_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListWorkstationsRequest() - - assert args[0] == request_msg - - -# This 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_usable_workstations_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - client.list_usable_workstations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.ListUsableWorkstationsRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - client.create_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.CreateWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - client.update_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.UpdateWorkstationRequest() - - assert args[0] == request_msg - - -# This 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_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - client.delete_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.DeleteWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_start_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - client.start_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StartWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_workstation_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - client.stop_workstation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.StopWorkstationRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_access_token_empty_call_rest(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - client.generate_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = workstations.GenerateAccessTokenRequest() - - assert args[0] == request_msg - - -def test_workstations_rest_lro_client(): - client = WorkstationsClient( - 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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WorkstationsGrpcTransport, - ) - -def test_workstations_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WorkstationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_workstations_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WorkstationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_workstation_cluster', - 'list_workstation_clusters', - 'create_workstation_cluster', - 'update_workstation_cluster', - 'delete_workstation_cluster', - 'get_workstation_config', - 'list_workstation_configs', - 'list_usable_workstation_configs', - 'create_workstation_config', - 'update_workstation_config', - 'delete_workstation_config', - 'get_workstation', - 'list_workstations', - 'list_usable_workstations', - 'create_workstation', - 'update_workstation', - 'delete_workstation', - 'start_workstation', - 'stop_workstation', - 'generate_access_token', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - 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_workstations_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkstationsTransport( - 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_workstations_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkstationsTransport() - adc.assert_called_once() - - -def test_workstations_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) - WorkstationsClient() - 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.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - ], -) -def test_workstations_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.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - transports.WorkstationsRestTransport, - ], -) -def test_workstations_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.WorkstationsGrpcTransport, grpc_helpers), - (transports.WorkstationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_workstations_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( - "workstations.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="workstations.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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_workstations_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.WorkstationsRestTransport ( - 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_workstations_host_no_port(transport_name): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workstations.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_workstations_host_with_port(transport_name): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workstations.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workstations.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_workstations_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = WorkstationsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = WorkstationsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_workstation_cluster._session - session2 = client2.transport.get_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.list_workstation_clusters._session - session2 = client2.transport.list_workstation_clusters._session - assert session1 != session2 - session1 = client1.transport.create_workstation_cluster._session - session2 = client2.transport.create_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.update_workstation_cluster._session - session2 = client2.transport.update_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.delete_workstation_cluster._session - session2 = client2.transport.delete_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.get_workstation_config._session - session2 = client2.transport.get_workstation_config._session - assert session1 != session2 - session1 = client1.transport.list_workstation_configs._session - session2 = client2.transport.list_workstation_configs._session - assert session1 != session2 - session1 = client1.transport.list_usable_workstation_configs._session - session2 = client2.transport.list_usable_workstation_configs._session - assert session1 != session2 - session1 = client1.transport.create_workstation_config._session - session2 = client2.transport.create_workstation_config._session - assert session1 != session2 - session1 = client1.transport.update_workstation_config._session - session2 = client2.transport.update_workstation_config._session - assert session1 != session2 - session1 = client1.transport.delete_workstation_config._session - session2 = client2.transport.delete_workstation_config._session - assert session1 != session2 - session1 = client1.transport.get_workstation._session - session2 = client2.transport.get_workstation._session - assert session1 != session2 - session1 = client1.transport.list_workstations._session - session2 = client2.transport.list_workstations._session - assert session1 != session2 - session1 = client1.transport.list_usable_workstations._session - session2 = client2.transport.list_usable_workstations._session - assert session1 != session2 - session1 = client1.transport.create_workstation._session - session2 = client2.transport.create_workstation._session - assert session1 != session2 - session1 = client1.transport.update_workstation._session - session2 = client2.transport.update_workstation._session - assert session1 != session2 - session1 = client1.transport.delete_workstation._session - session2 = client2.transport.delete_workstation._session - assert session1 != session2 - session1 = client1.transport.start_workstation._session - session2 = client2.transport.start_workstation._session - assert session1 != session2 - session1 = client1.transport.stop_workstation._session - session2 = client2.transport.stop_workstation._session - assert session1 != session2 - session1 = client1.transport.generate_access_token._session - session2 = client2.transport.generate_access_token._session - assert session1 != session2 -def test_workstations_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkstationsGrpcTransport( - 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_workstations_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkstationsGrpcAsyncIOTransport( - 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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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_workstations_grpc_lro_client(): - client = WorkstationsClient( - 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_workstations_grpc_lro_async_client(): - client = WorkstationsAsyncClient( - 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_workstation_path(): - project = "squid" - location = "clam" - workstation_cluster = "whelk" - workstation_config = "octopus" - workstation = "oyster" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) - actual = WorkstationsClient.workstation_path(project, location, workstation_cluster, workstation_config, workstation) - assert expected == actual - - -def test_parse_workstation_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "workstation_cluster": "mussel", - "workstation_config": "winkle", - "workstation": "nautilus", - } - path = WorkstationsClient.workstation_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_path(path) - assert expected == actual - -def test_workstation_cluster_path(): - project = "scallop" - location = "abalone" - workstation_cluster = "squid" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) - actual = WorkstationsClient.workstation_cluster_path(project, location, workstation_cluster) - assert expected == actual - - -def test_parse_workstation_cluster_path(): - expected = { - "project": "clam", - "location": "whelk", - "workstation_cluster": "octopus", - } - path = WorkstationsClient.workstation_cluster_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_cluster_path(path) - assert expected == actual - -def test_workstation_config_path(): - project = "oyster" - location = "nudibranch" - workstation_cluster = "cuttlefish" - workstation_config = "mussel" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) - actual = WorkstationsClient.workstation_config_path(project, location, workstation_cluster, workstation_config) - assert expected == actual - - -def test_parse_workstation_config_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "workstation_cluster": "scallop", - "workstation_config": "abalone", - } - path = WorkstationsClient.workstation_config_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WorkstationsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = WorkstationsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = WorkstationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = WorkstationsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WorkstationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = WorkstationsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = WorkstationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = WorkstationsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.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 = WorkstationsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = WorkstationsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.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.WorkstationsTransport, '_prep_wrapped_messages') as prep: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WorkstationsTransport, '_prep_wrapped_messages') as prep: - transport_class = WorkstationsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_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 response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_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 response is None - -def test_delete_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_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_delete_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_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_delete_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_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 response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_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 response is None - -def test_cancel_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_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_cancel_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_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_cancel_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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 = WorkstationsClient( - 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 = WorkstationsAsyncClient( - 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_list_operations(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the 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.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional 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.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the 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.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_list_operations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value 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.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_list_operations_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_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 response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_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 response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_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", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_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", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_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 response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_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 response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_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", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_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", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = WorkstationsClient( - 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 = WorkstationsAsyncClient( - 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 = WorkstationsClient( - 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 = WorkstationsClient( - 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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport), -]) -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-geo-type/viewport-py/.coveragerc b/owl-bot-staging/google-geo-type/viewport-py/.coveragerc deleted file mode 100644 index e4af1d8d84ca..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/geo/type/__init__.py - google/geo/type/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-geo-type/viewport-py/.flake8 b/owl-bot-staging/google-geo-type/viewport-py/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/.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-geo-type/viewport-py/MANIFEST.in b/owl-bot-staging/google-geo-type/viewport-py/MANIFEST.in deleted file mode 100644 index 736f6f23c6ae..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/geo/type *.py -recursive-include google/geo/type *.py diff --git a/owl-bot-staging/google-geo-type/viewport-py/README.rst b/owl-bot-staging/google-geo-type/viewport-py/README.rst deleted file mode 100644 index 82c7fce9ba73..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Geo Type 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 Geo Type 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-geo-type/viewport-py/docs/_static/custom.css b/owl-bot-staging/google-geo-type/viewport-py/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-geo-type/viewport-py/docs/conf.py b/owl-bot-staging/google-geo-type/viewport-py/docs/conf.py deleted file mode 100644 index 0a0ece936017..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type 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-geo-type" -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 Geo 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-geo-type-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-geo-type.tex", - u"google-geo-type 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-geo-type", - u"Google Geo Type 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-geo-type", - u"google-geo-type Documentation", - author, - "google-geo-type", - "GAPIC library for Google Geo Type 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-geo-type/viewport-py/docs/index.rst b/owl-bot-staging/google-geo-type/viewport-py/docs/index.rst deleted file mode 100644 index 2605a730d688..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - type/services_ - type/types_ diff --git a/owl-bot-staging/google-geo-type/viewport-py/docs/type/services_.rst b/owl-bot-staging/google-geo-type/viewport-py/docs/type/services_.rst deleted file mode 100644 index dd35c5318c16..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/docs/type/services_.rst +++ /dev/null @@ -1,4 +0,0 @@ -Services for Google Geo Type API -================================= -.. toctree:: - :maxdepth: 2 diff --git a/owl-bot-staging/google-geo-type/viewport-py/docs/type/types_.rst b/owl-bot-staging/google-geo-type/viewport-py/docs/type/types_.rst deleted file mode 100644 index e35c4d36c639..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/docs/type/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Geo Type API -============================== - -.. automodule:: google.geo.type.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/__init__.py deleted file mode 100644 index 25f9431db757..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/__init__.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. -# -from google.geo.type import gapic_version as package_version - -__version__ = package_version.__version__ - - - -from .types.viewport import Viewport - -__all__ = ( -'Viewport', -) diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_metadata.json b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_metadata.json deleted file mode 100644 index 4be1a3ac6e07..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_metadata.json +++ /dev/null @@ -1,7 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.geo.type", - "protoPackage": "google.geo.type", - "schema": "1.0" -} diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_version.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/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-geo-type/viewport-py/google/geo/type/py.typed b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/py.typed deleted file mode 100644 index 0e339d46fd3d..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-geo-type package uses inline types. diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/services/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/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-geo-type/viewport-py/google/geo/type/types/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/__init__.py deleted file mode 100644 index c7e53503d3fb..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/__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 .viewport import ( - Viewport, -) - -__all__ = ( - 'Viewport', -) diff --git a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/viewport.py b/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/viewport.py deleted file mode 100644 index 745655ca0561..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/google/geo/type/types/viewport.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 __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.geo.type', - manifest={ - 'Viewport', - }, -) - - -class Viewport(proto.Message): - r"""A latitude-longitude viewport, represented as two diagonally - opposite ``low`` and ``high`` points. A viewport is considered a - closed region, i.e. it includes its boundary. The latitude bounds - must range between -90 to 90 degrees inclusive, and the longitude - bounds must range between -180 to 180 degrees inclusive. Various - cases include: - - - If ``low`` = ``high``, the viewport consists of that single - point. - - - If ``low.longitude`` > ``high.longitude``, the longitude range is - inverted (the viewport crosses the 180 degree longitude line). - - - If ``low.longitude`` = -180 degrees and ``high.longitude`` = 180 - degrees, the viewport includes all longitudes. - - - If ``low.longitude`` = 180 degrees and ``high.longitude`` = -180 - degrees, the longitude range is empty. - - - If ``low.latitude`` > ``high.latitude``, the latitude range is - empty. - - Both ``low`` and ``high`` must be populated, and the represented box - cannot be empty (as specified by the definitions above). An empty - viewport will result in an error. - - For example, this viewport fully encloses New York City: - - { "low": { "latitude": 40.477398, "longitude": -74.259087 }, "high": - { "latitude": 40.91618, "longitude": -73.70018 } } - - Attributes: - low (google.type.latlng_pb2.LatLng): - Required. The low point of the viewport. - high (google.type.latlng_pb2.LatLng): - Required. The high point of the viewport. - """ - - low: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - high: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=2, - message=latlng_pb2.LatLng, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-geo-type/viewport-py/mypy.ini b/owl-bot-staging/google-geo-type/viewport-py/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-geo-type/viewport-py/noxfile.py b/owl-bot-staging/google-geo-type/viewport-py/noxfile.py deleted file mode 100644 index 50140b2929b3..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type' - -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/geo/type/', - '--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/geo/type/', - '--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-geo-type/viewport-py/scripts/fixup_type_keywords.py b/owl-bot-staging/google-geo-type/viewport-py/scripts/fixup_type_keywords.py deleted file mode 100644 index bae51b8ecbd3..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/scripts/fixup_type_keywords.py +++ /dev/null @@ -1,175 +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 typeCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - } - - 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=typeCallTransformer(), -): - """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 type 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-geo-type/viewport-py/setup.py b/owl-bot-staging/google-geo-type/viewport-py/setup.py deleted file mode 100644 index aee4ccc5c261..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type' - - -description = "Google Geo Type API client library" - -version = None - -with open(os.path.join(package_root, 'google/geo/type/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-geo-type" - -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-geo-type/viewport-py/testing/constraints-3.10.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.11.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.12.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.7.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.8.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/testing/constraints-3.9.txt b/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/tests/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/tests/unit/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/tests/unit/gapic/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/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-geo-type/viewport-py/tests/unit/gapic/type/__init__.py b/owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/type/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-geo-type/viewport-py/tests/unit/gapic/type/__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-addressvalidation/v1/.coveragerc b/owl-bot-staging/google-maps-addressvalidation/v1/.coveragerc deleted file mode 100644 index e4692ea29e6d..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/addressvalidation/__init__.py - google/maps/addressvalidation/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-addressvalidation/v1/.flake8 b/owl-bot-staging/google-maps-addressvalidation/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/MANIFEST.in b/owl-bot-staging/google-maps-addressvalidation/v1/MANIFEST.in deleted file mode 100644 index 6d21915b6647..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/addressvalidation *.py -recursive-include google/maps/addressvalidation_v1 *.py diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/README.rst b/owl-bot-staging/google-maps-addressvalidation/v1/README.rst deleted file mode 100644 index 6bce085c3115..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Addressvalidation 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 Addressvalidation 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-addressvalidation/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-addressvalidation/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/docs/addressvalidation_v1/address_validation.rst b/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/address_validation.rst deleted file mode 100644 index bfcddd27291d..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/address_validation.rst +++ /dev/null @@ -1,6 +0,0 @@ -AddressValidation ------------------------------------ - -.. automodule:: google.maps.addressvalidation_v1.services.address_validation - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/services_.rst b/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/services_.rst deleted file mode 100644 index 44fb49f7a1cb..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Addressvalidation v1 API -================================================= -.. toctree:: - :maxdepth: 2 - - address_validation diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/types_.rst b/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/types_.rst deleted file mode 100644 index 454488a7c78b..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/docs/addressvalidation_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Addressvalidation v1 API -============================================== - -.. automodule:: google.maps.addressvalidation_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/docs/conf.py b/owl-bot-staging/google-maps-addressvalidation/v1/docs/conf.py deleted file mode 100644 index 9d5b6f3e706d..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation 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-addressvalidation" -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-addressvalidation-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-addressvalidation.tex", - u"google-maps-addressvalidation 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-addressvalidation", - u"Google Maps Addressvalidation 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-addressvalidation", - u"google-maps-addressvalidation Documentation", - author, - "google-maps-addressvalidation", - "GAPIC library for Google Maps Addressvalidation 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-addressvalidation/v1/docs/index.rst b/owl-bot-staging/google-maps-addressvalidation/v1/docs/index.rst deleted file mode 100644 index cd7722de7e1b..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - addressvalidation_v1/services_ - addressvalidation_v1/types_ diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/__init__.py deleted file mode 100644 index 96f9e6d5ca84..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/__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.addressvalidation import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.addressvalidation_v1.services.address_validation.client import AddressValidationClient -from google.maps.addressvalidation_v1.services.address_validation.async_client import AddressValidationAsyncClient - -from google.maps.addressvalidation_v1.types.address import Address -from google.maps.addressvalidation_v1.types.address import AddressComponent -from google.maps.addressvalidation_v1.types.address import ComponentName -from google.maps.addressvalidation_v1.types.address_validation_service import ProvideValidationFeedbackRequest -from google.maps.addressvalidation_v1.types.address_validation_service import ProvideValidationFeedbackResponse -from google.maps.addressvalidation_v1.types.address_validation_service import ValidateAddressRequest -from google.maps.addressvalidation_v1.types.address_validation_service import ValidateAddressResponse -from google.maps.addressvalidation_v1.types.address_validation_service import ValidationResult -from google.maps.addressvalidation_v1.types.address_validation_service import Verdict -from google.maps.addressvalidation_v1.types.geocode import Geocode -from google.maps.addressvalidation_v1.types.geocode import PlusCode -from google.maps.addressvalidation_v1.types.metadata_ import AddressMetadata -from google.maps.addressvalidation_v1.types.usps_data import UspsAddress -from google.maps.addressvalidation_v1.types.usps_data import UspsData - -__all__ = ('AddressValidationClient', - 'AddressValidationAsyncClient', - 'Address', - 'AddressComponent', - 'ComponentName', - 'ProvideValidationFeedbackRequest', - 'ProvideValidationFeedbackResponse', - 'ValidateAddressRequest', - 'ValidateAddressResponse', - 'ValidationResult', - 'Verdict', - 'Geocode', - 'PlusCode', - 'AddressMetadata', - 'UspsAddress', - 'UspsData', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/gapic_version.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/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-addressvalidation/v1/google/maps/addressvalidation/py.typed b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/py.typed deleted file mode 100644 index 1e46c59c8e22..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-addressvalidation package uses inline types. diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/__init__.py deleted file mode 100644 index b93f37bdcafd..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_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.addressvalidation_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.address_validation import AddressValidationClient -from .services.address_validation import AddressValidationAsyncClient - -from .types.address import Address -from .types.address import AddressComponent -from .types.address import ComponentName -from .types.address_validation_service import ProvideValidationFeedbackRequest -from .types.address_validation_service import ProvideValidationFeedbackResponse -from .types.address_validation_service import ValidateAddressRequest -from .types.address_validation_service import ValidateAddressResponse -from .types.address_validation_service import ValidationResult -from .types.address_validation_service import Verdict -from .types.geocode import Geocode -from .types.geocode import PlusCode -from .types.metadata_ import AddressMetadata -from .types.usps_data import UspsAddress -from .types.usps_data import UspsData - -__all__ = ( - 'AddressValidationAsyncClient', -'Address', -'AddressComponent', -'AddressMetadata', -'AddressValidationClient', -'ComponentName', -'Geocode', -'PlusCode', -'ProvideValidationFeedbackRequest', -'ProvideValidationFeedbackResponse', -'UspsAddress', -'UspsData', -'ValidateAddressRequest', -'ValidateAddressResponse', -'ValidationResult', -'Verdict', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_metadata.json b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_metadata.json deleted file mode 100644 index c521c066be76..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_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.addressvalidation_v1", - "protoPackage": "google.maps.addressvalidation.v1", - "schema": "1.0", - "services": { - "AddressValidation": { - "clients": { - "grpc": { - "libraryClient": "AddressValidationClient", - "rpcs": { - "ProvideValidationFeedback": { - "methods": [ - "provide_validation_feedback" - ] - }, - "ValidateAddress": { - "methods": [ - "validate_address" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AddressValidationAsyncClient", - "rpcs": { - "ProvideValidationFeedback": { - "methods": [ - "provide_validation_feedback" - ] - }, - "ValidateAddress": { - "methods": [ - "validate_address" - ] - } - } - }, - "rest": { - "libraryClient": "AddressValidationClient", - "rpcs": { - "ProvideValidationFeedback": { - "methods": [ - "provide_validation_feedback" - ] - }, - "ValidateAddress": { - "methods": [ - "validate_address" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_version.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_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-addressvalidation/v1/google/maps/addressvalidation_v1/py.typed b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/py.typed deleted file mode 100644 index 1e46c59c8e22..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-addressvalidation package uses inline types. diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_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-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/__init__.py deleted file mode 100644 index 913dcf3e63eb..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/__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 AddressValidationClient -from .async_client import AddressValidationAsyncClient - -__all__ = ( - 'AddressValidationClient', - 'AddressValidationAsyncClient', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/async_client.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/async_client.py deleted file mode 100644 index 5a472ca3006e..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/async_client.py +++ /dev/null @@ -1,392 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.maps.addressvalidation_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.addressvalidation_v1.types import address_validation_service -from .transports.base import AddressValidationTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AddressValidationGrpcAsyncIOTransport -from .client import AddressValidationClient - - -class AddressValidationAsyncClient: - """The service for validating addresses.""" - - _client: AddressValidationClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AddressValidationClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AddressValidationClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AddressValidationClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AddressValidationClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(AddressValidationClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AddressValidationClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AddressValidationClient.common_folder_path) - parse_common_folder_path = staticmethod(AddressValidationClient.parse_common_folder_path) - common_organization_path = staticmethod(AddressValidationClient.common_organization_path) - parse_common_organization_path = staticmethod(AddressValidationClient.parse_common_organization_path) - common_project_path = staticmethod(AddressValidationClient.common_project_path) - parse_common_project_path = staticmethod(AddressValidationClient.parse_common_project_path) - common_location_path = staticmethod(AddressValidationClient.common_location_path) - parse_common_location_path = staticmethod(AddressValidationClient.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: - AddressValidationAsyncClient: The constructed client. - """ - return AddressValidationClient.from_service_account_info.__func__(AddressValidationAsyncClient, 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: - AddressValidationAsyncClient: The constructed client. - """ - return AddressValidationClient.from_service_account_file.__func__(AddressValidationAsyncClient, 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 AddressValidationClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AddressValidationTransport: - """Returns the transport used by the client instance. - - Returns: - AddressValidationTransport: 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 = AddressValidationClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AddressValidationTransport, Callable[..., AddressValidationTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the address validation 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,AddressValidationTransport,Callable[..., AddressValidationTransport]]]): - 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 AddressValidationTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = AddressValidationClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def validate_address(self, - request: Optional[Union[address_validation_service.ValidateAddressRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> address_validation_service.ValidateAddressResponse: - r"""Validates an address. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 addressvalidation_v1 - - async def sample_validate_address(): - # Create a client - client = addressvalidation_v1.AddressValidationAsyncClient() - - # Initialize request argument(s) - request = addressvalidation_v1.ValidateAddressRequest( - ) - - # Make the request - response = await client.validate_address(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.addressvalidation_v1.types.ValidateAddressRequest, dict]]): - The request object. The request for validating an - address. - retry (google.api_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. - - Returns: - google.maps.addressvalidation_v1.types.ValidateAddressResponse: - The response to an address validation - request. - - """ - # 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, address_validation_service.ValidateAddressRequest): - request = address_validation_service.ValidateAddressRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.validate_address] - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def provide_validation_feedback(self, - request: Optional[Union[address_validation_service.ProvideValidationFeedbackRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> address_validation_service.ProvideValidationFeedbackResponse: - r"""Feedback about the outcome of the sequence of validation - attempts. This should be the last call made after a sequence of - validation calls for the same address, and should be called once - the transaction is concluded. This should only be sent once for - the sequence of ``ValidateAddress`` requests needed to validate - an address fully. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 addressvalidation_v1 - - async def sample_provide_validation_feedback(): - # Create a client - client = addressvalidation_v1.AddressValidationAsyncClient() - - # Initialize request argument(s) - request = addressvalidation_v1.ProvideValidationFeedbackRequest( - conclusion="UNUSED", - response_id="response_id_value", - ) - - # Make the request - response = await client.provide_validation_feedback(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest, dict]]): - The request object. The request for sending validation - feedback. - retry (google.api_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. - - Returns: - google.maps.addressvalidation_v1.types.ProvideValidationFeedbackResponse: - The response for validation feedback. - - The response is empty if the feedback is - sent successfully. - - """ - # 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, address_validation_service.ProvideValidationFeedbackRequest): - request = address_validation_service.ProvideValidationFeedbackRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.provide_validation_feedback] - - # Validate the universe domain. - self._client._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) -> "AddressValidationAsyncClient": - 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__ = ( - "AddressValidationAsyncClient", -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/client.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/client.py deleted file mode 100644 index bda137e9c64e..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/client.py +++ /dev/null @@ -1,740 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.maps.addressvalidation_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 - -from google.maps.addressvalidation_v1.types import address_validation_service -from .transports.base import AddressValidationTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AddressValidationGrpcTransport -from .transports.grpc_asyncio import AddressValidationGrpcAsyncIOTransport -from .transports.rest import AddressValidationRestTransport - - -class AddressValidationClientMeta(type): - """Metaclass for the AddressValidation 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[AddressValidationTransport]] - _transport_registry["grpc"] = AddressValidationGrpcTransport - _transport_registry["grpc_asyncio"] = AddressValidationGrpcAsyncIOTransport - _transport_registry["rest"] = AddressValidationRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AddressValidationTransport]: - """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 AddressValidationClient(metaclass=AddressValidationClientMeta): - """The service for validating addresses.""" - - @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 = "addressvalidation.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "addressvalidation.{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: - AddressValidationClient: 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: - AddressValidationClient: 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) -> AddressValidationTransport: - """Returns the transport used by the client instance. - - Returns: - AddressValidationTransport: 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 = AddressValidationClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AddressValidationClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AddressValidationClient._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 = AddressValidationClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AddressValidationClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - AddressValidationClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, AddressValidationTransport, Callable[..., AddressValidationTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the address validation client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AddressValidationTransport,Callable[..., AddressValidationTransport]]]): - 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 AddressValidationTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = AddressValidationClient._read_environment_variables() - self._client_cert_source = AddressValidationClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AddressValidationClient._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 - - 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, AddressValidationTransport) - if transport_provided: - # transport is a AddressValidationTransport 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(AddressValidationTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AddressValidationClient._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[AddressValidationTransport], Callable[..., AddressValidationTransport]] = ( - AddressValidationClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AddressValidationTransport], 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, - ) - - def validate_address(self, - request: Optional[Union[address_validation_service.ValidateAddressRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> address_validation_service.ValidateAddressResponse: - r"""Validates an address. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 addressvalidation_v1 - - def sample_validate_address(): - # Create a client - client = addressvalidation_v1.AddressValidationClient() - - # Initialize request argument(s) - request = addressvalidation_v1.ValidateAddressRequest( - ) - - # Make the request - response = client.validate_address(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.addressvalidation_v1.types.ValidateAddressRequest, dict]): - The request object. The request for validating an - address. - retry (google.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. - - Returns: - google.maps.addressvalidation_v1.types.ValidateAddressResponse: - The response to an address validation - request. - - """ - # 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, address_validation_service.ValidateAddressRequest): - request = address_validation_service.ValidateAddressRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_address] - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def provide_validation_feedback(self, - request: Optional[Union[address_validation_service.ProvideValidationFeedbackRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> address_validation_service.ProvideValidationFeedbackResponse: - r"""Feedback about the outcome of the sequence of validation - attempts. This should be the last call made after a sequence of - validation calls for the same address, and should be called once - the transaction is concluded. This should only be sent once for - the sequence of ``ValidateAddress`` requests needed to validate - an address fully. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 addressvalidation_v1 - - def sample_provide_validation_feedback(): - # Create a client - client = addressvalidation_v1.AddressValidationClient() - - # Initialize request argument(s) - request = addressvalidation_v1.ProvideValidationFeedbackRequest( - conclusion="UNUSED", - response_id="response_id_value", - ) - - # Make the request - response = client.provide_validation_feedback(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest, dict]): - The request object. The request for sending validation - feedback. - retry (google.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. - - Returns: - google.maps.addressvalidation_v1.types.ProvideValidationFeedbackResponse: - The response for validation feedback. - - The response is empty if the feedback is - sent successfully. - - """ - # 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, address_validation_service.ProvideValidationFeedbackRequest): - request = address_validation_service.ProvideValidationFeedbackRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.provide_validation_feedback] - - # Validate the universe 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) -> "AddressValidationClient": - 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__ = ( - "AddressValidationClient", -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/README.rst b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/README.rst deleted file mode 100644 index a4f79a60e995..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AddressValidationTransport` is the ABC for all transports. -- public child `AddressValidationGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AddressValidationGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAddressValidationRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AddressValidationRestTransport` 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-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/__init__.py deleted file mode 100644 index fb4627d8d61f..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/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 AddressValidationTransport -from .grpc import AddressValidationGrpcTransport -from .grpc_asyncio import AddressValidationGrpcAsyncIOTransport -from .rest import AddressValidationRestTransport -from .rest import AddressValidationRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AddressValidationTransport]] -_transport_registry['grpc'] = AddressValidationGrpcTransport -_transport_registry['grpc_asyncio'] = AddressValidationGrpcAsyncIOTransport -_transport_registry['rest'] = AddressValidationRestTransport - -__all__ = ( - 'AddressValidationTransport', - 'AddressValidationGrpcTransport', - 'AddressValidationGrpcAsyncIOTransport', - 'AddressValidationRestTransport', - 'AddressValidationRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/base.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/base.py deleted file mode 100644 index 031c80651d72..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/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.addressvalidation_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.addressvalidation_v1.types import address_validation_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AddressValidationTransport(abc.ABC): - """Abstract transport class for AddressValidation.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'addressvalidation.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: 'addressvalidation.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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.validate_address: gapic_v1.method.wrap_method( - self.validate_address, - default_timeout=None, - client_info=client_info, - ), - self.provide_validation_feedback: gapic_v1.method.wrap_method( - self.provide_validation_feedback, - 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 validate_address(self) -> Callable[ - [address_validation_service.ValidateAddressRequest], - Union[ - address_validation_service.ValidateAddressResponse, - Awaitable[address_validation_service.ValidateAddressResponse] - ]]: - raise NotImplementedError() - - @property - def provide_validation_feedback(self) -> Callable[ - [address_validation_service.ProvideValidationFeedbackRequest], - Union[ - address_validation_service.ProvideValidationFeedbackResponse, - Awaitable[address_validation_service.ProvideValidationFeedbackResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AddressValidationTransport', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc.py deleted file mode 100644 index c88998ac09c9..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc.py +++ /dev/null @@ -1,301 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.maps.addressvalidation_v1.types import address_validation_service -from .base import AddressValidationTransport, DEFAULT_CLIENT_INFO - - -class AddressValidationGrpcTransport(AddressValidationTransport): - """gRPC backend transport for AddressValidation. - - The service for validating addresses. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'addressvalidation.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: 'addressvalidation.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'addressvalidation.googleapis.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 validate_address(self) -> Callable[ - [address_validation_service.ValidateAddressRequest], - address_validation_service.ValidateAddressResponse]: - r"""Return a callable for the validate address method over gRPC. - - Validates an address. - - Returns: - Callable[[~.ValidateAddressRequest], - ~.ValidateAddressResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_address' not in self._stubs: - self._stubs['validate_address'] = self.grpc_channel.unary_unary( - '/google.maps.addressvalidation.v1.AddressValidation/ValidateAddress', - request_serializer=address_validation_service.ValidateAddressRequest.serialize, - response_deserializer=address_validation_service.ValidateAddressResponse.deserialize, - ) - return self._stubs['validate_address'] - - @property - def provide_validation_feedback(self) -> Callable[ - [address_validation_service.ProvideValidationFeedbackRequest], - address_validation_service.ProvideValidationFeedbackResponse]: - r"""Return a callable for the provide validation feedback method over gRPC. - - Feedback about the outcome of the sequence of validation - attempts. This should be the last call made after a sequence of - validation calls for the same address, and should be called once - the transaction is concluded. This should only be sent once for - the sequence of ``ValidateAddress`` requests needed to validate - an address fully. - - Returns: - Callable[[~.ProvideValidationFeedbackRequest], - ~.ProvideValidationFeedbackResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'provide_validation_feedback' not in self._stubs: - self._stubs['provide_validation_feedback'] = self.grpc_channel.unary_unary( - '/google.maps.addressvalidation.v1.AddressValidation/ProvideValidationFeedback', - request_serializer=address_validation_service.ProvideValidationFeedbackRequest.serialize, - response_deserializer=address_validation_service.ProvideValidationFeedbackResponse.deserialize, - ) - return self._stubs['provide_validation_feedback'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AddressValidationGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc_asyncio.py deleted file mode 100644 index 08c85a976410..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/grpc_asyncio.py +++ /dev/null @@ -1,327 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.addressvalidation_v1.types import address_validation_service -from .base import AddressValidationTransport, DEFAULT_CLIENT_INFO -from .grpc import AddressValidationGrpcTransport - - -class AddressValidationGrpcAsyncIOTransport(AddressValidationTransport): - """gRPC AsyncIO backend transport for AddressValidation. - - The service for validating addresses. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'addressvalidation.googleapis.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 = 'addressvalidation.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: 'addressvalidation.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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 validate_address(self) -> Callable[ - [address_validation_service.ValidateAddressRequest], - Awaitable[address_validation_service.ValidateAddressResponse]]: - r"""Return a callable for the validate address method over gRPC. - - Validates an address. - - Returns: - Callable[[~.ValidateAddressRequest], - Awaitable[~.ValidateAddressResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_address' not in self._stubs: - self._stubs['validate_address'] = self.grpc_channel.unary_unary( - '/google.maps.addressvalidation.v1.AddressValidation/ValidateAddress', - request_serializer=address_validation_service.ValidateAddressRequest.serialize, - response_deserializer=address_validation_service.ValidateAddressResponse.deserialize, - ) - return self._stubs['validate_address'] - - @property - def provide_validation_feedback(self) -> Callable[ - [address_validation_service.ProvideValidationFeedbackRequest], - Awaitable[address_validation_service.ProvideValidationFeedbackResponse]]: - r"""Return a callable for the provide validation feedback method over gRPC. - - Feedback about the outcome of the sequence of validation - attempts. This should be the last call made after a sequence of - validation calls for the same address, and should be called once - the transaction is concluded. This should only be sent once for - the sequence of ``ValidateAddress`` requests needed to validate - an address fully. - - Returns: - Callable[[~.ProvideValidationFeedbackRequest], - Awaitable[~.ProvideValidationFeedbackResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'provide_validation_feedback' not in self._stubs: - self._stubs['provide_validation_feedback'] = self.grpc_channel.unary_unary( - '/google.maps.addressvalidation.v1.AddressValidation/ProvideValidationFeedback', - request_serializer=address_validation_service.ProvideValidationFeedbackRequest.serialize, - response_deserializer=address_validation_service.ProvideValidationFeedbackResponse.deserialize, - ) - return self._stubs['provide_validation_feedback'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.validate_address: self._wrap_method( - self.validate_address, - default_timeout=None, - client_info=client_info, - ), - self.provide_validation_feedback: self._wrap_method( - self.provide_validation_feedback, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'AddressValidationGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py deleted file mode 100644 index 7f8c3885e117..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest.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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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.addressvalidation_v1.types import address_validation_service - - -from .rest_base import _BaseAddressValidationRestTransport -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 - - -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 AddressValidationRestInterceptor: - """Interceptor for AddressValidation. - - 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 AddressValidationRestTransport. - - .. code-block:: python - class MyCustomAddressValidationInterceptor(AddressValidationRestInterceptor): - def pre_provide_validation_feedback(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_provide_validation_feedback(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_validate_address(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_validate_address(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AddressValidationRestTransport(interceptor=MyCustomAddressValidationInterceptor()) - client = AddressValidationClient(transport=transport) - - - """ - def pre_provide_validation_feedback(self, request: address_validation_service.ProvideValidationFeedbackRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[address_validation_service.ProvideValidationFeedbackRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for provide_validation_feedback - - Override in a subclass to manipulate the request or metadata - before they are sent to the AddressValidation server. - """ - return request, metadata - - def post_provide_validation_feedback(self, response: address_validation_service.ProvideValidationFeedbackResponse) -> address_validation_service.ProvideValidationFeedbackResponse: - """Post-rpc interceptor for provide_validation_feedback - - Override in a subclass to manipulate the response - after it is returned by the AddressValidation server but before - it is returned to user code. - """ - return response - - def pre_validate_address(self, request: address_validation_service.ValidateAddressRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[address_validation_service.ValidateAddressRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for validate_address - - Override in a subclass to manipulate the request or metadata - before they are sent to the AddressValidation server. - """ - return request, metadata - - def post_validate_address(self, response: address_validation_service.ValidateAddressResponse) -> address_validation_service.ValidateAddressResponse: - """Post-rpc interceptor for validate_address - - Override in a subclass to manipulate the response - after it is returned by the AddressValidation server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AddressValidationRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AddressValidationRestInterceptor - - -class AddressValidationRestTransport(_BaseAddressValidationRestTransport): - """REST backend synchronous transport for AddressValidation. - - The service for validating addresses. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'addressvalidation.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[AddressValidationRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'addressvalidation.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 AddressValidationRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ProvideValidationFeedback(_BaseAddressValidationRestTransport._BaseProvideValidationFeedback, AddressValidationRestStub): - def __hash__(self): - return hash("AddressValidationRestTransport.ProvideValidationFeedback") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: address_validation_service.ProvideValidationFeedbackRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> address_validation_service.ProvideValidationFeedbackResponse: - r"""Call the provide validation - feedback method over HTTP. - - Args: - request (~.address_validation_service.ProvideValidationFeedbackRequest): - The request object. The request for sending validation - feedback. - retry (google.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. - - Returns: - ~.address_validation_service.ProvideValidationFeedbackResponse: - The response for validation feedback. - - The response is empty if the feedback is - sent successfully. - - """ - - http_options = _BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_http_options() - request, metadata = self._interceptor.pre_provide_validation_feedback(request, metadata) - transcoded_request = _BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_transcoded_request(http_options, request) - - body = _BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_query_params_json(transcoded_request) - - # Send the request - response = AddressValidationRestTransport._ProvideValidationFeedback._get_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 = address_validation_service.ProvideValidationFeedbackResponse() - pb_resp = address_validation_service.ProvideValidationFeedbackResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_provide_validation_feedback(resp) - return resp - - class _ValidateAddress(_BaseAddressValidationRestTransport._BaseValidateAddress, AddressValidationRestStub): - def __hash__(self): - return hash("AddressValidationRestTransport.ValidateAddress") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: address_validation_service.ValidateAddressRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> address_validation_service.ValidateAddressResponse: - r"""Call the validate address method over HTTP. - - Args: - request (~.address_validation_service.ValidateAddressRequest): - The request object. The request for validating an - address. - retry (google.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. - - Returns: - ~.address_validation_service.ValidateAddressResponse: - The response to an address validation - request. - - """ - - http_options = _BaseAddressValidationRestTransport._BaseValidateAddress._get_http_options() - request, metadata = self._interceptor.pre_validate_address(request, metadata) - transcoded_request = _BaseAddressValidationRestTransport._BaseValidateAddress._get_transcoded_request(http_options, request) - - body = _BaseAddressValidationRestTransport._BaseValidateAddress._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAddressValidationRestTransport._BaseValidateAddress._get_query_params_json(transcoded_request) - - # Send the request - response = AddressValidationRestTransport._ValidateAddress._get_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 = address_validation_service.ValidateAddressResponse() - pb_resp = address_validation_service.ValidateAddressResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_validate_address(resp) - return resp - - @property - def provide_validation_feedback(self) -> Callable[ - [address_validation_service.ProvideValidationFeedbackRequest], - address_validation_service.ProvideValidationFeedbackResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ProvideValidationFeedback(self._session, self._host, self._interceptor) # type: ignore - - @property - def validate_address(self) -> Callable[ - [address_validation_service.ValidateAddressRequest], - address_validation_service.ValidateAddressResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ValidateAddress(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AddressValidationRestTransport', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest_base.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/transports/rest_base.py deleted file mode 100644 index b44693398055..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/services/address_validation/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 AddressValidationTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.maps.addressvalidation_v1.types import address_validation_service - - -class _BaseAddressValidationRestTransport(AddressValidationTransport): - """Base REST backend transport for AddressValidation. - - 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 = 'addressvalidation.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: 'addressvalidation.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 _BaseProvideValidationFeedback: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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:provideValidationFeedback', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = address_validation_service.ProvideValidationFeedbackRequest.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(_BaseAddressValidationRestTransport._BaseProvideValidationFeedback._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseValidateAddress: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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:validateAddress', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = address_validation_service.ValidateAddressRequest.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(_BaseAddressValidationRestTransport._BaseValidateAddress._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseAddressValidationRestTransport', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/__init__.py deleted file mode 100644 index c261d0bfa001..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/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 .address import ( - Address, - AddressComponent, - ComponentName, -) -from .address_validation_service import ( - ProvideValidationFeedbackRequest, - ProvideValidationFeedbackResponse, - ValidateAddressRequest, - ValidateAddressResponse, - ValidationResult, - Verdict, -) -from .geocode import ( - Geocode, - PlusCode, -) -from .metadata_ import ( - AddressMetadata, -) -from .usps_data import ( - UspsAddress, - UspsData, -) - -__all__ = ( - 'Address', - 'AddressComponent', - 'ComponentName', - 'ProvideValidationFeedbackRequest', - 'ProvideValidationFeedbackResponse', - 'ValidateAddressRequest', - 'ValidateAddressResponse', - 'ValidationResult', - 'Verdict', - 'Geocode', - 'PlusCode', - 'AddressMetadata', - 'UspsAddress', - 'UspsData', -) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address.py deleted file mode 100644 index 9af37ec7d243..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.type import postal_address_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.addressvalidation.v1', - manifest={ - 'Address', - 'AddressComponent', - 'ComponentName', - }, -) - - -class Address(proto.Message): - r"""Details of the post-processed address. Post-processing - includes correcting misspelled parts of the address, replacing - incorrect parts, and inferring missing parts. - - Attributes: - formatted_address (str): - The post-processed address, formatted as a - single-line address following the address - formatting rules of the region where the address - is located. - postal_address (google.type.postal_address_pb2.PostalAddress): - The post-processed address represented as a - postal address. - address_components (MutableSequence[google.maps.addressvalidation_v1.types.AddressComponent]): - Unordered list. The individual address - components of the formatted and corrected - address, along with validation information. This - provides information on the validation status of - the individual components. - - Address components are not ordered in a - particular way. Do not make any assumptions on - the ordering of the address components in the - list. - missing_component_types (MutableSequence[str]): - The types of components that were expected to be present in - a correctly formatted mailing address but were not found in - the input AND could not be inferred. Components of this type - are not present in ``formatted_address``, - ``postal_address``, or ``address_components``. An example - might be ``['street_number', 'route']`` for an input like - "Boulder, Colorado, 80301, USA". The list of possible types - can be found - `here `__. - unconfirmed_component_types (MutableSequence[str]): - The types of the components that are present in the - ``address_components`` but could not be confirmed to be - correct. This field is provided for the sake of convenience: - its contents are equivalent to iterating through the - ``address_components`` to find the types of all the - components where the - [confirmation_level][google.maps.addressvalidation.v1.AddressComponent.confirmation_level] - is not - [CONFIRMED][google.maps.addressvalidation.v1.AddressComponent.ConfirmationLevel.CONFIRMED] - or the - [inferred][google.maps.addressvalidation.v1.AddressComponent.inferred] - flag is not set to ``true``. The list of possible types can - be found - `here `__. - unresolved_tokens (MutableSequence[str]): - Any tokens in the input that could not be resolved. This - might be an input that was not recognized as a valid part of - an address (for example in an input like "123235253253 Main - St, San Francisco, CA, 94105", the unresolved tokens may - look like ``["123235253253"]`` since that does not look like - a valid street number. - """ - - formatted_address: str = proto.Field( - proto.STRING, - number=2, - ) - postal_address: postal_address_pb2.PostalAddress = proto.Field( - proto.MESSAGE, - number=3, - message=postal_address_pb2.PostalAddress, - ) - address_components: MutableSequence['AddressComponent'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='AddressComponent', - ) - missing_component_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - unconfirmed_component_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - unresolved_tokens: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - - -class AddressComponent(proto.Message): - r"""Represents an address component, such as a street, city, or - state. - - Attributes: - component_name (google.maps.addressvalidation_v1.types.ComponentName): - The name for this component. - component_type (str): - The type of the address component. See `Table 2: Additional - types returned by the Places - service `__ - for a list of possible types. - confirmation_level (google.maps.addressvalidation_v1.types.AddressComponent.ConfirmationLevel): - Indicates the level of certainty that we have - that the component is correct. - inferred (bool): - Indicates that the component was not part of - the input, but we inferred it for the address - location and believe it should be provided for a - complete address. - spell_corrected (bool): - Indicates a correction to a misspelling in - the component name. The API does not always - flag changes from one spelling variant to - another, such as when changing "centre" to - "center". It also does not always flag common - misspellings, such as when changing - "Amphitheater Pkwy" to "Amphitheatre Pkwy". - replaced (bool): - Indicates the name of the component was - replaced with a completely different one, for - example a wrong postal code being replaced with - one that is correct for the address. This is not - a cosmetic change, the input component has been - changed to a different one. - unexpected (bool): - Indicates an address component that is not - expected to be present in a postal address for - the given region. We have retained it only - because it was part of the input. - """ - class ConfirmationLevel(proto.Enum): - r"""The different possible values for confirmation levels. - - Values: - CONFIRMATION_LEVEL_UNSPECIFIED (0): - Default value. This value is unused. - CONFIRMED (1): - We were able to verify that this component - exists and makes sense in the context of the - rest of the address. - UNCONFIRMED_BUT_PLAUSIBLE (2): - This component could not be confirmed, but it - is plausible that it exists. For example, a - street number within a known valid range of - numbers on a street where specific house numbers - are not known. - UNCONFIRMED_AND_SUSPICIOUS (3): - This component was not confirmed and is - likely to be wrong. For example, a neighborhood - that does not fit the rest of the address. - """ - CONFIRMATION_LEVEL_UNSPECIFIED = 0 - CONFIRMED = 1 - UNCONFIRMED_BUT_PLAUSIBLE = 2 - UNCONFIRMED_AND_SUSPICIOUS = 3 - - component_name: 'ComponentName' = proto.Field( - proto.MESSAGE, - number=1, - message='ComponentName', - ) - component_type: str = proto.Field( - proto.STRING, - number=2, - ) - confirmation_level: ConfirmationLevel = proto.Field( - proto.ENUM, - number=3, - enum=ConfirmationLevel, - ) - inferred: bool = proto.Field( - proto.BOOL, - number=4, - ) - spell_corrected: bool = proto.Field( - proto.BOOL, - number=5, - ) - replaced: bool = proto.Field( - proto.BOOL, - number=6, - ) - unexpected: bool = proto.Field( - proto.BOOL, - number=7, - ) - - -class ComponentName(proto.Message): - r"""A wrapper for the name of the component. - - Attributes: - text (str): - The name text. For example, "5th Avenue" for - a street name or "1253" for a street number. - language_code (str): - The BCP-47 language code. This will not be - present if the component name is not associated - with a language, such as a street number. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address_validation_service.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address_validation_service.py deleted file mode 100644 index b9af9ae8fbf6..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/address_validation_service.py +++ /dev/null @@ -1,413 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.addressvalidation_v1.types import address as gma_address -from google.maps.addressvalidation_v1.types import geocode as gma_geocode -from google.maps.addressvalidation_v1.types import metadata_ -from google.maps.addressvalidation_v1.types import usps_data as gma_usps_data -from google.type import postal_address_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.addressvalidation.v1', - manifest={ - 'ValidateAddressRequest', - 'ValidateAddressResponse', - 'ProvideValidationFeedbackRequest', - 'ProvideValidationFeedbackResponse', - 'ValidationResult', - 'Verdict', - }, -) - - -class ValidateAddressRequest(proto.Message): - r"""The request for validating an address. - - Attributes: - address (google.type.postal_address_pb2.PostalAddress): - Required. The address being validated. Unformatted addresses - should be submitted via - [``address_lines``][google.type.PostalAddress.address_lines]. - - The total length of the fields in this input must not exceed - 280 characters. - - Supported regions can be found - `here `__. - - The [language_code][google.type.PostalAddress.language_code] - value in the input address is reserved for future uses and - is ignored today. The validated address result will be - populated based on the preferred language for the given - address, as identified by the system. - - The Address Validation API ignores the values in - [recipients][google.type.PostalAddress.recipients] and - [organization][google.type.PostalAddress.organization]. Any - values in those fields will be discarded and not returned. - Please do not set them. - previous_response_id (str): - This field must be empty for the first address validation - request. If more requests are necessary to fully validate a - single address (for example if the changes the user makes - after the initial validation need to be re-validated), then - each followup request must populate this field with the - [response_id][google.maps.addressvalidation.v1.ValidateAddressResponse.response_id] - from the very first response in the validation sequence. - enable_usps_cass (bool): - Enables USPS CASS compatible mode. This affects *only* the - [google.maps.addressvalidation.v1.ValidationResult.usps_data] - field of - [google.maps.addressvalidation.v1.ValidationResult]. Note: - for USPS CASS enabled requests for addresses in Puerto Rico, - a [google.type.PostalAddress.region_code] of the ``address`` - must be provided as "PR", or an - [google.type.PostalAddress.administrative_area] of the - ``address`` must be provided as "Puerto Rico" - (case-insensitive) or "PR". - - It's recommended to use a componentized ``address``, or - alternatively specify at least two - [google.type.PostalAddress.address_lines] where the first - line contains the street number and name and the second line - contains the city, state, and zip code. - 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 autocomplete 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). - - Note: Address Validation can only be used in sessions with - the Autocomplete (New) API, not the old Autocomplete API. - See - https://developers.google.com/maps/documentation/places/web-service/session-pricing - for more details. - """ - - address: postal_address_pb2.PostalAddress = proto.Field( - proto.MESSAGE, - number=1, - message=postal_address_pb2.PostalAddress, - ) - previous_response_id: str = proto.Field( - proto.STRING, - number=2, - ) - enable_usps_cass: bool = proto.Field( - proto.BOOL, - number=3, - ) - session_token: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ValidateAddressResponse(proto.Message): - r"""The response to an address validation request. - - Attributes: - result (google.maps.addressvalidation_v1.types.ValidationResult): - The result of the address validation. - response_id (str): - The UUID that identifies this response. If the address needs - to be re-validated, this UUID *must* accompany the new - request. - """ - - result: 'ValidationResult' = proto.Field( - proto.MESSAGE, - number=1, - message='ValidationResult', - ) - response_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ProvideValidationFeedbackRequest(proto.Message): - r"""The request for sending validation feedback. - - Attributes: - conclusion (google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest.ValidationConclusion): - Required. The outcome of the sequence of validation - attempts. - - If this field is set to - ``VALIDATION_CONCLUSION_UNSPECIFIED``, an - ``INVALID_ARGUMENT`` error will be returned. - response_id (str): - Required. The ID of the response that this feedback is for. - This should be the - [response_id][google.maps.addressvalidation.v1.ValidateAddressRequest.response_id] - from the first response in a series of address validation - attempts. - """ - class ValidationConclusion(proto.Enum): - r"""The possible final outcomes of the sequence of address - validation requests needed to validate an address. - - Values: - VALIDATION_CONCLUSION_UNSPECIFIED (0): - This value is unused. If the - ``ProvideValidationFeedbackRequest.conclusion`` field is set - to ``VALIDATION_CONCLUSION_UNSPECIFIED``, an - ``INVALID_ARGUMENT`` error will be returned. - VALIDATED_VERSION_USED (1): - The version of the address returned by the - Address Validation API was used for the - transaction. - USER_VERSION_USED (2): - The version of the address provided by the - user was used for the transaction - UNVALIDATED_VERSION_USED (3): - A version of the address that was entered - after the last validation attempt but that was - not re-validated was used for the transaction. - UNUSED (4): - The transaction was abandoned and the address - was not used. - """ - VALIDATION_CONCLUSION_UNSPECIFIED = 0 - VALIDATED_VERSION_USED = 1 - USER_VERSION_USED = 2 - UNVALIDATED_VERSION_USED = 3 - UNUSED = 4 - - conclusion: ValidationConclusion = proto.Field( - proto.ENUM, - number=1, - enum=ValidationConclusion, - ) - response_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ProvideValidationFeedbackResponse(proto.Message): - r"""The response for validation feedback. - - The response is empty if the feedback is sent successfully. - - """ - - -class ValidationResult(proto.Message): - r"""The result of validating an address. - - Attributes: - verdict (google.maps.addressvalidation_v1.types.Verdict): - Overall verdict flags - address (google.maps.addressvalidation_v1.types.Address): - Information about the address itself as - opposed to the geocode. - geocode (google.maps.addressvalidation_v1.types.Geocode): - Information about the location and place that - the address geocoded to. - metadata (google.maps.addressvalidation_v1.types.AddressMetadata): - Other information relevant to deliverability. ``metadata`` - is not guaranteed to be fully populated for every address - sent to the Address Validation API. - usps_data (google.maps.addressvalidation_v1.types.UspsData): - Extra deliverability flags provided by USPS. Only provided - in region ``US`` and ``PR``. - """ - - verdict: 'Verdict' = proto.Field( - proto.MESSAGE, - number=1, - message='Verdict', - ) - address: gma_address.Address = proto.Field( - proto.MESSAGE, - number=2, - message=gma_address.Address, - ) - geocode: gma_geocode.Geocode = proto.Field( - proto.MESSAGE, - number=3, - message=gma_geocode.Geocode, - ) - metadata: metadata_.AddressMetadata = proto.Field( - proto.MESSAGE, - number=4, - message=metadata_.AddressMetadata, - ) - usps_data: gma_usps_data.UspsData = proto.Field( - proto.MESSAGE, - number=5, - message=gma_usps_data.UspsData, - ) - - -class Verdict(proto.Message): - r"""High level overview of the address validation result and - geocode. - - Attributes: - input_granularity (google.maps.addressvalidation_v1.types.Verdict.Granularity): - The granularity of the **input** address. This is the result - of parsing the input address and does not give any - validation signals. For validation signals, refer to - ``validation_granularity`` below. - - For example, if the input address includes a specific - apartment number, then the ``input_granularity`` here will - be ``SUB_PREMISE``. If we cannot match the apartment number - in the databases or the apartment number is invalid, the - ``validation_granularity`` will likely be ``PREMISE`` or - below. - validation_granularity (google.maps.addressvalidation_v1.types.Verdict.Granularity): - The granularity level that the API can fully **validate** - the address to. For example, an ``validation_granularity`` - of ``PREMISE`` indicates all address components at the level - of ``PREMISE`` or more coarse can be validated. - - Per address component validation result can be found in - [google.maps.addressvalidation.v1.Address.address_components]. - geocode_granularity (google.maps.addressvalidation_v1.types.Verdict.Granularity): - Information about the granularity of the - [``geocode``][google.maps.addressvalidation.v1.ValidationResult.geocode]. - This can be understood as the semantic meaning of how coarse - or fine the geocoded location is. - - This can differ from the ``validation_granularity`` above - occasionally. For example, our database might record the - existence of an apartment number but do not have a precise - location for the apartment within a big apartment complex. - In that case, the ``validation_granularity`` will be - ``SUB_PREMISE`` but the ``geocode_granularity`` will be - ``PREMISE``. - address_complete (bool): - The address is considered complete if there are no - unresolved tokens, no unexpected or missing address - components. See - [``missing_component_types``][google.maps.addressvalidation.v1.Address.missing_component_types], - [``unresolved_tokens``][google.maps.addressvalidation.v1.Address.unresolved_tokens] - or - [``unexpected``][google.maps.addressvalidation.v1.AddressComponent.unexpected] - fields for more details. - has_unconfirmed_components (bool): - At least one address component cannot be categorized or - validated, see - [google.maps.addressvalidation.v1.Address.address_components] - for details. - has_inferred_components (bool): - At least one address component was inferred (added) that - wasn't in the input, see - [google.maps.addressvalidation.v1.Address.address_components] - for details. - has_replaced_components (bool): - At least one address component was replaced, see - [google.maps.addressvalidation.v1.Address.address_components] - for details. - """ - class Granularity(proto.Enum): - r"""The various granularities that an address or a geocode can have. - When used to indicate granularity for an *address*, these values - indicate with how fine a granularity the address identifies a - mailing destination. For example, an address such as "123 Main - Street, Redwood City, CA, 94061" identifies a ``PREMISE`` while - something like "Redwood City, CA, 94061" identifies a ``LOCALITY``. - However, if we are unable to find a geocode for "123 Main Street" in - Redwood City, the geocode returned might be of ``LOCALITY`` - granularity even though the address is more granular. - - Values: - GRANULARITY_UNSPECIFIED (0): - Default value. This value is unused. - SUB_PREMISE (1): - Below-building level result, such as an - apartment. - PREMISE (2): - Building-level result. - PREMISE_PROXIMITY (3): - A geocode that approximates the - building-level location of the address. - BLOCK (4): - The address or geocode indicates a block. - Only used in regions which have block-level - addressing, such as Japan. - ROUTE (5): - The geocode or address is granular to route, - such as a street, road, or highway. - OTHER (6): - All other granularities, which are bucketed - together since they are not deliverable. - """ - GRANULARITY_UNSPECIFIED = 0 - SUB_PREMISE = 1 - PREMISE = 2 - PREMISE_PROXIMITY = 3 - BLOCK = 4 - ROUTE = 5 - OTHER = 6 - - input_granularity: Granularity = proto.Field( - proto.ENUM, - number=1, - enum=Granularity, - ) - validation_granularity: Granularity = proto.Field( - proto.ENUM, - number=2, - enum=Granularity, - ) - geocode_granularity: Granularity = proto.Field( - proto.ENUM, - number=3, - enum=Granularity, - ) - address_complete: bool = proto.Field( - proto.BOOL, - number=4, - ) - has_unconfirmed_components: bool = proto.Field( - proto.BOOL, - number=5, - ) - has_inferred_components: bool = proto.Field( - proto.BOOL, - number=6, - ) - has_replaced_components: bool = proto.Field( - proto.BOOL, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/geocode.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/geocode.py deleted file mode 100644 index 4e2d66b9ba63..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/geocode.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.addressvalidation.v1', - manifest={ - 'Geocode', - 'PlusCode', - }, -) - - -class Geocode(proto.Message): - r"""Contains information about the place the input was geocoded - to. - - Attributes: - location (google.type.latlng_pb2.LatLng): - The geocoded location of the input. - - Using place IDs is preferred over using - addresses, latitude/longitude coordinates, or - plus codes. Using coordinates when routing or - calculating driving directions will always - result in the point being snapped to the road - nearest to those coordinates. This may not be a - road that will quickly or safely lead to the - destination and may not be near an access point - to the property. Additionally, when a location - is reverse geocoded, there is no guarantee that - the returned address will match the original. - plus_code (google.maps.addressvalidation_v1.types.PlusCode): - The plus code corresponding to the ``location``. - bounds (google.geo.type.types.Viewport): - The bounds of the geocoded place. - feature_size_meters (float): - The size of the geocoded place, in meters. - This is another measure of the coarseness of the - geocoded location, but in physical size rather - than in semantic meaning. - place_id (str): - The PlaceID of the place this input geocodes to. - - For more information about Place IDs see - `here `__. - place_types (MutableSequence[str]): - The type(s) of place that the input geocoded to. For - example, ``['locality', 'political']``. The full list of - types can be found - `here `__. - """ - - location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - plus_code: 'PlusCode' = proto.Field( - proto.MESSAGE, - number=2, - message='PlusCode', - ) - bounds: viewport.Viewport = proto.Field( - proto.MESSAGE, - number=4, - message=viewport.Viewport, - ) - feature_size_meters: float = proto.Field( - proto.FLOAT, - number=5, - ) - place_id: str = proto.Field( - proto.STRING, - number=6, - ) - place_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - - -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, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/metadata_.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/metadata_.py deleted file mode 100644 index 79a1779dd9f6..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/metadata_.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.addressvalidation.v1', - manifest={ - 'AddressMetadata', - }, -) - - -class AddressMetadata(proto.Message): - r"""The metadata for the address. ``metadata`` is not guaranteed to be - fully populated for every address sent to the Address Validation - API. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - business (bool): - Indicates that this is the address of a - business. If unset, indicates that the value is - unknown. - - This field is a member of `oneof`_ ``_business``. - po_box (bool): - Indicates that the address of a PO box. - If unset, indicates that the value is unknown. - - This field is a member of `oneof`_ ``_po_box``. - residential (bool): - Indicates that this is the address of a - residence. If unset, indicates that the value is - unknown. - - This field is a member of `oneof`_ ``_residential``. - """ - - business: bool = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - po_box: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - residential: bool = proto.Field( - proto.BOOL, - number=6, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/usps_data.py b/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/usps_data.py deleted file mode 100644 index 5c99d6ab4462..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/google/maps/addressvalidation_v1/types/usps_data.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.addressvalidation.v1', - manifest={ - 'UspsAddress', - 'UspsData', - }, -) - - -class UspsAddress(proto.Message): - r"""USPS representation of a US address. - - Attributes: - first_address_line (str): - First address line. - firm (str): - Firm name. - second_address_line (str): - Second address line. - urbanization (str): - Puerto Rican urbanization name. - city_state_zip_address_line (str): - City + state + postal code. - city (str): - City name. - state (str): - 2 letter state code. - zip_code (str): - Postal code e.g. 10009. - zip_code_extension (str): - 4-digit postal code extension e.g. 5023. - """ - - first_address_line: str = proto.Field( - proto.STRING, - number=1, - ) - firm: str = proto.Field( - proto.STRING, - number=2, - ) - second_address_line: str = proto.Field( - proto.STRING, - number=3, - ) - urbanization: str = proto.Field( - proto.STRING, - number=4, - ) - city_state_zip_address_line: str = proto.Field( - proto.STRING, - number=5, - ) - city: str = proto.Field( - proto.STRING, - number=6, - ) - state: str = proto.Field( - proto.STRING, - number=7, - ) - zip_code: str = proto.Field( - proto.STRING, - number=8, - ) - zip_code_extension: str = proto.Field( - proto.STRING, - number=9, - ) - - -class UspsData(proto.Message): - r"""The USPS data for the address. ``uspsData`` is not guaranteed to be - fully populated for every US or PR address sent to the Address - Validation API. It's recommended to integrate the backup address - fields in the response if you utilize uspsData as the primary part - of the response. - - Attributes: - standardized_address (google.maps.addressvalidation_v1.types.UspsAddress): - USPS standardized address. - delivery_point_code (str): - 2 digit delivery point code - delivery_point_check_digit (str): - The delivery point check digit. This number is added to the - end of the delivery_point_barcode for mechanically scanned - mail. Adding all the digits of the delivery_point_barcode, - delivery_point_check_digit, postal code, and ZIP+4 together - should yield a number divisible by 10. - dpv_confirmation (str): - The possible values for DPV confirmation. Returns a single - character or returns no value. - - - ``N``: Primary and any secondary number information - failed to DPV confirm. - - ``D``: Address was DPV confirmed for the primary number - only, and the secondary number information was missing. - - ``S``: Address was DPV confirmed for the primary number - only, and the secondary number information was present - but not confirmed. - - ``Y``: Address was DPV confirmed for primary and any - secondary numbers. - - Empty: If the response does not contain a - ``dpv_confirmation`` value, the address was not submitted - for DPV confirmation. - dpv_footnote (str): - The footnotes from delivery point validation. Multiple - footnotes may be strung together in the same string. - - - ``AA``: Input address matched to the ZIP+4 file - - ``A1``: Input address was not matched to the ZIP+4 file - - ``BB``: Matched to DPV (all components) - - ``CC``: Secondary number not matched and not required - - ``C1``: Secondary number not matched but required - - ``N1``: High-rise address missing secondary number - - ``M1``: Primary number missing - - ``M3``: Primary number invalid - - ``P1``: Input address PO, RR or HC box number missing - - ``P3``: Input address PO, RR, or HC Box number invalid - - ``F1``: Input address matched to a military address - - ``G1``: Input address matched to a general delivery - address - - ``U1``: Input address matched to a unique ZIP code - - ``PB``: Input address matched to PBSA record - - ``RR``: DPV confirmed address with PMB information - - ``R1``: DPV confirmed address without PMB information - - ``R7``: Carrier Route R777 or R779 record - - ``IA``: Informed Address identified - - ``TA``: Primary number matched by dropping a trailing - alpha - dpv_cmra (str): - Indicates if the address is a CMRA (Commercial Mail - Receiving Agency)--a private business receiving mail for - clients. Returns a single character. - - - ``Y``: The address is a CMRA - - ``N``: The address is not a CMRA - dpv_vacant (str): - Is this place vacant? Returns a single character. - - - ``Y``: The address is vacant - - ``N``: The address is not vacant - dpv_no_stat (str): - Is this a no stat address or an active address? No stat - addresses are ones which are not continuously occupied or - addresses that the USPS does not service. Returns a single - character. - - - ``Y``: The address is not active - - ``N``: The address is active - dpv_no_stat_reason_code (int): - Indicates the NoStat type. Returns a reason code as int. - - - ``1``: IDA (Internal Drop Address) – Addresses that do - not receive mail directly from the USPS but are delivered - to a drop address that services them. - - ``2``: CDS - Addresses that have not yet become - deliverable. For example, a new subdivision where lots - and primary numbers have been determined, but no - structure exists yet for occupancy. - - ``3``: Collision - Addresses that do not actually DPV - confirm. - - ``4``: CMZ (College, Military and Other Types) - ZIP + 4 - records USPS has incorporated into the data. - - ``5``: Regular - Indicates addresses not receiving - delivery and the addresses are not counted as possible - deliveries. - - ``6``: Secondary Required - The address requires - secondary information. - dpv_drop (str): - Flag indicates mail is delivered to a single receptable at a - site. Returns a single character. - - - ``Y``: The mail is delivered to a single receptable at a - site. - - ``N``: The mail is not delivered to a single receptable - at a site. - dpv_throwback (str): - Indicates that mail is not delivered to the street address. - Returns a single character. - - - ``Y``: The mail is not delivered to the street address. - - ``N``: The mail is delivered to the street address. - dpv_non_delivery_days (str): - Flag indicates mail delivery is not performed every day of - the week. Returns a single character. - - - ``Y``: The mail delivery is not performed every day of - the week. - - ``N``: No indication the mail delivery is not performed - every day of the week. - dpv_non_delivery_days_values (int): - Integer identifying non-delivery days. It can - be interrogated using bit flags: - - 0x40 – Sunday is a non-delivery day - 0x20 – Monday is a non-delivery day - 0x10 – Tuesday is a non-delivery day - 0x08 – Wednesday is a non-delivery day - 0x04 – Thursday is a non-delivery day - 0x02 – Friday is a non-delivery day - 0x01 – Saturday is a non-delivery day - dpv_no_secure_location (str): - Flag indicates door is accessible, but package will not be - left due to security concerns. Returns a single character. - - - ``Y``: The package will not be left due to security - concerns. - - ``N``: No indication the package will not be left due to - security concerns. - dpv_pbsa (str): - Indicates the address was matched to PBSA record. Returns a - single character. - - - ``Y``: The address was matched to PBSA record. - - ``N``: The address was not matched to PBSA record. - dpv_door_not_accessible (str): - Flag indicates addresses where USPS cannot knock on a door - to deliver mail. Returns a single character. - - - ``Y``: The door is not accessible. - - ``N``: No indication the door is not accessible. - dpv_enhanced_delivery_code (str): - Indicates that more than one DPV return code is valid for - the address. Returns a single character. - - - ``Y``: Address was DPV confirmed for primary and any - secondary numbers. - - ``N``: Primary and any secondary number information - failed to DPV confirm. - - ``S``: Address was DPV confirmed for the primary number - only, and the secondary number information was present by - not confirmed, or a single trailing alpha on a primary - number was dropped to make a DPV match and secondary - information required. - - ``D``: Address was DPV confirmed for the primary number - only, and the secondary number information was missing. - - ``R``: Address confirmed but assigned to phantom route - R777 and R779 and USPS delivery is not provided. - carrier_route (str): - The carrier route code. A four character code consisting of - a one letter prefix and a three digit route designator. - - Prefixes: - - - ``C``: Carrier route (or city route) - - ``R``: Rural route - - ``H``: Highway Contract Route - - ``B``: Post Office Box Section - - ``G``: General delivery unit - carrier_route_indicator (str): - Carrier route rate sort indicator. - ews_no_match (bool): - The delivery address is matchable, but the - EWS file indicates that an exact match will be - available soon. - post_office_city (str): - Main post office city. - post_office_state (str): - Main post office state. - abbreviated_city (str): - Abbreviated city. - fips_county_code (str): - FIPS county code. - county (str): - County name. - elot_number (str): - Enhanced Line of Travel (eLOT) number. - elot_flag (str): - eLOT Ascending/Descending Flag (A/D). - lacs_link_return_code (str): - LACSLink return code. - lacs_link_indicator (str): - LACSLink indicator. - po_box_only_postal_code (bool): - PO Box only postal code. - suitelink_footnote (str): - Footnotes from matching a street or highrise record to suite - information. If business name match is found, the secondary - number is returned. - - - ``A``: SuiteLink record match, business address improved. - - ``00``: No match, business address is not improved. - pmb_designator (str): - PMB (Private Mail Box) unit designator. - pmb_number (str): - PMB (Private Mail Box) number; - address_record_type (str): - Type of the address record that matches the input address. - - - ``F``: FIRM. This is a match to a Firm Record, which is - the finest level of match available for an address. - - ``G``: GENERAL DELIVERY. This is a match to a General - Delivery record. - - ``H``: BUILDING / APARTMENT. This is a match to a - Building or Apartment record. - - ``P``: POST OFFICE BOX. This is a match to a Post Office - Box. - - ``R``: RURAL ROUTE or HIGHWAY CONTRACT: This is a match - to either a Rural Route or a Highway Contract record, - both of which may have associated Box Number ranges. - - ``S``: STREET RECORD: This is a match to a Street record - containing a valid primary number range. - default_address (bool): - Indicator that a default address was found, - but more specific addresses exists. - error_message (str): - Error message for USPS data retrieval. This - is populated when USPS processing is suspended - because of the detection of artificially created - addresses. - - The USPS data fields might not be populated when - this error is present. - cass_processed (bool): - Indicator that the request has been CASS - processed. - """ - - standardized_address: 'UspsAddress' = proto.Field( - proto.MESSAGE, - number=1, - message='UspsAddress', - ) - delivery_point_code: str = proto.Field( - proto.STRING, - number=2, - ) - delivery_point_check_digit: str = proto.Field( - proto.STRING, - number=3, - ) - dpv_confirmation: str = proto.Field( - proto.STRING, - number=4, - ) - dpv_footnote: str = proto.Field( - proto.STRING, - number=5, - ) - dpv_cmra: str = proto.Field( - proto.STRING, - number=6, - ) - dpv_vacant: str = proto.Field( - proto.STRING, - number=7, - ) - dpv_no_stat: str = proto.Field( - proto.STRING, - number=8, - ) - dpv_no_stat_reason_code: int = proto.Field( - proto.INT32, - number=29, - ) - dpv_drop: str = proto.Field( - proto.STRING, - number=30, - ) - dpv_throwback: str = proto.Field( - proto.STRING, - number=31, - ) - dpv_non_delivery_days: str = proto.Field( - proto.STRING, - number=32, - ) - dpv_non_delivery_days_values: int = proto.Field( - proto.INT32, - number=33, - ) - dpv_no_secure_location: str = proto.Field( - proto.STRING, - number=34, - ) - dpv_pbsa: str = proto.Field( - proto.STRING, - number=35, - ) - dpv_door_not_accessible: str = proto.Field( - proto.STRING, - number=36, - ) - dpv_enhanced_delivery_code: str = proto.Field( - proto.STRING, - number=37, - ) - carrier_route: str = proto.Field( - proto.STRING, - number=9, - ) - carrier_route_indicator: str = proto.Field( - proto.STRING, - number=10, - ) - ews_no_match: bool = proto.Field( - proto.BOOL, - number=11, - ) - post_office_city: str = proto.Field( - proto.STRING, - number=12, - ) - post_office_state: str = proto.Field( - proto.STRING, - number=13, - ) - abbreviated_city: str = proto.Field( - proto.STRING, - number=14, - ) - fips_county_code: str = proto.Field( - proto.STRING, - number=15, - ) - county: str = proto.Field( - proto.STRING, - number=16, - ) - elot_number: str = proto.Field( - proto.STRING, - number=17, - ) - elot_flag: str = proto.Field( - proto.STRING, - number=18, - ) - lacs_link_return_code: str = proto.Field( - proto.STRING, - number=19, - ) - lacs_link_indicator: str = proto.Field( - proto.STRING, - number=20, - ) - po_box_only_postal_code: bool = proto.Field( - proto.BOOL, - number=21, - ) - suitelink_footnote: str = proto.Field( - proto.STRING, - number=22, - ) - pmb_designator: str = proto.Field( - proto.STRING, - number=23, - ) - pmb_number: str = proto.Field( - proto.STRING, - number=24, - ) - address_record_type: str = proto.Field( - proto.STRING, - number=25, - ) - default_address: bool = proto.Field( - proto.BOOL, - number=26, - ) - error_message: str = proto.Field( - proto.STRING, - number=27, - ) - cass_processed: bool = proto.Field( - proto.BOOL, - number=28, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/mypy.ini b/owl-bot-staging/google-maps-addressvalidation/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/noxfile.py b/owl-bot-staging/google-maps-addressvalidation/v1/noxfile.py deleted file mode 100644 index 40d06dd046c5..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation' - -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/addressvalidation_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/addressvalidation_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-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py deleted file mode 100644 index 5694fbaa5b87..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_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 ProvideValidationFeedback -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-addressvalidation - - -# [START addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 addressvalidation_v1 - - -async def sample_provide_validation_feedback(): - # Create a client - client = addressvalidation_v1.AddressValidationAsyncClient() - - # Initialize request argument(s) - request = addressvalidation_v1.ProvideValidationFeedbackRequest( - conclusion="UNUSED", - response_id="response_id_value", - ) - - # Make the request - response = await client.provide_validation_feedback(request=request) - - # Handle the response - print(response) - -# [END addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_async] diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py deleted file mode 100644 index a1611f9bfaba..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_provide_validation_feedback_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 ProvideValidationFeedback -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-addressvalidation - - -# [START addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 addressvalidation_v1 - - -def sample_provide_validation_feedback(): - # Create a client - client = addressvalidation_v1.AddressValidationClient() - - # Initialize request argument(s) - request = addressvalidation_v1.ProvideValidationFeedbackRequest( - conclusion="UNUSED", - response_id="response_id_value", - ) - - # Make the request - response = client.provide_validation_feedback(request=request) - - # Handle the response - print(response) - -# [END addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_sync] diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_async.py b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_async.py deleted file mode 100644 index 19457cbd1d8e..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_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 ValidateAddress -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-addressvalidation - - -# [START addressvalidation_v1_generated_AddressValidation_ValidateAddress_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 addressvalidation_v1 - - -async def sample_validate_address(): - # Create a client - client = addressvalidation_v1.AddressValidationAsyncClient() - - # Initialize request argument(s) - request = addressvalidation_v1.ValidateAddressRequest( - ) - - # Make the request - response = await client.validate_address(request=request) - - # Handle the response - print(response) - -# [END addressvalidation_v1_generated_AddressValidation_ValidateAddress_async] diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_sync.py b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_sync.py deleted file mode 100644 index 361e727d5bff..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/addressvalidation_v1_generated_address_validation_validate_address_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 ValidateAddress -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-addressvalidation - - -# [START addressvalidation_v1_generated_AddressValidation_ValidateAddress_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 addressvalidation_v1 - - -def sample_validate_address(): - # Create a client - client = addressvalidation_v1.AddressValidationClient() - - # Initialize request argument(s) - request = addressvalidation_v1.ValidateAddressRequest( - ) - - # Make the request - response = client.validate_address(request=request) - - # Handle the response - print(response) - -# [END addressvalidation_v1_generated_AddressValidation_ValidateAddress_sync] diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json b/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json deleted file mode 100644 index b8aeda3afd23..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.addressvalidation.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-addressvalidation", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.addressvalidation_v1.AddressValidationAsyncClient", - "shortName": "AddressValidationAsyncClient" - }, - "fullName": "google.maps.addressvalidation_v1.AddressValidationAsyncClient.provide_validation_feedback", - "method": { - "fullName": "google.maps.addressvalidation.v1.AddressValidation.ProvideValidationFeedback", - "service": { - "fullName": "google.maps.addressvalidation.v1.AddressValidation", - "shortName": "AddressValidation" - }, - "shortName": "ProvideValidationFeedback" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.addressvalidation_v1.types.ProvideValidationFeedbackResponse", - "shortName": "provide_validation_feedback" - }, - "description": "Sample for ProvideValidationFeedback", - "file": "addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_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": "addressvalidation_v1_generated_address_validation_provide_validation_feedback_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.addressvalidation_v1.AddressValidationClient", - "shortName": "AddressValidationClient" - }, - "fullName": "google.maps.addressvalidation_v1.AddressValidationClient.provide_validation_feedback", - "method": { - "fullName": "google.maps.addressvalidation.v1.AddressValidation.ProvideValidationFeedback", - "service": { - "fullName": "google.maps.addressvalidation.v1.AddressValidation", - "shortName": "AddressValidation" - }, - "shortName": "ProvideValidationFeedback" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.addressvalidation_v1.types.ProvideValidationFeedbackRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.addressvalidation_v1.types.ProvideValidationFeedbackResponse", - "shortName": "provide_validation_feedback" - }, - "description": "Sample for ProvideValidationFeedback", - "file": "addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "addressvalidation_v1_generated_AddressValidation_ProvideValidationFeedback_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": "addressvalidation_v1_generated_address_validation_provide_validation_feedback_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.addressvalidation_v1.AddressValidationAsyncClient", - "shortName": "AddressValidationAsyncClient" - }, - "fullName": "google.maps.addressvalidation_v1.AddressValidationAsyncClient.validate_address", - "method": { - "fullName": "google.maps.addressvalidation.v1.AddressValidation.ValidateAddress", - "service": { - "fullName": "google.maps.addressvalidation.v1.AddressValidation", - "shortName": "AddressValidation" - }, - "shortName": "ValidateAddress" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.addressvalidation_v1.types.ValidateAddressRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.addressvalidation_v1.types.ValidateAddressResponse", - "shortName": "validate_address" - }, - "description": "Sample for ValidateAddress", - "file": "addressvalidation_v1_generated_address_validation_validate_address_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "addressvalidation_v1_generated_AddressValidation_ValidateAddress_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": "addressvalidation_v1_generated_address_validation_validate_address_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.addressvalidation_v1.AddressValidationClient", - "shortName": "AddressValidationClient" - }, - "fullName": "google.maps.addressvalidation_v1.AddressValidationClient.validate_address", - "method": { - "fullName": "google.maps.addressvalidation.v1.AddressValidation.ValidateAddress", - "service": { - "fullName": "google.maps.addressvalidation.v1.AddressValidation", - "shortName": "AddressValidation" - }, - "shortName": "ValidateAddress" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.addressvalidation_v1.types.ValidateAddressRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.addressvalidation_v1.types.ValidateAddressResponse", - "shortName": "validate_address" - }, - "description": "Sample for ValidateAddress", - "file": "addressvalidation_v1_generated_address_validation_validate_address_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "addressvalidation_v1_generated_AddressValidation_ValidateAddress_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": "addressvalidation_v1_generated_address_validation_validate_address_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/scripts/fixup_addressvalidation_v1_keywords.py b/owl-bot-staging/google-maps-addressvalidation/v1/scripts/fixup_addressvalidation_v1_keywords.py deleted file mode 100644 index 4dfe232a0943..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/scripts/fixup_addressvalidation_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 addressvalidationCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'provide_validation_feedback': ('conclusion', 'response_id', ), - 'validate_address': ('address', 'previous_response_id', 'enable_usps_cass', 'session_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=addressvalidationCallTransformer(), -): - """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 addressvalidation 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-addressvalidation/v1/setup.py b/owl-bot-staging/google-maps-addressvalidation/v1/setup.py deleted file mode 100644 index c24c77e55e90..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation' - - -description = "Google Maps Addressvalidation API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/addressvalidation/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-addressvalidation" - -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-addressvalidation/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.7.txt deleted file mode 100644 index 277853c664a0..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/tests/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/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-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/__init__.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_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-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/test_address_validation.py b/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/test_address_validation.py deleted file mode 100644 index 54ae9e6c5b4d..000000000000 --- a/owl-bot-staging/google-maps-addressvalidation/v1/tests/unit/gapic/addressvalidation_v1/test_address_validation.py +++ /dev/null @@ -1,2364 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.addressvalidation_v1.services.address_validation import AddressValidationAsyncClient -from google.maps.addressvalidation_v1.services.address_validation import AddressValidationClient -from google.maps.addressvalidation_v1.services.address_validation import transports -from google.maps.addressvalidation_v1.types import address_validation_service -from google.oauth2 import service_account -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 AddressValidationClient._get_default_mtls_endpoint(None) is None - assert AddressValidationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AddressValidationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AddressValidationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AddressValidationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AddressValidationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AddressValidationClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AddressValidationClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AddressValidationClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AddressValidationClient._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 AddressValidationClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AddressValidationClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AddressValidationClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AddressValidationClient._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 AddressValidationClient._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 AddressValidationClient._get_client_cert_source(None, False) is None - assert AddressValidationClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AddressValidationClient._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 AddressValidationClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AddressValidationClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AddressValidationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationClient)) -@mock.patch.object(AddressValidationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AddressValidationClient._DEFAULT_UNIVERSE - default_endpoint = AddressValidationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AddressValidationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AddressValidationClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AddressValidationClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AddressValidationClient.DEFAULT_MTLS_ENDPOINT - assert AddressValidationClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AddressValidationClient._get_api_endpoint(None, None, default_universe, "always") == AddressValidationClient.DEFAULT_MTLS_ENDPOINT - assert AddressValidationClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AddressValidationClient.DEFAULT_MTLS_ENDPOINT - assert AddressValidationClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AddressValidationClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AddressValidationClient._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 AddressValidationClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AddressValidationClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AddressValidationClient._get_universe_domain(None, None) == AddressValidationClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AddressValidationClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc"), - (AddressValidationClient, transports.AddressValidationRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AddressValidationClient, "grpc"), - (AddressValidationAsyncClient, "grpc_asyncio"), - (AddressValidationClient, "rest"), -]) -def test_address_validation_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 == ( - 'addressvalidation.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://addressvalidation.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AddressValidationGrpcTransport, "grpc"), - (transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AddressValidationRestTransport, "rest"), -]) -def test_address_validation_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", [ - (AddressValidationClient, "grpc"), - (AddressValidationAsyncClient, "grpc_asyncio"), - (AddressValidationClient, "rest"), -]) -def test_address_validation_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 == ( - 'addressvalidation.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://addressvalidation.googleapis.com' - ) - - -def test_address_validation_client_get_transport_class(): - transport = AddressValidationClient.get_transport_class() - available_transports = [ - transports.AddressValidationGrpcTransport, - transports.AddressValidationRestTransport, - ] - assert transport in available_transports - - transport = AddressValidationClient.get_transport_class("grpc") - assert transport == transports.AddressValidationGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc"), - (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio"), - (AddressValidationClient, transports.AddressValidationRestTransport, "rest"), -]) -@mock.patch.object(AddressValidationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationClient)) -@mock.patch.object(AddressValidationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationAsyncClient)) -def test_address_validation_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(AddressValidationClient, '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(AddressValidationClient, '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", [ - (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc", "true"), - (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc", "false"), - (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AddressValidationClient, transports.AddressValidationRestTransport, "rest", "true"), - (AddressValidationClient, transports.AddressValidationRestTransport, "rest", "false"), -]) -@mock.patch.object(AddressValidationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationClient)) -@mock.patch.object(AddressValidationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_address_validation_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", [ - AddressValidationClient, AddressValidationAsyncClient -]) -@mock.patch.object(AddressValidationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AddressValidationClient)) -@mock.patch.object(AddressValidationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AddressValidationAsyncClient)) -def test_address_validation_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", [ - AddressValidationClient, AddressValidationAsyncClient -]) -@mock.patch.object(AddressValidationClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationClient)) -@mock.patch.object(AddressValidationAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressValidationAsyncClient)) -def test_address_validation_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AddressValidationClient._DEFAULT_UNIVERSE - default_endpoint = AddressValidationClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AddressValidationClient._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", [ - (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc"), - (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio"), - (AddressValidationClient, transports.AddressValidationRestTransport, "rest"), -]) -def test_address_validation_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", [ - (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc", grpc_helpers), - (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AddressValidationClient, transports.AddressValidationRestTransport, "rest", None), -]) -def test_address_validation_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_address_validation_client_client_options_from_dict(): - with mock.patch('google.maps.addressvalidation_v1.services.address_validation.transports.AddressValidationGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AddressValidationClient( - 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", [ - (AddressValidationClient, transports.AddressValidationGrpcTransport, "grpc", grpc_helpers), - (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_address_validation_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( - "addressvalidation.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="addressvalidation.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - address_validation_service.ValidateAddressRequest, - dict, -]) -def test_validate_address(request_type, transport: str = 'grpc'): - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_address), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = address_validation_service.ValidateAddressResponse( - response_id='response_id_value', - ) - response = client.validate_address(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = address_validation_service.ValidateAddressRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, address_validation_service.ValidateAddressResponse) - assert response.response_id == 'response_id_value' - - -def test_validate_address_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = address_validation_service.ValidateAddressRequest( - previous_response_id='previous_response_id_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.validate_address), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.validate_address(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == address_validation_service.ValidateAddressRequest( - previous_response_id='previous_response_id_value', - session_token='session_token_value', - ) - -def test_validate_address_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.validate_address in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.validate_address] = mock_rpc - request = {} - client.validate_address(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_address(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_validate_address_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AddressValidationAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.validate_address in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.validate_address] = mock_rpc - - request = {} - await client.validate_address(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.validate_address(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_validate_address_async(transport: str = 'grpc_asyncio', request_type=address_validation_service.ValidateAddressRequest): - client = AddressValidationAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_address), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_validation_service.ValidateAddressResponse( - response_id='response_id_value', - )) - response = await client.validate_address(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = address_validation_service.ValidateAddressRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, address_validation_service.ValidateAddressResponse) - assert response.response_id == 'response_id_value' - - -@pytest.mark.asyncio -async def test_validate_address_async_from_dict(): - await test_validate_address_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - address_validation_service.ProvideValidationFeedbackRequest, - dict, -]) -def test_provide_validation_feedback(request_type, transport: str = 'grpc'): - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.provide_validation_feedback), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = address_validation_service.ProvideValidationFeedbackResponse( - ) - response = client.provide_validation_feedback(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = address_validation_service.ProvideValidationFeedbackRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, address_validation_service.ProvideValidationFeedbackResponse) - - -def test_provide_validation_feedback_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = address_validation_service.ProvideValidationFeedbackRequest( - response_id='response_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.provide_validation_feedback), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.provide_validation_feedback(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == address_validation_service.ProvideValidationFeedbackRequest( - response_id='response_id_value', - ) - -def test_provide_validation_feedback_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.provide_validation_feedback in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.provide_validation_feedback] = mock_rpc - request = {} - client.provide_validation_feedback(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.provide_validation_feedback(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_provide_validation_feedback_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AddressValidationAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.provide_validation_feedback in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.provide_validation_feedback] = mock_rpc - - request = {} - await client.provide_validation_feedback(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.provide_validation_feedback(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_provide_validation_feedback_async(transport: str = 'grpc_asyncio', request_type=address_validation_service.ProvideValidationFeedbackRequest): - client = AddressValidationAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.provide_validation_feedback), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_validation_service.ProvideValidationFeedbackResponse( - )) - response = await client.provide_validation_feedback(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = address_validation_service.ProvideValidationFeedbackRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, address_validation_service.ProvideValidationFeedbackResponse) - - -@pytest.mark.asyncio -async def test_provide_validation_feedback_async_from_dict(): - await test_provide_validation_feedback_async(request_type=dict) - - -def test_validate_address_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.validate_address in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.validate_address] = mock_rpc - - request = {} - client.validate_address(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_address(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_validate_address_rest_required_fields(request_type=address_validation_service.ValidateAddressRequest): - transport_class = transports.AddressValidationRestTransport - - 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()).validate_address._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()).validate_address._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = address_validation_service.ValidateAddressResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = address_validation_service.ValidateAddressResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.validate_address(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_validate_address_rest_unset_required_fields(): - transport = transports.AddressValidationRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.validate_address._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("address", ))) - - -def test_provide_validation_feedback_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.provide_validation_feedback in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.provide_validation_feedback] = mock_rpc - - request = {} - client.provide_validation_feedback(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.provide_validation_feedback(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_provide_validation_feedback_rest_required_fields(request_type=address_validation_service.ProvideValidationFeedbackRequest): - transport_class = transports.AddressValidationRestTransport - - request_init = {} - request_init["response_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).provide_validation_feedback._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["responseId"] = 'response_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).provide_validation_feedback._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "responseId" in jsonified_request - assert jsonified_request["responseId"] == 'response_id_value' - - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = address_validation_service.ProvideValidationFeedbackResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = address_validation_service.ProvideValidationFeedbackResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.provide_validation_feedback(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_provide_validation_feedback_rest_unset_required_fields(): - transport = transports.AddressValidationRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.provide_validation_feedback._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("conclusion", "responseId", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AddressValidationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AddressValidationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AddressValidationClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AddressValidationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AddressValidationClient( - 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 = AddressValidationClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AddressValidationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AddressValidationClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AddressValidationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AddressValidationClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AddressValidationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AddressValidationGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AddressValidationGrpcTransport, - transports.AddressValidationGrpcAsyncIOTransport, - transports.AddressValidationRestTransport, -]) -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 = AddressValidationClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AddressValidationClient( - 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_validate_address_empty_call_grpc(): - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.validate_address), - '__call__') as call: - call.return_value = address_validation_service.ValidateAddressResponse() - client.validate_address(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = address_validation_service.ValidateAddressRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_provide_validation_feedback_empty_call_grpc(): - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.provide_validation_feedback), - '__call__') as call: - call.return_value = address_validation_service.ProvideValidationFeedbackResponse() - client.provide_validation_feedback(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = address_validation_service.ProvideValidationFeedbackRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AddressValidationAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AddressValidationAsyncClient( - 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_validate_address_empty_call_grpc_asyncio(): - client = AddressValidationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.validate_address), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_validation_service.ValidateAddressResponse( - response_id='response_id_value', - )) - await client.validate_address(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = address_validation_service.ValidateAddressRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_provide_validation_feedback_empty_call_grpc_asyncio(): - client = AddressValidationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.provide_validation_feedback), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_validation_service.ProvideValidationFeedbackResponse( - )) - await client.provide_validation_feedback(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = address_validation_service.ProvideValidationFeedbackRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AddressValidationClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_validate_address_rest_bad_request(request_type=address_validation_service.ValidateAddressRequest): - client = AddressValidationClient( - 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 - client.validate_address(request) - - -@pytest.mark.parametrize("request_type", [ - address_validation_service.ValidateAddressRequest, - dict, -]) -def test_validate_address_rest_call_success(request_type): - client = AddressValidationClient( - 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 = address_validation_service.ValidateAddressResponse( - response_id='response_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = address_validation_service.ValidateAddressResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.validate_address(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, address_validation_service.ValidateAddressResponse) - assert response.response_id == 'response_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_validate_address_rest_interceptors(null_interceptor): - transport = transports.AddressValidationRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressValidationRestInterceptor(), - ) - client = AddressValidationClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AddressValidationRestInterceptor, "post_validate_address") as post, \ - mock.patch.object(transports.AddressValidationRestInterceptor, "pre_validate_address") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = address_validation_service.ValidateAddressRequest.pb(address_validation_service.ValidateAddressRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = address_validation_service.ValidateAddressResponse.to_json(address_validation_service.ValidateAddressResponse()) - req.return_value.content = return_value - - request = address_validation_service.ValidateAddressRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = address_validation_service.ValidateAddressResponse() - - client.validate_address(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_provide_validation_feedback_rest_bad_request(request_type=address_validation_service.ProvideValidationFeedbackRequest): - client = AddressValidationClient( - 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 - client.provide_validation_feedback(request) - - -@pytest.mark.parametrize("request_type", [ - address_validation_service.ProvideValidationFeedbackRequest, - dict, -]) -def test_provide_validation_feedback_rest_call_success(request_type): - client = AddressValidationClient( - 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 = address_validation_service.ProvideValidationFeedbackResponse( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = address_validation_service.ProvideValidationFeedbackResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.provide_validation_feedback(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, address_validation_service.ProvideValidationFeedbackResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_provide_validation_feedback_rest_interceptors(null_interceptor): - transport = transports.AddressValidationRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressValidationRestInterceptor(), - ) - client = AddressValidationClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AddressValidationRestInterceptor, "post_provide_validation_feedback") as post, \ - mock.patch.object(transports.AddressValidationRestInterceptor, "pre_provide_validation_feedback") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = address_validation_service.ProvideValidationFeedbackRequest.pb(address_validation_service.ProvideValidationFeedbackRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = address_validation_service.ProvideValidationFeedbackResponse.to_json(address_validation_service.ProvideValidationFeedbackResponse()) - req.return_value.content = return_value - - request = address_validation_service.ProvideValidationFeedbackRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = address_validation_service.ProvideValidationFeedbackResponse() - - client.provide_validation_feedback(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = AddressValidationClient( - 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_validate_address_empty_call_rest(): - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.validate_address), - '__call__') as call: - client.validate_address(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = address_validation_service.ValidateAddressRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_provide_validation_feedback_empty_call_rest(): - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.provide_validation_feedback), - '__call__') as call: - client.provide_validation_feedback(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = address_validation_service.ProvideValidationFeedbackRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AddressValidationGrpcTransport, - ) - -def test_address_validation_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AddressValidationTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_address_validation_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.addressvalidation_v1.services.address_validation.transports.AddressValidationTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AddressValidationTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'validate_address', - 'provide_validation_feedback', - ) - 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_address_validation_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.addressvalidation_v1.services.address_validation.transports.AddressValidationTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AddressValidationTransport( - 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_address_validation_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.addressvalidation_v1.services.address_validation.transports.AddressValidationTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AddressValidationTransport() - adc.assert_called_once() - - -def test_address_validation_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) - AddressValidationClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AddressValidationGrpcTransport, - transports.AddressValidationGrpcAsyncIOTransport, - ], -) -def test_address_validation_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.AddressValidationGrpcTransport, - transports.AddressValidationGrpcAsyncIOTransport, - transports.AddressValidationRestTransport, - ], -) -def test_address_validation_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.AddressValidationGrpcTransport, grpc_helpers), - (transports.AddressValidationGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_address_validation_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( - "addressvalidation.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="addressvalidation.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AddressValidationGrpcTransport, transports.AddressValidationGrpcAsyncIOTransport]) -def test_address_validation_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_address_validation_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.AddressValidationRestTransport ( - 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_address_validation_host_no_port(transport_name): - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='addressvalidation.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'addressvalidation.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://addressvalidation.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_address_validation_host_with_port(transport_name): - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='addressvalidation.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'addressvalidation.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://addressvalidation.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_address_validation_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AddressValidationClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AddressValidationClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.validate_address._session - session2 = client2.transport.validate_address._session - assert session1 != session2 - session1 = client1.transport.provide_validation_feedback._session - session2 = client2.transport.provide_validation_feedback._session - assert session1 != session2 -def test_address_validation_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AddressValidationGrpcTransport( - 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_address_validation_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AddressValidationGrpcAsyncIOTransport( - 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.AddressValidationGrpcTransport, transports.AddressValidationGrpcAsyncIOTransport]) -def test_address_validation_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.AddressValidationGrpcTransport, transports.AddressValidationGrpcAsyncIOTransport]) -def test_address_validation_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 = AddressValidationClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = AddressValidationClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AddressValidationClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = AddressValidationClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = AddressValidationClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AddressValidationClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AddressValidationClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = AddressValidationClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AddressValidationClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = AddressValidationClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = AddressValidationClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AddressValidationClient.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 = AddressValidationClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AddressValidationClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AddressValidationClient.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.AddressValidationTransport, '_prep_wrapped_messages') as prep: - client = AddressValidationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AddressValidationTransport, '_prep_wrapped_messages') as prep: - transport_class = AddressValidationClient.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 = AddressValidationClient( - 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 = AddressValidationAsyncClient( - 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 = AddressValidationClient( - 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 = AddressValidationClient( - 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", [ - (AddressValidationClient, transports.AddressValidationGrpcTransport), - (AddressValidationAsyncClient, transports.AddressValidationGrpcAsyncIOTransport), -]) -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-areainsights/v1/.coveragerc b/owl-bot-staging/google-maps-areainsights/v1/.coveragerc deleted file mode 100644 index 612fd0382a68..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/areainsights/__init__.py - google/maps/areainsights/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-areainsights/v1/.flake8 b/owl-bot-staging/google-maps-areainsights/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/MANIFEST.in b/owl-bot-staging/google-maps-areainsights/v1/MANIFEST.in deleted file mode 100644 index 6f1322254e3a..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/areainsights *.py -recursive-include google/maps/areainsights_v1 *.py diff --git a/owl-bot-staging/google-maps-areainsights/v1/README.rst b/owl-bot-staging/google-maps-areainsights/v1/README.rst deleted file mode 100644 index 85225fe6e116..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Areainsights 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 Areainsights 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-areainsights/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-areainsights/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/docs/areainsights_v1/area_insights.rst b/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/area_insights.rst deleted file mode 100644 index 78835e4cf335..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/area_insights.rst +++ /dev/null @@ -1,6 +0,0 @@ -AreaInsights ------------------------------- - -.. automodule:: google.maps.areainsights_v1.services.area_insights - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/services_.rst b/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/services_.rst deleted file mode 100644 index 54fbea792518..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Areainsights v1 API -============================================ -.. toctree:: - :maxdepth: 2 - - area_insights diff --git a/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/types_.rst b/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/types_.rst deleted file mode 100644 index 4774a4b375c1..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/docs/areainsights_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Areainsights v1 API -========================================= - -.. automodule:: google.maps.areainsights_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-areainsights/v1/docs/conf.py b/owl-bot-staging/google-maps-areainsights/v1/docs/conf.py deleted file mode 100644 index c2b8f89658a8..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights 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-areainsights" -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-areainsights-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-areainsights.tex", - u"google-maps-areainsights 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-areainsights", - u"Google Maps Areainsights 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-areainsights", - u"google-maps-areainsights Documentation", - author, - "google-maps-areainsights", - "GAPIC library for Google Maps Areainsights 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-areainsights/v1/docs/index.rst b/owl-bot-staging/google-maps-areainsights/v1/docs/index.rst deleted file mode 100644 index 2371f3c41e8a..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - areainsights_v1/services_ - areainsights_v1/types_ diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/__init__.py deleted file mode 100644 index 155569990ce6..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/__init__.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 google.maps.areainsights import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.areainsights_v1.services.area_insights.client import AreaInsightsClient -from google.maps.areainsights_v1.services.area_insights.async_client import AreaInsightsAsyncClient - -from google.maps.areainsights_v1.types.area_insights_service import ComputeInsightsRequest -from google.maps.areainsights_v1.types.area_insights_service import ComputeInsightsResponse -from google.maps.areainsights_v1.types.area_insights_service import Filter -from google.maps.areainsights_v1.types.area_insights_service import LocationFilter -from google.maps.areainsights_v1.types.area_insights_service import PlaceInsight -from google.maps.areainsights_v1.types.area_insights_service import RatingFilter -from google.maps.areainsights_v1.types.area_insights_service import TypeFilter -from google.maps.areainsights_v1.types.area_insights_service import Insight -from google.maps.areainsights_v1.types.area_insights_service import OperatingStatus -from google.maps.areainsights_v1.types.area_insights_service import PriceLevel - -__all__ = ('AreaInsightsClient', - 'AreaInsightsAsyncClient', - 'ComputeInsightsRequest', - 'ComputeInsightsResponse', - 'Filter', - 'LocationFilter', - 'PlaceInsight', - 'RatingFilter', - 'TypeFilter', - 'Insight', - 'OperatingStatus', - 'PriceLevel', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/gapic_version.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/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-areainsights/v1/google/maps/areainsights/py.typed b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/py.typed deleted file mode 100644 index b098dc9b9f40..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-areainsights package uses inline types. diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/__init__.py deleted file mode 100644 index 0b2859bdd2ca..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/__init__.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.areainsights_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.area_insights import AreaInsightsClient -from .services.area_insights import AreaInsightsAsyncClient - -from .types.area_insights_service import ComputeInsightsRequest -from .types.area_insights_service import ComputeInsightsResponse -from .types.area_insights_service import Filter -from .types.area_insights_service import LocationFilter -from .types.area_insights_service import PlaceInsight -from .types.area_insights_service import RatingFilter -from .types.area_insights_service import TypeFilter -from .types.area_insights_service import Insight -from .types.area_insights_service import OperatingStatus -from .types.area_insights_service import PriceLevel - -__all__ = ( - 'AreaInsightsAsyncClient', -'AreaInsightsClient', -'ComputeInsightsRequest', -'ComputeInsightsResponse', -'Filter', -'Insight', -'LocationFilter', -'OperatingStatus', -'PlaceInsight', -'PriceLevel', -'RatingFilter', -'TypeFilter', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_metadata.json b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_metadata.json deleted file mode 100644 index 413146689761..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/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.maps.areainsights_v1", - "protoPackage": "google.maps.areainsights.v1", - "schema": "1.0", - "services": { - "AreaInsights": { - "clients": { - "grpc": { - "libraryClient": "AreaInsightsClient", - "rpcs": { - "ComputeInsights": { - "methods": [ - "compute_insights" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AreaInsightsAsyncClient", - "rpcs": { - "ComputeInsights": { - "methods": [ - "compute_insights" - ] - } - } - }, - "rest": { - "libraryClient": "AreaInsightsClient", - "rpcs": { - "ComputeInsights": { - "methods": [ - "compute_insights" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_version.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_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-areainsights/v1/google/maps/areainsights_v1/py.typed b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/py.typed deleted file mode 100644 index b098dc9b9f40..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-areainsights package uses inline types. diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_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-areainsights/v1/google/maps/areainsights_v1/services/area_insights/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/__init__.py deleted file mode 100644 index 39f60ebeeb2e..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/__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 AreaInsightsClient -from .async_client import AreaInsightsAsyncClient - -__all__ = ( - 'AreaInsightsClient', - 'AreaInsightsAsyncClient', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/async_client.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/async_client.py deleted file mode 100644 index 9722e6501448..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/async_client.py +++ /dev/null @@ -1,321 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.maps.areainsights_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.areainsights_v1.types import area_insights_service -from .transports.base import AreaInsightsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AreaInsightsGrpcAsyncIOTransport -from .client import AreaInsightsClient - - -class AreaInsightsAsyncClient: - """Service definition for the Places Insights API.""" - - _client: AreaInsightsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AreaInsightsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AreaInsightsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AreaInsightsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AreaInsightsClient._DEFAULT_UNIVERSE - - place_path = staticmethod(AreaInsightsClient.place_path) - parse_place_path = staticmethod(AreaInsightsClient.parse_place_path) - common_billing_account_path = staticmethod(AreaInsightsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AreaInsightsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AreaInsightsClient.common_folder_path) - parse_common_folder_path = staticmethod(AreaInsightsClient.parse_common_folder_path) - common_organization_path = staticmethod(AreaInsightsClient.common_organization_path) - parse_common_organization_path = staticmethod(AreaInsightsClient.parse_common_organization_path) - common_project_path = staticmethod(AreaInsightsClient.common_project_path) - parse_common_project_path = staticmethod(AreaInsightsClient.parse_common_project_path) - common_location_path = staticmethod(AreaInsightsClient.common_location_path) - parse_common_location_path = staticmethod(AreaInsightsClient.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: - AreaInsightsAsyncClient: The constructed client. - """ - return AreaInsightsClient.from_service_account_info.__func__(AreaInsightsAsyncClient, 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: - AreaInsightsAsyncClient: The constructed client. - """ - return AreaInsightsClient.from_service_account_file.__func__(AreaInsightsAsyncClient, 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 AreaInsightsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AreaInsightsTransport: - """Returns the transport used by the client instance. - - Returns: - AreaInsightsTransport: 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 = AreaInsightsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AreaInsightsTransport, Callable[..., AreaInsightsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the area insights 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,AreaInsightsTransport,Callable[..., AreaInsightsTransport]]]): - 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 AreaInsightsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = AreaInsightsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def compute_insights(self, - request: Optional[Union[area_insights_service.ComputeInsightsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> area_insights_service.ComputeInsightsResponse: - r"""Compute Insights RPC - - This method lets you retrieve insights about areas using a - variaty of filter such as: area, place type, operating status, - price level and ratings. Currently "count" and "places" insights - are supported. With "count" insights you can answer questions - such as "How many restaurant are located in California that are - operational, are inexpensive and have an average rating of at - least 4 stars" (see ``insight`` enum for more details). With - "places" insights, you can determine which places match the - requested filter. Clients can then use those place resource - names to fetch more details about each individual place using - the Places API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 areainsights_v1 - - async def sample_compute_insights(): - # Create a client - client = areainsights_v1.AreaInsightsAsyncClient() - - # Initialize request argument(s) - request = areainsights_v1.ComputeInsightsRequest( - insights=['INSIGHT_PLACES'], - ) - - # Make the request - response = await client.compute_insights(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.areainsights_v1.types.ComputeInsightsRequest, dict]]): - The request object. Request for the ComputeInsights RPC. - retry (google.api_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. - - Returns: - google.maps.areainsights_v1.types.ComputeInsightsResponse: - Response for the ComputeInsights RPC. - """ - # 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, area_insights_service.ComputeInsightsRequest): - request = area_insights_service.ComputeInsightsRequest(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_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 __aenter__(self) -> "AreaInsightsAsyncClient": - 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__ = ( - "AreaInsightsAsyncClient", -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/client.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/client.py deleted file mode 100644 index dd9e11628f77..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/client.py +++ /dev/null @@ -1,678 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.maps.areainsights_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 - -from google.maps.areainsights_v1.types import area_insights_service -from .transports.base import AreaInsightsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AreaInsightsGrpcTransport -from .transports.grpc_asyncio import AreaInsightsGrpcAsyncIOTransport -from .transports.rest import AreaInsightsRestTransport - - -class AreaInsightsClientMeta(type): - """Metaclass for the AreaInsights 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[AreaInsightsTransport]] - _transport_registry["grpc"] = AreaInsightsGrpcTransport - _transport_registry["grpc_asyncio"] = AreaInsightsGrpcAsyncIOTransport - _transport_registry["rest"] = AreaInsightsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AreaInsightsTransport]: - """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 AreaInsightsClient(metaclass=AreaInsightsClientMeta): - """Service definition for the Places Insights 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 = "areainsights.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "areainsights.{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: - AreaInsightsClient: 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: - AreaInsightsClient: 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) -> AreaInsightsTransport: - """Returns the transport used by the client instance. - - Returns: - AreaInsightsTransport: The transport used by the client - instance. - """ - return self._transport - - @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 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 = AreaInsightsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AreaInsightsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AreaInsightsClient._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 = AreaInsightsClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AreaInsightsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - AreaInsightsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, AreaInsightsTransport, Callable[..., AreaInsightsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the area insights client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AreaInsightsTransport,Callable[..., AreaInsightsTransport]]]): - 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 AreaInsightsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = AreaInsightsClient._read_environment_variables() - self._client_cert_source = AreaInsightsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AreaInsightsClient._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 - - 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, AreaInsightsTransport) - if transport_provided: - # transport is a AreaInsightsTransport 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(AreaInsightsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AreaInsightsClient._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[AreaInsightsTransport], Callable[..., AreaInsightsTransport]] = ( - AreaInsightsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AreaInsightsTransport], 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, - ) - - def compute_insights(self, - request: Optional[Union[area_insights_service.ComputeInsightsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> area_insights_service.ComputeInsightsResponse: - r"""Compute Insights RPC - - This method lets you retrieve insights about areas using a - variaty of filter such as: area, place type, operating status, - price level and ratings. Currently "count" and "places" insights - are supported. With "count" insights you can answer questions - such as "How many restaurant are located in California that are - operational, are inexpensive and have an average rating of at - least 4 stars" (see ``insight`` enum for more details). With - "places" insights, you can determine which places match the - requested filter. Clients can then use those place resource - names to fetch more details about each individual place using - the Places API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 areainsights_v1 - - def sample_compute_insights(): - # Create a client - client = areainsights_v1.AreaInsightsClient() - - # Initialize request argument(s) - request = areainsights_v1.ComputeInsightsRequest( - insights=['INSIGHT_PLACES'], - ) - - # Make the request - response = client.compute_insights(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.areainsights_v1.types.ComputeInsightsRequest, dict]): - The request object. Request for the ComputeInsights RPC. - retry (google.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. - - Returns: - google.maps.areainsights_v1.types.ComputeInsightsResponse: - Response for the ComputeInsights RPC. - """ - # 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, area_insights_service.ComputeInsightsRequest): - request = area_insights_service.ComputeInsightsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_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 __enter__(self) -> "AreaInsightsClient": - 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__ = ( - "AreaInsightsClient", -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/README.rst b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/README.rst deleted file mode 100644 index bb3b3fd75775..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AreaInsightsTransport` is the ABC for all transports. -- public child `AreaInsightsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AreaInsightsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAreaInsightsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AreaInsightsRestTransport` 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-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/__init__.py deleted file mode 100644 index 2155301953d7..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/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 AreaInsightsTransport -from .grpc import AreaInsightsGrpcTransport -from .grpc_asyncio import AreaInsightsGrpcAsyncIOTransport -from .rest import AreaInsightsRestTransport -from .rest import AreaInsightsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AreaInsightsTransport]] -_transport_registry['grpc'] = AreaInsightsGrpcTransport -_transport_registry['grpc_asyncio'] = AreaInsightsGrpcAsyncIOTransport -_transport_registry['rest'] = AreaInsightsRestTransport - -__all__ = ( - 'AreaInsightsTransport', - 'AreaInsightsGrpcTransport', - 'AreaInsightsGrpcAsyncIOTransport', - 'AreaInsightsRestTransport', - 'AreaInsightsRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/base.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/base.py deleted file mode 100644 index 57c23d3efe13..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/base.py +++ /dev/null @@ -1,163 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.areainsights_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.areainsights_v1.types import area_insights_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AreaInsightsTransport(abc.ABC): - """Abstract transport class for AreaInsights.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'areainsights.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: 'areainsights.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_insights: gapic_v1.method.wrap_method( - self.compute_insights, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.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 compute_insights(self) -> Callable[ - [area_insights_service.ComputeInsightsRequest], - Union[ - area_insights_service.ComputeInsightsResponse, - Awaitable[area_insights_service.ComputeInsightsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AreaInsightsTransport', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc.py deleted file mode 100644 index ab0371a36a28..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc.py +++ /dev/null @@ -1,282 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.maps.areainsights_v1.types import area_insights_service -from .base import AreaInsightsTransport, DEFAULT_CLIENT_INFO - - -class AreaInsightsGrpcTransport(AreaInsightsTransport): - """gRPC backend transport for AreaInsights. - - Service definition for the Places Insights 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 = 'areainsights.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: 'areainsights.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'areainsights.googleapis.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_insights(self) -> Callable[ - [area_insights_service.ComputeInsightsRequest], - area_insights_service.ComputeInsightsResponse]: - r"""Return a callable for the compute insights method over gRPC. - - Compute Insights RPC - - This method lets you retrieve insights about areas using a - variaty of filter such as: area, place type, operating status, - price level and ratings. Currently "count" and "places" insights - are supported. With "count" insights you can answer questions - such as "How many restaurant are located in California that are - operational, are inexpensive and have an average rating of at - least 4 stars" (see ``insight`` enum for more details). With - "places" insights, you can determine which places match the - requested filter. Clients can then use those place resource - names to fetch more details about each individual place using - the Places API. - - Returns: - Callable[[~.ComputeInsightsRequest], - ~.ComputeInsightsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_insights' not in self._stubs: - self._stubs['compute_insights'] = self.grpc_channel.unary_unary( - '/google.maps.areainsights.v1.AreaInsights/ComputeInsights', - request_serializer=area_insights_service.ComputeInsightsRequest.serialize, - response_deserializer=area_insights_service.ComputeInsightsResponse.deserialize, - ) - return self._stubs['compute_insights'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AreaInsightsGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc_asyncio.py deleted file mode 100644 index bf60bfa9fa69..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/grpc_asyncio.py +++ /dev/null @@ -1,312 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.areainsights_v1.types import area_insights_service -from .base import AreaInsightsTransport, DEFAULT_CLIENT_INFO -from .grpc import AreaInsightsGrpcTransport - - -class AreaInsightsGrpcAsyncIOTransport(AreaInsightsTransport): - """gRPC AsyncIO backend transport for AreaInsights. - - Service definition for the Places Insights 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 = 'areainsights.googleapis.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 = 'areainsights.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: 'areainsights.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_insights(self) -> Callable[ - [area_insights_service.ComputeInsightsRequest], - Awaitable[area_insights_service.ComputeInsightsResponse]]: - r"""Return a callable for the compute insights method over gRPC. - - Compute Insights RPC - - This method lets you retrieve insights about areas using a - variaty of filter such as: area, place type, operating status, - price level and ratings. Currently "count" and "places" insights - are supported. With "count" insights you can answer questions - such as "How many restaurant are located in California that are - operational, are inexpensive and have an average rating of at - least 4 stars" (see ``insight`` enum for more details). With - "places" insights, you can determine which places match the - requested filter. Clients can then use those place resource - names to fetch more details about each individual place using - the Places API. - - Returns: - Callable[[~.ComputeInsightsRequest], - Awaitable[~.ComputeInsightsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_insights' not in self._stubs: - self._stubs['compute_insights'] = self.grpc_channel.unary_unary( - '/google.maps.areainsights.v1.AreaInsights/ComputeInsights', - request_serializer=area_insights_service.ComputeInsightsRequest.serialize, - response_deserializer=area_insights_service.ComputeInsightsResponse.deserialize, - ) - return self._stubs['compute_insights'] - - 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_insights: self._wrap_method( - self.compute_insights, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'AreaInsightsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest.py deleted file mode 100644 index 75d995749fa2..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest.py +++ /dev/null @@ -1,275 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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.areainsights_v1.types import area_insights_service - - -from .rest_base import _BaseAreaInsightsRestTransport -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 - - -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 AreaInsightsRestInterceptor: - """Interceptor for AreaInsights. - - 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 AreaInsightsRestTransport. - - .. code-block:: python - class MyCustomAreaInsightsInterceptor(AreaInsightsRestInterceptor): - def pre_compute_insights(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_insights(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AreaInsightsRestTransport(interceptor=MyCustomAreaInsightsInterceptor()) - client = AreaInsightsClient(transport=transport) - - - """ - def pre_compute_insights(self, request: area_insights_service.ComputeInsightsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[area_insights_service.ComputeInsightsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_insights - - Override in a subclass to manipulate the request or metadata - before they are sent to the AreaInsights server. - """ - return request, metadata - - def post_compute_insights(self, response: area_insights_service.ComputeInsightsResponse) -> area_insights_service.ComputeInsightsResponse: - """Post-rpc interceptor for compute_insights - - Override in a subclass to manipulate the response - after it is returned by the AreaInsights server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AreaInsightsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AreaInsightsRestInterceptor - - -class AreaInsightsRestTransport(_BaseAreaInsightsRestTransport): - """REST backend synchronous transport for AreaInsights. - - Service definition for the Places Insights 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 = 'areainsights.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[AreaInsightsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'areainsights.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 AreaInsightsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ComputeInsights(_BaseAreaInsightsRestTransport._BaseComputeInsights, AreaInsightsRestStub): - def __hash__(self): - return hash("AreaInsightsRestTransport.ComputeInsights") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: area_insights_service.ComputeInsightsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> area_insights_service.ComputeInsightsResponse: - r"""Call the compute insights method over HTTP. - - Args: - request (~.area_insights_service.ComputeInsightsRequest): - The request object. Request for the ComputeInsights RPC. - retry (google.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. - - Returns: - ~.area_insights_service.ComputeInsightsResponse: - Response for the ComputeInsights RPC. - """ - - http_options = _BaseAreaInsightsRestTransport._BaseComputeInsights._get_http_options() - request, metadata = self._interceptor.pre_compute_insights(request, metadata) - transcoded_request = _BaseAreaInsightsRestTransport._BaseComputeInsights._get_transcoded_request(http_options, request) - - body = _BaseAreaInsightsRestTransport._BaseComputeInsights._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAreaInsightsRestTransport._BaseComputeInsights._get_query_params_json(transcoded_request) - - # Send the request - response = AreaInsightsRestTransport._ComputeInsights._get_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 = area_insights_service.ComputeInsightsResponse() - pb_resp = area_insights_service.ComputeInsightsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_compute_insights(resp) - return resp - - @property - def compute_insights(self) -> Callable[ - [area_insights_service.ComputeInsightsRequest], - area_insights_service.ComputeInsightsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeInsights(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AreaInsightsRestTransport', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest_base.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/transports/rest_base.py deleted file mode 100644 index 10ffc4defde0..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/services/area_insights/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 AreaInsightsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.maps.areainsights_v1.types import area_insights_service - - -class _BaseAreaInsightsRestTransport(AreaInsightsTransport): - """Base REST backend transport for AreaInsights. - - 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 = 'areainsights.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: 'areainsights.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 _BaseComputeInsights: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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:computeInsights', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = area_insights_service.ComputeInsightsRequest.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(_BaseAreaInsightsRestTransport._BaseComputeInsights._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseAreaInsightsRestTransport', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/__init__.py deleted file mode 100644 index 06ae52567693..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .area_insights_service import ( - ComputeInsightsRequest, - ComputeInsightsResponse, - Filter, - LocationFilter, - PlaceInsight, - RatingFilter, - TypeFilter, - Insight, - OperatingStatus, - PriceLevel, -) - -__all__ = ( - 'ComputeInsightsRequest', - 'ComputeInsightsResponse', - 'Filter', - 'LocationFilter', - 'PlaceInsight', - 'RatingFilter', - 'TypeFilter', - 'Insight', - 'OperatingStatus', - 'PriceLevel', -) diff --git a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/area_insights_service.py b/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/area_insights_service.py deleted file mode 100644 index e0796e3a9c67..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/google/maps/areainsights_v1/types/area_insights_service.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.areainsights.v1', - manifest={ - 'Insight', - 'OperatingStatus', - 'PriceLevel', - 'ComputeInsightsRequest', - 'ComputeInsightsResponse', - 'PlaceInsight', - 'Filter', - 'LocationFilter', - 'TypeFilter', - 'RatingFilter', - }, -) - - -class Insight(proto.Enum): - r"""Supported insights. - - Values: - INSIGHT_UNSPECIFIED (0): - Not Specified. - INSIGHT_COUNT (1): - Count insight. - - When this insight is specified ComputeInsights returns the - number of places that match the specified filter criteria. - - :: - - For example if the request is: - ComputeInsightsRequest { - insights: INSIGHT_COUNT - filter { - location_filter {region: } - type_filter {included_types: "restaurant"} - operating_status: OPERATING_STATUS_OPERATIONAL - price_levels: PRICE_LEVEL_FREE - price_levels: PRICE_LEVEL_INEXPENSIVE - min_rating: 4.0 - } - } - - The method will return the count of restaurants in California that are - operational, with price level free or inexpensive and have an average - rating of at least 4 starts. - - Example response: - ComputeInsightsResponse { - count: - } - INSIGHT_PLACES (2): - Return Places - - When this insight is specified ComputeInsights returns - Places that match the specified filter criteria. - - :: - - For example if the request is: - ComputeInsightsRequest { - insights: INSIGHT_PLACES - filter { - location_filter {region: } - type_filter {included_types: "restaurant"} - operating_status: OPERATING_STATUS_OPERATIONAL - price_levels: PRICE_LEVEL_FREE - price_levels: PRICE_LEVEL_INEXPENSIVE - min_rating: 4.0 - } - } - - The method will return list of places of restaurants in - California that are operational, with price level free or inexpensive and - have an average rating of at least 4 stars. - - Example response: - ComputeInsightsResponse { - place_insights { place: "places/ABC" } - place_insights { place: "places/PQR" } - place_insights { place: "places/XYZ" } - } - """ - INSIGHT_UNSPECIFIED = 0 - INSIGHT_COUNT = 1 - INSIGHT_PLACES = 2 - - -class OperatingStatus(proto.Enum): - r"""Operating status of the place. - - Values: - OPERATING_STATUS_UNSPECIFIED (0): - Not Specified. - OPERATING_STATUS_OPERATIONAL (1): - The place is operational and its open during - its defined hours. - OPERATING_STATUS_PERMANENTLY_CLOSED (3): - The Place is no longer in business. - OPERATING_STATUS_TEMPORARILY_CLOSED (4): - The Place is temporarily closed and expected - to reopen in the future. - """ - OPERATING_STATUS_UNSPECIFIED = 0 - OPERATING_STATUS_OPERATIONAL = 1 - OPERATING_STATUS_PERMANENTLY_CLOSED = 3 - OPERATING_STATUS_TEMPORARILY_CLOSED = 4 - - -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 ComputeInsightsRequest(proto.Message): - r"""Request for the ComputeInsights RPC. - - Attributes: - insights (MutableSequence[google.maps.areainsights_v1.types.Insight]): - Required. Insights to compute. Currently only INSIGHT_COUNT - and INSIGHT_PLACES are supported. - filter (google.maps.areainsights_v1.types.Filter): - Required. Insight filter. - """ - - insights: MutableSequence['Insight'] = proto.RepeatedField( - proto.ENUM, - number=4, - enum='Insight', - ) - filter: 'Filter' = proto.Field( - proto.MESSAGE, - number=5, - message='Filter', - ) - - -class ComputeInsightsResponse(proto.Message): - r"""Response for the ComputeInsights RPC. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - count (int): - Result for Insights.INSIGHT_COUNT. - - This field is a member of `oneof`_ ``_count``. - place_insights (MutableSequence[google.maps.areainsights_v1.types.PlaceInsight]): - Result for Insights.INSIGHT_PLACES. - """ - - count: int = proto.Field( - proto.INT64, - number=1, - optional=True, - ) - place_insights: MutableSequence['PlaceInsight'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='PlaceInsight', - ) - - -class PlaceInsight(proto.Message): - r"""Holds information about a place - - Attributes: - place (str): - The resource name of a place. This resource name can be used - to retrieve details about the place using the `Places - API `__. - """ - - place: str = proto.Field( - proto.STRING, - number=1, - ) - - -class Filter(proto.Message): - r"""Filters for the ComputeInsights RPC. - - Attributes: - location_filter (google.maps.areainsights_v1.types.LocationFilter): - Required. Restricts results to places which - are located in the area specified by location - filters. - type_filter (google.maps.areainsights_v1.types.TypeFilter): - Required. Place type filters. - operating_status (MutableSequence[google.maps.areainsights_v1.types.OperatingStatus]): - Optional. Restricts results to places whose operating status - is included on this list. If operating_status is not set, - OPERATING_STATUS_OPERATIONAL is used as default. - price_levels (MutableSequence[google.maps.areainsights_v1.types.PriceLevel]): - Optional. Restricts results to places whose price level is - included on this list. If price_level is not set, all price - levels are included in the results. - rating_filter (google.maps.areainsights_v1.types.RatingFilter): - Optional. Restricts results to places whose average user - ratings are in the range specified by rating_filter. If - rating_filter is not set, all ratings are included in the - result. - """ - - location_filter: 'LocationFilter' = proto.Field( - proto.MESSAGE, - number=1, - message='LocationFilter', - ) - type_filter: 'TypeFilter' = proto.Field( - proto.MESSAGE, - number=2, - message='TypeFilter', - ) - operating_status: MutableSequence['OperatingStatus'] = proto.RepeatedField( - proto.ENUM, - number=3, - enum='OperatingStatus', - ) - price_levels: MutableSequence['PriceLevel'] = proto.RepeatedField( - proto.ENUM, - number=4, - enum='PriceLevel', - ) - rating_filter: 'RatingFilter' = proto.Field( - proto.MESSAGE, - number=5, - message='RatingFilter', - ) - - -class LocationFilter(proto.Message): - r"""Location filters. - - Specifies the area of interest for the insight. - - 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: - circle (google.maps.areainsights_v1.types.LocationFilter.Circle): - Area as a circle. - - This field is a member of `oneof`_ ``area``. - region (google.maps.areainsights_v1.types.LocationFilter.Region): - Area as region. - - This field is a member of `oneof`_ ``area``. - custom_area (google.maps.areainsights_v1.types.LocationFilter.CustomArea): - Custom area specified by a polygon. - - This field is a member of `oneof`_ ``area``. - """ - - class Circle(proto.Message): - r"""A circle is defined by a center point and radius in meters. - - 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: - lat_lng (google.type.latlng_pb2.LatLng): - The latitude and longitude of the center of - the circle. - - This field is a member of `oneof`_ ``center``. - place (str): - The Place resource name of the center of the - circle. Only point places are supported. - - This field is a member of `oneof`_ ``center``. - radius (int): - Optional. The radius of the circle in meters - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - oneof='center', - message=latlng_pb2.LatLng, - ) - place: str = proto.Field( - proto.STRING, - number=2, - oneof='center', - ) - radius: int = proto.Field( - proto.INT32, - number=3, - ) - - class Region(proto.Message): - r"""A region is a geographic boundary such as: cities, postal - codes, counties, states, etc. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - place (str): - The Place resource name of a region. - - This field is a member of `oneof`_ ``region``. - """ - - place: str = proto.Field( - proto.STRING, - number=1, - oneof='region', - ) - - class CustomArea(proto.Message): - r"""Custom Area. - - Attributes: - polygon (google.maps.areainsights_v1.types.LocationFilter.CustomArea.Polygon): - Required. The custom area represented as a - polygon - """ - - class Polygon(proto.Message): - r"""A polygon is represented by a series of connected coordinates - in an counterclockwise ordered sequence. The coordinates form a - closed loop and define a filled region. The first and last - coordinates are equivalent, and they must contain identical - values. The format is a simplified version of GeoJSON polygons - (we only support one counterclockwise exterior ring). - - Attributes: - coordinates (MutableSequence[google.type.latlng_pb2.LatLng]): - Optional. The coordinates that define the - polygon. - """ - - coordinates: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - - polygon: 'LocationFilter.CustomArea.Polygon' = proto.Field( - proto.MESSAGE, - number=1, - message='LocationFilter.CustomArea.Polygon', - ) - - circle: Circle = proto.Field( - proto.MESSAGE, - number=1, - oneof='area', - message=Circle, - ) - region: Region = proto.Field( - proto.MESSAGE, - number=2, - oneof='area', - message=Region, - ) - custom_area: CustomArea = proto.Field( - proto.MESSAGE, - number=3, - oneof='area', - message=CustomArea, - ) - - -class TypeFilter(proto.Message): - r"""Place type filters. - - Only Place types from `Table - a `__ - are supported. - - A place can only have a single primary type associated with it. For - example, the primary type might be "mexican_restaurant" or - "steak_house". Use included_primary_types and excluded_primary_types - to filter the results on a place's primary type. - - A place can also have multiple type values associated with it. For - example a restaurant might have the following types: - "seafood_restaurant", "restaurant", "food", "point_of_interest", - "establishment". Use included_types and excluded_types to filter the - results on the list of types associated with a place. - - If a search is specified with multiple type restrictions, only - places that satisfy all of the restrictions are returned. For - example, if you specify {"included_types": ["restaurant"], - "excluded_primary_types": ["steak_house"]}, the returned places - provide "restaurant" related services but do not operate primarily - as a "steak_house". - - If there are any conflicting types, i.e. a type appears in both - included_types and excluded_types types or included_primary_types - and excluded_primary_types, an INVALID_ARGUMENT error is returned. - - One of included_types or included_primary_types must be set. - - Attributes: - included_types (MutableSequence[str]): - Optional. Included Place types. - excluded_types (MutableSequence[str]): - Optional. Excluded Place types. - included_primary_types (MutableSequence[str]): - Optional. Included primary Place types. - excluded_primary_types (MutableSequence[str]): - Optional. Excluded primary Place types. - """ - - included_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - excluded_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - included_primary_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - excluded_primary_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class RatingFilter(proto.Message): - r"""Average user rating filters. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - min_rating (float): - Optional. Restricts results to places whose average user - rating is greater than or equal to min_rating. Values must - be between 1.0 and 5.0. - - This field is a member of `oneof`_ ``_min_rating``. - max_rating (float): - Optional. Restricts results to places whose average user - rating is strictly less than or equal to max_rating. Values - must be between 1.0 and 5.0. - - This field is a member of `oneof`_ ``_max_rating``. - """ - - min_rating: float = proto.Field( - proto.FLOAT, - number=5, - optional=True, - ) - max_rating: float = proto.Field( - proto.FLOAT, - number=6, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-areainsights/v1/mypy.ini b/owl-bot-staging/google-maps-areainsights/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/noxfile.py b/owl-bot-staging/google-maps-areainsights/v1/noxfile.py deleted file mode 100644 index c9af38e95ec1..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights' - -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/areainsights_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/areainsights_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-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_async.py b/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_async.py deleted file mode 100644 index 880f4b4385cc..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_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 ComputeInsights -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-areainsights - - -# [START areainsights_v1_generated_AreaInsights_ComputeInsights_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 areainsights_v1 - - -async def sample_compute_insights(): - # Create a client - client = areainsights_v1.AreaInsightsAsyncClient() - - # Initialize request argument(s) - request = areainsights_v1.ComputeInsightsRequest( - insights=['INSIGHT_PLACES'], - ) - - # Make the request - response = await client.compute_insights(request=request) - - # Handle the response - print(response) - -# [END areainsights_v1_generated_AreaInsights_ComputeInsights_async] diff --git a/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_sync.py b/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_sync.py deleted file mode 100644 index cbf41464d3b3..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/areainsights_v1_generated_area_insights_compute_insights_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 ComputeInsights -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-areainsights - - -# [START areainsights_v1_generated_AreaInsights_ComputeInsights_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 areainsights_v1 - - -def sample_compute_insights(): - # Create a client - client = areainsights_v1.AreaInsightsClient() - - # Initialize request argument(s) - request = areainsights_v1.ComputeInsightsRequest( - insights=['INSIGHT_PLACES'], - ) - - # Make the request - response = client.compute_insights(request=request) - - # Handle the response - print(response) - -# [END areainsights_v1_generated_AreaInsights_ComputeInsights_sync] diff --git a/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/snippet_metadata_google.maps.areainsights.v1.json b/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/snippet_metadata_google.maps.areainsights.v1.json deleted file mode 100644 index 508e4607c0f8..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/samples/generated_samples/snippet_metadata_google.maps.areainsights.v1.json +++ /dev/null @@ -1,168 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.areainsights.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-areainsights", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.areainsights_v1.AreaInsightsAsyncClient", - "shortName": "AreaInsightsAsyncClient" - }, - "fullName": "google.maps.areainsights_v1.AreaInsightsAsyncClient.compute_insights", - "method": { - "fullName": "google.maps.areainsights.v1.AreaInsights.ComputeInsights", - "service": { - "fullName": "google.maps.areainsights.v1.AreaInsights", - "shortName": "AreaInsights" - }, - "shortName": "ComputeInsights" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.areainsights_v1.types.ComputeInsightsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.areainsights_v1.types.ComputeInsightsResponse", - "shortName": "compute_insights" - }, - "description": "Sample for ComputeInsights", - "file": "areainsights_v1_generated_area_insights_compute_insights_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "areainsights_v1_generated_AreaInsights_ComputeInsights_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": "areainsights_v1_generated_area_insights_compute_insights_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.areainsights_v1.AreaInsightsClient", - "shortName": "AreaInsightsClient" - }, - "fullName": "google.maps.areainsights_v1.AreaInsightsClient.compute_insights", - "method": { - "fullName": "google.maps.areainsights.v1.AreaInsights.ComputeInsights", - "service": { - "fullName": "google.maps.areainsights.v1.AreaInsights", - "shortName": "AreaInsights" - }, - "shortName": "ComputeInsights" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.areainsights_v1.types.ComputeInsightsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.areainsights_v1.types.ComputeInsightsResponse", - "shortName": "compute_insights" - }, - "description": "Sample for ComputeInsights", - "file": "areainsights_v1_generated_area_insights_compute_insights_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "areainsights_v1_generated_AreaInsights_ComputeInsights_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": "areainsights_v1_generated_area_insights_compute_insights_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-areainsights/v1/scripts/fixup_areainsights_v1_keywords.py b/owl-bot-staging/google-maps-areainsights/v1/scripts/fixup_areainsights_v1_keywords.py deleted file mode 100644 index 2b35b82f7b4e..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/scripts/fixup_areainsights_v1_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 areainsightsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_insights': ('insights', 'filter', ), - } - - 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=areainsightsCallTransformer(), -): - """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 areainsights 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-areainsights/v1/setup.py b/owl-bot-staging/google-maps-areainsights/v1/setup.py deleted file mode 100644 index b4a51e3a8d23..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights' - - -description = "Google Maps Areainsights API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/areainsights/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-areainsights" - -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-areainsights/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/tests/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-areainsights/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-areainsights/v1/tests/unit/gapic/areainsights_v1/__init__.py b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_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-areainsights/v1/tests/unit/gapic/areainsights_v1/test_area_insights.py b/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/test_area_insights.py deleted file mode 100644 index 7c2001255008..000000000000 --- a/owl-bot-staging/google-maps-areainsights/v1/tests/unit/gapic/areainsights_v1/test_area_insights.py +++ /dev/null @@ -1,1935 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.areainsights_v1.services.area_insights import AreaInsightsAsyncClient -from google.maps.areainsights_v1.services.area_insights import AreaInsightsClient -from google.maps.areainsights_v1.services.area_insights import transports -from google.maps.areainsights_v1.types import area_insights_service -from google.oauth2 import service_account -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 AreaInsightsClient._get_default_mtls_endpoint(None) is None - assert AreaInsightsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AreaInsightsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AreaInsightsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AreaInsightsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AreaInsightsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AreaInsightsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AreaInsightsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AreaInsightsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AreaInsightsClient._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 AreaInsightsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AreaInsightsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AreaInsightsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AreaInsightsClient._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 AreaInsightsClient._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 AreaInsightsClient._get_client_cert_source(None, False) is None - assert AreaInsightsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AreaInsightsClient._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 AreaInsightsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AreaInsightsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AreaInsightsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsClient)) -@mock.patch.object(AreaInsightsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AreaInsightsClient._DEFAULT_UNIVERSE - default_endpoint = AreaInsightsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AreaInsightsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AreaInsightsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AreaInsightsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AreaInsightsClient.DEFAULT_MTLS_ENDPOINT - assert AreaInsightsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AreaInsightsClient._get_api_endpoint(None, None, default_universe, "always") == AreaInsightsClient.DEFAULT_MTLS_ENDPOINT - assert AreaInsightsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AreaInsightsClient.DEFAULT_MTLS_ENDPOINT - assert AreaInsightsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AreaInsightsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AreaInsightsClient._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 AreaInsightsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AreaInsightsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AreaInsightsClient._get_universe_domain(None, None) == AreaInsightsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AreaInsightsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc"), - (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AreaInsightsClient, "grpc"), - (AreaInsightsAsyncClient, "grpc_asyncio"), - (AreaInsightsClient, "rest"), -]) -def test_area_insights_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 == ( - 'areainsights.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://areainsights.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AreaInsightsGrpcTransport, "grpc"), - (transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AreaInsightsRestTransport, "rest"), -]) -def test_area_insights_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", [ - (AreaInsightsClient, "grpc"), - (AreaInsightsAsyncClient, "grpc_asyncio"), - (AreaInsightsClient, "rest"), -]) -def test_area_insights_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 == ( - 'areainsights.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://areainsights.googleapis.com' - ) - - -def test_area_insights_client_get_transport_class(): - transport = AreaInsightsClient.get_transport_class() - available_transports = [ - transports.AreaInsightsGrpcTransport, - transports.AreaInsightsRestTransport, - ] - assert transport in available_transports - - transport = AreaInsightsClient.get_transport_class("grpc") - assert transport == transports.AreaInsightsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc"), - (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio"), - (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest"), -]) -@mock.patch.object(AreaInsightsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsClient)) -@mock.patch.object(AreaInsightsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsAsyncClient)) -def test_area_insights_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(AreaInsightsClient, '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(AreaInsightsClient, '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", [ - (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc", "true"), - (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc", "false"), - (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest", "true"), - (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest", "false"), -]) -@mock.patch.object(AreaInsightsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsClient)) -@mock.patch.object(AreaInsightsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_area_insights_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", [ - AreaInsightsClient, AreaInsightsAsyncClient -]) -@mock.patch.object(AreaInsightsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AreaInsightsClient)) -@mock.patch.object(AreaInsightsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AreaInsightsAsyncClient)) -def test_area_insights_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", [ - AreaInsightsClient, AreaInsightsAsyncClient -]) -@mock.patch.object(AreaInsightsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsClient)) -@mock.patch.object(AreaInsightsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AreaInsightsAsyncClient)) -def test_area_insights_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AreaInsightsClient._DEFAULT_UNIVERSE - default_endpoint = AreaInsightsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AreaInsightsClient._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", [ - (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc"), - (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio"), - (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest"), -]) -def test_area_insights_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", [ - (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc", grpc_helpers), - (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AreaInsightsClient, transports.AreaInsightsRestTransport, "rest", None), -]) -def test_area_insights_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_area_insights_client_client_options_from_dict(): - with mock.patch('google.maps.areainsights_v1.services.area_insights.transports.AreaInsightsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AreaInsightsClient( - 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", [ - (AreaInsightsClient, transports.AreaInsightsGrpcTransport, "grpc", grpc_helpers), - (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_area_insights_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( - "areainsights.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="areainsights.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - area_insights_service.ComputeInsightsRequest, - dict, -]) -def test_compute_insights(request_type, transport: str = 'grpc'): - client = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_insights), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = area_insights_service.ComputeInsightsResponse( - count=553, - ) - response = client.compute_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = area_insights_service.ComputeInsightsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, area_insights_service.ComputeInsightsResponse) - assert response.count == 553 - - -def test_compute_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 = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = area_insights_service.ComputeInsightsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_insights), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.compute_insights(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == area_insights_service.ComputeInsightsRequest( - ) - -def test_compute_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 = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.compute_insights] = mock_rpc - request = {} - client.compute_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_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_compute_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 = AreaInsightsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_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.compute_insights] = mock_rpc - - request = {} - await client.compute_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.compute_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_compute_insights_async(transport: str = 'grpc_asyncio', request_type=area_insights_service.ComputeInsightsRequest): - client = AreaInsightsAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_insights), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(area_insights_service.ComputeInsightsResponse( - count=553, - )) - response = await client.compute_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = area_insights_service.ComputeInsightsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, area_insights_service.ComputeInsightsResponse) - assert response.count == 553 - - -@pytest.mark.asyncio -async def test_compute_insights_async_from_dict(): - await test_compute_insights_async(request_type=dict) - - -def test_compute_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 = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.compute_insights] = mock_rpc - - request = {} - client.compute_insights(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_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_compute_insights_rest_required_fields(request_type=area_insights_service.ComputeInsightsRequest): - transport_class = transports.AreaInsightsRestTransport - - 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_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()).compute_insights._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = area_insights_service.ComputeInsightsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = area_insights_service.ComputeInsightsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.compute_insights(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_insights_rest_unset_required_fields(): - transport = transports.AreaInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_insights._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("insights", "filter", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AreaInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AreaInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AreaInsightsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AreaInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AreaInsightsClient( - 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 = AreaInsightsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AreaInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AreaInsightsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AreaInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AreaInsightsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AreaInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AreaInsightsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AreaInsightsGrpcTransport, - transports.AreaInsightsGrpcAsyncIOTransport, - transports.AreaInsightsRestTransport, -]) -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 = AreaInsightsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AreaInsightsClient( - 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_insights_empty_call_grpc(): - client = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_insights), - '__call__') as call: - call.return_value = area_insights_service.ComputeInsightsResponse() - client.compute_insights(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = area_insights_service.ComputeInsightsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AreaInsightsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AreaInsightsAsyncClient( - 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_insights_empty_call_grpc_asyncio(): - client = AreaInsightsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_insights), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(area_insights_service.ComputeInsightsResponse( - count=553, - )) - await client.compute_insights(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = area_insights_service.ComputeInsightsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AreaInsightsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_compute_insights_rest_bad_request(request_type=area_insights_service.ComputeInsightsRequest): - client = AreaInsightsClient( - 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 - client.compute_insights(request) - - -@pytest.mark.parametrize("request_type", [ - area_insights_service.ComputeInsightsRequest, - dict, -]) -def test_compute_insights_rest_call_success(request_type): - client = AreaInsightsClient( - 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 = area_insights_service.ComputeInsightsResponse( - count=553, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = area_insights_service.ComputeInsightsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.compute_insights(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, area_insights_service.ComputeInsightsResponse) - assert response.count == 553 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_insights_rest_interceptors(null_interceptor): - transport = transports.AreaInsightsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AreaInsightsRestInterceptor(), - ) - client = AreaInsightsClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AreaInsightsRestInterceptor, "post_compute_insights") as post, \ - mock.patch.object(transports.AreaInsightsRestInterceptor, "pre_compute_insights") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = area_insights_service.ComputeInsightsRequest.pb(area_insights_service.ComputeInsightsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = area_insights_service.ComputeInsightsResponse.to_json(area_insights_service.ComputeInsightsResponse()) - req.return_value.content = return_value - - request = area_insights_service.ComputeInsightsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = area_insights_service.ComputeInsightsResponse() - - client.compute_insights(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = AreaInsightsClient( - 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_insights_empty_call_rest(): - client = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_insights), - '__call__') as call: - client.compute_insights(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = area_insights_service.ComputeInsightsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AreaInsightsGrpcTransport, - ) - -def test_area_insights_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AreaInsightsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_area_insights_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.areainsights_v1.services.area_insights.transports.AreaInsightsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AreaInsightsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'compute_insights', - ) - 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_area_insights_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.areainsights_v1.services.area_insights.transports.AreaInsightsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AreaInsightsTransport( - 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_area_insights_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.areainsights_v1.services.area_insights.transports.AreaInsightsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AreaInsightsTransport() - adc.assert_called_once() - - -def test_area_insights_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) - AreaInsightsClient() - 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.AreaInsightsGrpcTransport, - transports.AreaInsightsGrpcAsyncIOTransport, - ], -) -def test_area_insights_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.AreaInsightsGrpcTransport, - transports.AreaInsightsGrpcAsyncIOTransport, - transports.AreaInsightsRestTransport, - ], -) -def test_area_insights_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.AreaInsightsGrpcTransport, grpc_helpers), - (transports.AreaInsightsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_area_insights_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( - "areainsights.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="areainsights.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AreaInsightsGrpcTransport, transports.AreaInsightsGrpcAsyncIOTransport]) -def test_area_insights_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_area_insights_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.AreaInsightsRestTransport ( - 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_area_insights_host_no_port(transport_name): - client = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='areainsights.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'areainsights.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://areainsights.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_area_insights_host_with_port(transport_name): - client = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='areainsights.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'areainsights.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://areainsights.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_area_insights_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AreaInsightsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AreaInsightsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.compute_insights._session - session2 = client2.transport.compute_insights._session - assert session1 != session2 -def test_area_insights_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AreaInsightsGrpcTransport( - 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_area_insights_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AreaInsightsGrpcAsyncIOTransport( - 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.AreaInsightsGrpcTransport, transports.AreaInsightsGrpcAsyncIOTransport]) -def test_area_insights_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.AreaInsightsGrpcTransport, transports.AreaInsightsGrpcAsyncIOTransport]) -def test_area_insights_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_place_path(): - place_id = "squid" - expected = "places/{place_id}".format(place_id=place_id, ) - actual = AreaInsightsClient.place_path(place_id) - assert expected == actual - - -def test_parse_place_path(): - expected = { - "place_id": "clam", - } - path = AreaInsightsClient.place_path(**expected) - - # Check that the path construction is reversible. - actual = AreaInsightsClient.parse_place_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AreaInsightsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = AreaInsightsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AreaInsightsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = AreaInsightsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = AreaInsightsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AreaInsightsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AreaInsightsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = AreaInsightsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AreaInsightsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = AreaInsightsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = AreaInsightsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AreaInsightsClient.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 = AreaInsightsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = AreaInsightsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AreaInsightsClient.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.AreaInsightsTransport, '_prep_wrapped_messages') as prep: - client = AreaInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AreaInsightsTransport, '_prep_wrapped_messages') as prep: - transport_class = AreaInsightsClient.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 = AreaInsightsClient( - 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 = AreaInsightsAsyncClient( - 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 = AreaInsightsClient( - 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 = AreaInsightsClient( - 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", [ - (AreaInsightsClient, transports.AreaInsightsGrpcTransport), - (AreaInsightsAsyncClient, transports.AreaInsightsGrpcAsyncIOTransport), -]) -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-fleetengine-delivery/v1/.coveragerc b/owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc deleted file mode 100644 index 4d78db33eace..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/fleetengine_delivery/__init__.py - google/maps/fleetengine_delivery/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-fleetengine-delivery/v1/.flake8 b/owl-bot-staging/google-maps-fleetengine-delivery/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/MANIFEST.in b/owl-bot-staging/google-maps-fleetengine-delivery/v1/MANIFEST.in deleted file mode 100644 index 76734494c81d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/fleetengine_delivery *.py -recursive-include google/maps/fleetengine_delivery_v1 *.py diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst deleted file mode 100644 index 1261668cfc0b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Fleetengine Delivery 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 Fleetengine Delivery 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-fleetengine-delivery/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/docs/conf.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/conf.py deleted file mode 100644 index ba785733498b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery 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-fleetengine-delivery" -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-fleetengine-delivery-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-fleetengine-delivery.tex", - u"google-maps-fleetengine-delivery 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-fleetengine-delivery", - u"Google Maps Fleetengine Delivery 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-fleetengine-delivery", - u"google-maps-fleetengine-delivery Documentation", - author, - "google-maps-fleetengine-delivery", - "GAPIC library for Google Maps Fleetengine Delivery 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-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst deleted file mode 100644 index 88aac9c4fbb4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DeliveryService ---------------------------------- - -.. automodule:: google.maps.fleetengine_delivery_v1.services.delivery_service - :members: - :inherited-members: - -.. automodule:: google.maps.fleetengine_delivery_v1.services.delivery_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst deleted file mode 100644 index 97febb72086f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Fleetengine Delivery v1 API -==================================================== -.. toctree:: - :maxdepth: 2 - - delivery_service diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst deleted file mode 100644 index d633ae8b217f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Fleetengine Delivery v1 API -================================================= - -.. automodule:: google.maps.fleetengine_delivery_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst deleted file mode 100644 index a5601707f6f4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - fleetengine_delivery_v1/services_ - fleetengine_delivery_v1/types_ diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py deleted file mode 100644 index 9aceee6293a4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__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.fleetengine_delivery import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.fleetengine_delivery_v1.services.delivery_service.client import DeliveryServiceClient -from google.maps.fleetengine_delivery_v1.services.delivery_service.async_client import DeliveryServiceAsyncClient - -from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleAttribute -from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleLocation -from google.maps.fleetengine_delivery_v1.types.common import TaskAttribute -from google.maps.fleetengine_delivery_v1.types.common import TimeWindow -from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleLocationSensor -from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleNavigationStatus -from google.maps.fleetengine_delivery_v1.types.delivery_api import BatchCreateTasksRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import BatchCreateTasksResponse -from google.maps.fleetengine_delivery_v1.types.delivery_api import CreateDeliveryVehicleRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import CreateTaskRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import GetDeliveryVehicleRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import GetTaskRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import GetTaskTrackingInfoRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import ListDeliveryVehiclesRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import ListDeliveryVehiclesResponse -from google.maps.fleetengine_delivery_v1.types.delivery_api import ListTasksRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import ListTasksResponse -from google.maps.fleetengine_delivery_v1.types.delivery_api import UpdateDeliveryVehicleRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import UpdateTaskRequest -from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import DeliveryVehicle -from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import LocationInfo -from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import VehicleJourneySegment -from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import VehicleStop -from google.maps.fleetengine_delivery_v1.types.header import DeliveryRequestHeader -from google.maps.fleetengine_delivery_v1.types.task_tracking_info import TaskTrackingInfo -from google.maps.fleetengine_delivery_v1.types.tasks import Task -from google.maps.fleetengine_delivery_v1.types.tasks import TaskTrackingViewConfig - -__all__ = ('DeliveryServiceClient', - 'DeliveryServiceAsyncClient', - 'DeliveryVehicleAttribute', - 'DeliveryVehicleLocation', - 'TaskAttribute', - 'TimeWindow', - 'DeliveryVehicleLocationSensor', - 'DeliveryVehicleNavigationStatus', - 'BatchCreateTasksRequest', - 'BatchCreateTasksResponse', - 'CreateDeliveryVehicleRequest', - 'CreateTaskRequest', - 'GetDeliveryVehicleRequest', - 'GetTaskRequest', - 'GetTaskTrackingInfoRequest', - 'ListDeliveryVehiclesRequest', - 'ListDeliveryVehiclesResponse', - 'ListTasksRequest', - 'ListTasksResponse', - 'UpdateDeliveryVehicleRequest', - 'UpdateTaskRequest', - 'DeliveryVehicle', - 'LocationInfo', - 'VehicleJourneySegment', - 'VehicleStop', - 'DeliveryRequestHeader', - 'TaskTrackingInfo', - 'Task', - 'TaskTrackingViewConfig', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/gapic_version.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/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-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed deleted file mode 100644 index 8464ee4c8285..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-fleetengine-delivery package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py deleted file mode 100644 index 3dee9f0b3f48..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_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.fleetengine_delivery_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.delivery_service import DeliveryServiceClient -from .services.delivery_service import DeliveryServiceAsyncClient - -from .types.common import DeliveryVehicleAttribute -from .types.common import DeliveryVehicleLocation -from .types.common import TaskAttribute -from .types.common import TimeWindow -from .types.common import DeliveryVehicleLocationSensor -from .types.common import DeliveryVehicleNavigationStatus -from .types.delivery_api import BatchCreateTasksRequest -from .types.delivery_api import BatchCreateTasksResponse -from .types.delivery_api import CreateDeliveryVehicleRequest -from .types.delivery_api import CreateTaskRequest -from .types.delivery_api import GetDeliveryVehicleRequest -from .types.delivery_api import GetTaskRequest -from .types.delivery_api import GetTaskTrackingInfoRequest -from .types.delivery_api import ListDeliveryVehiclesRequest -from .types.delivery_api import ListDeliveryVehiclesResponse -from .types.delivery_api import ListTasksRequest -from .types.delivery_api import ListTasksResponse -from .types.delivery_api import UpdateDeliveryVehicleRequest -from .types.delivery_api import UpdateTaskRequest -from .types.delivery_vehicles import DeliveryVehicle -from .types.delivery_vehicles import LocationInfo -from .types.delivery_vehicles import VehicleJourneySegment -from .types.delivery_vehicles import VehicleStop -from .types.header import DeliveryRequestHeader -from .types.task_tracking_info import TaskTrackingInfo -from .types.tasks import Task -from .types.tasks import TaskTrackingViewConfig - -__all__ = ( - 'DeliveryServiceAsyncClient', -'BatchCreateTasksRequest', -'BatchCreateTasksResponse', -'CreateDeliveryVehicleRequest', -'CreateTaskRequest', -'DeliveryRequestHeader', -'DeliveryServiceClient', -'DeliveryVehicle', -'DeliveryVehicleAttribute', -'DeliveryVehicleLocation', -'DeliveryVehicleLocationSensor', -'DeliveryVehicleNavigationStatus', -'GetDeliveryVehicleRequest', -'GetTaskRequest', -'GetTaskTrackingInfoRequest', -'ListDeliveryVehiclesRequest', -'ListDeliveryVehiclesResponse', -'ListTasksRequest', -'ListTasksResponse', -'LocationInfo', -'Task', -'TaskAttribute', -'TaskTrackingInfo', -'TaskTrackingViewConfig', -'TimeWindow', -'UpdateDeliveryVehicleRequest', -'UpdateTaskRequest', -'VehicleJourneySegment', -'VehicleStop', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json deleted file mode 100644 index 8b15810ecafd..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json +++ /dev/null @@ -1,178 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.fleetengine_delivery_v1", - "protoPackage": "maps.fleetengine.delivery.v1", - "schema": "1.0", - "services": { - "DeliveryService": { - "clients": { - "grpc": { - "libraryClient": "DeliveryServiceClient", - "rpcs": { - "BatchCreateTasks": { - "methods": [ - "batch_create_tasks" - ] - }, - "CreateDeliveryVehicle": { - "methods": [ - "create_delivery_vehicle" - ] - }, - "CreateTask": { - "methods": [ - "create_task" - ] - }, - "GetDeliveryVehicle": { - "methods": [ - "get_delivery_vehicle" - ] - }, - "GetTask": { - "methods": [ - "get_task" - ] - }, - "GetTaskTrackingInfo": { - "methods": [ - "get_task_tracking_info" - ] - }, - "ListDeliveryVehicles": { - "methods": [ - "list_delivery_vehicles" - ] - }, - "ListTasks": { - "methods": [ - "list_tasks" - ] - }, - "UpdateDeliveryVehicle": { - "methods": [ - "update_delivery_vehicle" - ] - }, - "UpdateTask": { - "methods": [ - "update_task" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DeliveryServiceAsyncClient", - "rpcs": { - "BatchCreateTasks": { - "methods": [ - "batch_create_tasks" - ] - }, - "CreateDeliveryVehicle": { - "methods": [ - "create_delivery_vehicle" - ] - }, - "CreateTask": { - "methods": [ - "create_task" - ] - }, - "GetDeliveryVehicle": { - "methods": [ - "get_delivery_vehicle" - ] - }, - "GetTask": { - "methods": [ - "get_task" - ] - }, - "GetTaskTrackingInfo": { - "methods": [ - "get_task_tracking_info" - ] - }, - "ListDeliveryVehicles": { - "methods": [ - "list_delivery_vehicles" - ] - }, - "ListTasks": { - "methods": [ - "list_tasks" - ] - }, - "UpdateDeliveryVehicle": { - "methods": [ - "update_delivery_vehicle" - ] - }, - "UpdateTask": { - "methods": [ - "update_task" - ] - } - } - }, - "rest": { - "libraryClient": "DeliveryServiceClient", - "rpcs": { - "BatchCreateTasks": { - "methods": [ - "batch_create_tasks" - ] - }, - "CreateDeliveryVehicle": { - "methods": [ - "create_delivery_vehicle" - ] - }, - "CreateTask": { - "methods": [ - "create_task" - ] - }, - "GetDeliveryVehicle": { - "methods": [ - "get_delivery_vehicle" - ] - }, - "GetTask": { - "methods": [ - "get_task" - ] - }, - "GetTaskTrackingInfo": { - "methods": [ - "get_task_tracking_info" - ] - }, - "ListDeliveryVehicles": { - "methods": [ - "list_delivery_vehicles" - ] - }, - "ListTasks": { - "methods": [ - "list_tasks" - ] - }, - "UpdateDeliveryVehicle": { - "methods": [ - "update_delivery_vehicle" - ] - }, - "UpdateTask": { - "methods": [ - "update_task" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_version.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_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-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed deleted file mode 100644 index 8464ee4c8285..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-fleetengine-delivery package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_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-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/__init__.py deleted file mode 100644 index 4dc5b334d96a..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_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 DeliveryServiceClient -from .async_client import DeliveryServiceAsyncClient - -__all__ = ( - 'DeliveryServiceClient', - 'DeliveryServiceAsyncClient', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py deleted file mode 100644 index c42f336acb5c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py +++ /dev/null @@ -1,1558 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.maps.fleetengine_delivery_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.fleetengine_delivery_v1.services.delivery_service import pagers -from google.maps.fleetengine_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -from .transports.base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DeliveryServiceGrpcAsyncIOTransport -from .client import DeliveryServiceClient - - -class DeliveryServiceAsyncClient: - """The Last Mile Delivery service.""" - - _client: DeliveryServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = DeliveryServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = DeliveryServiceClient._DEFAULT_UNIVERSE - - delivery_vehicle_path = staticmethod(DeliveryServiceClient.delivery_vehicle_path) - parse_delivery_vehicle_path = staticmethod(DeliveryServiceClient.parse_delivery_vehicle_path) - task_path = staticmethod(DeliveryServiceClient.task_path) - parse_task_path = staticmethod(DeliveryServiceClient.parse_task_path) - task_tracking_info_path = staticmethod(DeliveryServiceClient.task_tracking_info_path) - parse_task_tracking_info_path = staticmethod(DeliveryServiceClient.parse_task_tracking_info_path) - common_billing_account_path = staticmethod(DeliveryServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DeliveryServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DeliveryServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DeliveryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DeliveryServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DeliveryServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DeliveryServiceClient.common_project_path) - parse_common_project_path = staticmethod(DeliveryServiceClient.parse_common_project_path) - common_location_path = staticmethod(DeliveryServiceClient.common_location_path) - parse_common_location_path = staticmethod(DeliveryServiceClient.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: - DeliveryServiceAsyncClient: The constructed client. - """ - return DeliveryServiceClient.from_service_account_info.__func__(DeliveryServiceAsyncClient, 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: - DeliveryServiceAsyncClient: The constructed client. - """ - return DeliveryServiceClient.from_service_account_file.__func__(DeliveryServiceAsyncClient, 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 DeliveryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DeliveryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DeliveryServiceTransport: 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 = DeliveryServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DeliveryServiceTransport, Callable[..., DeliveryServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the delivery 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,DeliveryServiceTransport,Callable[..., DeliveryServiceTransport]]]): - 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 DeliveryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = DeliveryServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_delivery_vehicle(self, - request: Optional[Union[delivery_api.CreateDeliveryVehicleRequest, dict]] = None, - *, - parent: Optional[str] = None, - delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = None, - delivery_vehicle_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Creates and returns a new ``DeliveryVehicle``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_create_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( - parent="parent_value", - delivery_vehicle_id="delivery_vehicle_id_value", - ) - - # Make the request - response = await client.create_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest, dict]]): - The request object. The ``CreateDeliveryVehicle`` request message. - parent (:class:`str`): - Required. Must be in the format - ``providers/{provider}``. The provider must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - delivery_vehicle (:class:`google.maps.fleetengine_delivery_v1.types.DeliveryVehicle`): - Required. The ``DeliveryVehicle`` entity to create. When - creating a new delivery vehicle, you may set the - following optional fields: - - - type - - last_location - - attributes - - Note: The DeliveryVehicle's ``name`` field is ignored. - All other DeliveryVehicle fields must not be set; - otherwise, an error is returned. - - This corresponds to the ``delivery_vehicle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - delivery_vehicle_id (:class:`str`): - Required. The Delivery Vehicle ID must be unique and - subject to the following restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form - C] (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII - characters: '/', ':', '?', ',', or '#'. - - This corresponds to the ``delivery_vehicle_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, delivery_vehicle, delivery_vehicle_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, delivery_api.CreateDeliveryVehicleRequest): - request = delivery_api.CreateDeliveryVehicleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if delivery_vehicle is not None: - request.delivery_vehicle = delivery_vehicle - if delivery_vehicle_id is not None: - request.delivery_vehicle_id = delivery_vehicle_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_delivery_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_delivery_vehicle(self, - request: Optional[Union[delivery_api.GetDeliveryVehicleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Returns the specified ``DeliveryVehicle`` instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_get_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest, dict]]): - The request object. The ``GetDeliveryVehicle`` request message. - name (:class:`str`): - Required. Must be in the format - ``providers/{provider}/deliveryVehicles/{delivery_vehicle}``. - The ``provider`` must be the Google Cloud Project ID. - For example, ``sample-cloud-project``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - 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, delivery_api.GetDeliveryVehicleRequest): - request = delivery_api.GetDeliveryVehicleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_delivery_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_delivery_vehicle(self, - request: Optional[Union[delivery_api.UpdateDeliveryVehicleRequest, dict]] = None, - *, - delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = 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, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Writes updated ``DeliveryVehicle`` data to Fleet Engine, and - assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update - the name of the ``DeliveryVehicle``. You *can* update - ``remaining_vehicle_journey_segments``, but it must contain all - of the ``VehicleJourneySegment``\ s to be persisted on the - ``DeliveryVehicle``. The ``task_id``\ s are retrieved from - ``remaining_vehicle_journey_segments``, and their corresponding - ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have - not yet been assigned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_update_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( - ) - - # Make the request - response = await client.update_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest, dict]]): - The request object. The ``UpdateDeliveryVehicle`` request message. - delivery_vehicle (:class:`google.maps.fleetengine_delivery_v1.types.DeliveryVehicle`): - Required. The ``DeliveryVehicle`` entity update to - apply. Note: You cannot update the name of the - ``DeliveryVehicle``. - - This corresponds to the ``delivery_vehicle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. A field mask that indicates which - ``DeliveryVehicle`` fields to update. Note that the - update_mask must contain at least one field. - - This is a comma-separated list of fully qualified names - of fields. Example: - ``"remaining_vehicle_journey_segments"``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([delivery_vehicle, 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, delivery_api.UpdateDeliveryVehicleRequest): - request = delivery_api.UpdateDeliveryVehicleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if delivery_vehicle is not None: - request.delivery_vehicle = delivery_vehicle - 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_delivery_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.delivery_vehicle.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_tasks(self, - request: Optional[Union[delivery_api.BatchCreateTasksRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_api.BatchCreateTasksResponse: - r"""Creates and returns a batch of new ``Task`` objects. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_batch_create_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - requests = fleetengine_delivery_v1.CreateTaskRequest() - requests.parent = "parent_value" - requests.task_id = "task_id_value" - requests.task.type_ = "UNAVAILABLE" - requests.task.state = "CLOSED" - - request = fleetengine_delivery_v1.BatchCreateTasksRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_tasks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest, dict]]): - The request object. The ``BatchCreateTask`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse: - The BatchCreateTask 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, delivery_api.BatchCreateTasksRequest): - request = delivery_api.BatchCreateTasksRequest(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_create_tasks] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_task(self, - request: Optional[Union[delivery_api.CreateTaskRequest, dict]] = None, - *, - parent: Optional[str] = None, - task: Optional[tasks.Task] = None, - task_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Creates and returns a new ``Task`` object. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_create_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.CreateTaskRequest( - parent="parent_value", - task_id="task_id_value", - task=task, - ) - - # Make the request - response = await client.create_task(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.CreateTaskRequest, dict]]): - The request object. The ``CreateTask`` request message. - parent (:class:`str`): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - task (:class:`google.maps.fleetengine_delivery_v1.types.Task`): - Required. The Task entity to create. When creating a - Task, the following fields are required: - - - ``type`` - - ``state`` (must be set to ``OPEN``) - - ``tracking_id`` (must not be set for ``UNAVAILABLE`` - or ``SCHEDULED_STOP`` tasks, but required for all - other task types) - - ``planned_location`` (optional for ``UNAVAILABLE`` - tasks) - - ``task_duration`` - - Note: The Task's ``name`` field is ignored. All other - Task fields must not be set; otherwise, an error is - returned. - - This corresponds to the ``task`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - task_id (:class:`str`): - Required. The Task ID must be unique, but it should be - not a shipment tracking ID. To store a shipment tracking - ID, use the ``tracking_id`` field. Note that multiple - tasks can have the same ``tracking_id``. Task IDs are - subject to the following restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form - C] (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII - characters: '/', ':', '?', ',', or '#'. - - This corresponds to the ``task_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, task, task_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, delivery_api.CreateTaskRequest): - request = delivery_api.CreateTaskRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if task is not None: - request.task = task - if task_id is not None: - request.task_id = task_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_task] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_task(self, - request: Optional[Union[delivery_api.GetTaskRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Gets information about a ``Task``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_get_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskRequest( - name="name_value", - ) - - # Make the request - response = await client.get_task(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.GetTaskRequest, dict]]): - The request object. The ``GetTask`` request message. - name (:class:`str`): - Required. Must be in the format - ``providers/{provider}/tasks/{task}``. The ``provider`` - must be the Google Cloud Project ID. For example, - ``sample-cloud-project``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - 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, delivery_api.GetTaskRequest): - request = delivery_api.GetTaskRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_task] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_task(self, - request: Optional[Union[delivery_api.UpdateTaskRequest, dict]] = None, - *, - task: Optional[tasks.Task] = 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, str]] = (), - ) -> tasks.Task: - r"""Updates ``Task`` data. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_update_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.UpdateTaskRequest( - task=task, - ) - - # Make the request - response = await client.update_task(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest, dict]]): - The request object. The ``UpdateTask`` request message. - task (:class:`google.maps.fleetengine_delivery_v1.types.Task`): - Required. The Task associated with the update. The - following fields are maintained by Fleet Engine. Do not - update them using ``Task.update``. - - - ``last_location``. - - ``last_location_snappable``. - - ``name``. - - ``remaining_vehicle_journey_segments``. - - ``task_outcome_location_source``. - - Note: You cannot change the value of ``task_outcome`` - once you set it. - - If the Task has been assigned to a delivery vehicle, - then don't set the Task state to CLOSED using - ``Task.update``. Instead, remove the ``VehicleStop`` - that contains the Task from the delivery vehicle, which - automatically sets the Task state to CLOSED. - - This corresponds to the ``task`` 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 field mask that indicates which Task - fields to update. Note: The ``update_mask`` must contain - at least one field. - - This is a comma-separated list of fully qualified names - of fields. Example: - ``"task_outcome,task_outcome_time,task_outcome_location"``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([task, 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, delivery_api.UpdateTaskRequest): - request = delivery_api.UpdateTaskRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if task is not None: - request.task = task - 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_task] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.task.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_tasks(self, - request: Optional[Union[delivery_api.ListTasksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTasksAsyncPager: - r"""Gets all ``Task``\ s that meet the specified filtering criteria. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_list_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListTasksRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tasks(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.ListTasksRequest, dict]]): - The request object. The ``ListTasks`` request message. - parent (:class:`str`): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksAsyncPager: - The ListTasks response that contains the set of Tasks that meet the filter - criteria in the ListTasksRequest. - - 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, delivery_api.ListTasksRequest): - request = delivery_api.ListTasksRequest(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_tasks] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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.ListTasksAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_task_tracking_info(self, - request: Optional[Union[delivery_api.GetTaskTrackingInfoRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> task_tracking_info.TaskTrackingInfo: - r"""Returns the specified ``TaskTrackingInfo`` instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_get_task_tracking_info(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( - name="name_value", - ) - - # Make the request - response = await client.get_task_tracking_info(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest, dict]]): - The request object. The ``GetTaskTrackingInfoRequest`` request message. - name (:class:`str`): - Required. Must be in the format - ``providers/{provider}/taskTrackingInfo/{tracking_id}``. - The ``provider`` must be the Google Cloud Project ID, - and the ``tracking_id`` must be the tracking ID - associated with the task. An example name can be - ``providers/sample-cloud-project/taskTrackingInfo/sample-tracking-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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo: - The TaskTrackingInfo message. The message contains task tracking - information which will be used for display. If a - tracking ID is associated with multiple Tasks, Fleet - Engine uses a heuristic to decide which Task's - TaskTrackingInfo to select. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, delivery_api.GetTaskTrackingInfoRequest): - request = delivery_api.GetTaskTrackingInfoRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_task_tracking_info] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_delivery_vehicles(self, - request: Optional[Union[delivery_api.ListDeliveryVehiclesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDeliveryVehiclesAsyncPager: - r"""Gets all ``DeliveryVehicle``\ s that meet the specified - filtering criteria. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - async def sample_list_delivery_vehicles(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_delivery_vehicles(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest, dict]]): - The request object. The ``ListDeliveryVehicles`` request message. - parent (:class:`str`): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesAsyncPager: - The ListDeliveryVehicles response message. - - 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, delivery_api.ListDeliveryVehiclesRequest): - request = delivery_api.ListDeliveryVehiclesRequest(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_delivery_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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.ListDeliveryVehiclesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "DeliveryServiceAsyncClient": - 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__ = ( - "DeliveryServiceAsyncClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py deleted file mode 100644 index c4eae523cd1f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py +++ /dev/null @@ -1,1924 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.maps.fleetengine_delivery_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 - -from google.maps.fleetengine_delivery_v1.services.delivery_service import pagers -from google.maps.fleetengine_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -from .transports.base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DeliveryServiceGrpcTransport -from .transports.grpc_asyncio import DeliveryServiceGrpcAsyncIOTransport -from .transports.rest import DeliveryServiceRestTransport - - -class DeliveryServiceClientMeta(type): - """Metaclass for the DeliveryService 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[DeliveryServiceTransport]] - _transport_registry["grpc"] = DeliveryServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DeliveryServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DeliveryServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DeliveryServiceTransport]: - """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 DeliveryServiceClient(metaclass=DeliveryServiceClientMeta): - """The Last Mile Delivery service.""" - - @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 = "fleetengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: - DeliveryServiceClient: 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: - DeliveryServiceClient: 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) -> DeliveryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DeliveryServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def delivery_vehicle_path(provider: str,vehicle: str,) -> str: - """Returns a fully-qualified delivery_vehicle string.""" - return "providers/{provider}/deliveryVehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) - - @staticmethod - def parse_delivery_vehicle_path(path: str) -> Dict[str,str]: - """Parses a delivery_vehicle path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/deliveryVehicles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def task_path(provider: str,task: str,) -> str: - """Returns a fully-qualified task string.""" - return "providers/{provider}/tasks/{task}".format(provider=provider, task=task, ) - - @staticmethod - def parse_task_path(path: str) -> Dict[str,str]: - """Parses a task path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/tasks/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def task_tracking_info_path(provider: str,tracking: str,) -> str: - """Returns a fully-qualified task_tracking_info string.""" - return "providers/{provider}/taskTrackingInfo/{tracking}".format(provider=provider, tracking=tracking, ) - - @staticmethod - def parse_task_tracking_info_path(path: str) -> Dict[str,str]: - """Parses a task_tracking_info path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/taskTrackingInfo/(?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 = DeliveryServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = DeliveryServiceClient._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 = DeliveryServiceClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DeliveryServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - DeliveryServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, DeliveryServiceTransport, Callable[..., DeliveryServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the delivery 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,DeliveryServiceTransport,Callable[..., DeliveryServiceTransport]]]): - 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 DeliveryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = DeliveryServiceClient._read_environment_variables() - self._client_cert_source = DeliveryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = DeliveryServiceClient._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 - - 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, DeliveryServiceTransport) - if transport_provided: - # transport is a DeliveryServiceTransport 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(DeliveryServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - DeliveryServiceClient._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[DeliveryServiceTransport], Callable[..., DeliveryServiceTransport]] = ( - DeliveryServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., DeliveryServiceTransport], 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, - ) - - def create_delivery_vehicle(self, - request: Optional[Union[delivery_api.CreateDeliveryVehicleRequest, dict]] = None, - *, - parent: Optional[str] = None, - delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = None, - delivery_vehicle_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Creates and returns a new ``DeliveryVehicle``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_create_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( - parent="parent_value", - delivery_vehicle_id="delivery_vehicle_id_value", - ) - - # Make the request - response = client.create_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest, dict]): - The request object. The ``CreateDeliveryVehicle`` request message. - parent (str): - Required. Must be in the format - ``providers/{provider}``. The provider must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): - Required. The ``DeliveryVehicle`` entity to create. When - creating a new delivery vehicle, you may set the - following optional fields: - - - type - - last_location - - attributes - - Note: The DeliveryVehicle's ``name`` field is ignored. - All other DeliveryVehicle fields must not be set; - otherwise, an error is returned. - - This corresponds to the ``delivery_vehicle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - delivery_vehicle_id (str): - Required. The Delivery Vehicle ID must be unique and - subject to the following restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form - C] (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII - characters: '/', ':', '?', ',', or '#'. - - This corresponds to the ``delivery_vehicle_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, delivery_vehicle, delivery_vehicle_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, delivery_api.CreateDeliveryVehicleRequest): - request = delivery_api.CreateDeliveryVehicleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if delivery_vehicle is not None: - request.delivery_vehicle = delivery_vehicle - if delivery_vehicle_id is not None: - request.delivery_vehicle_id = delivery_vehicle_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_delivery_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_delivery_vehicle(self, - request: Optional[Union[delivery_api.GetDeliveryVehicleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Returns the specified ``DeliveryVehicle`` instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_get_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.get_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest, dict]): - The request object. The ``GetDeliveryVehicle`` request message. - name (str): - Required. Must be in the format - ``providers/{provider}/deliveryVehicles/{delivery_vehicle}``. - The ``provider`` must be the Google Cloud Project ID. - For example, ``sample-cloud-project``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - 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, delivery_api.GetDeliveryVehicleRequest): - request = delivery_api.GetDeliveryVehicleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_delivery_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_delivery_vehicle(self, - request: Optional[Union[delivery_api.UpdateDeliveryVehicleRequest, dict]] = None, - *, - delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = 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, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Writes updated ``DeliveryVehicle`` data to Fleet Engine, and - assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update - the name of the ``DeliveryVehicle``. You *can* update - ``remaining_vehicle_journey_segments``, but it must contain all - of the ``VehicleJourneySegment``\ s to be persisted on the - ``DeliveryVehicle``. The ``task_id``\ s are retrieved from - ``remaining_vehicle_journey_segments``, and their corresponding - ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have - not yet been assigned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_update_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( - ) - - # Make the request - response = client.update_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest, dict]): - The request object. The ``UpdateDeliveryVehicle`` request message. - delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): - Required. The ``DeliveryVehicle`` entity update to - apply. Note: You cannot update the name of the - ``DeliveryVehicle``. - - This corresponds to the ``delivery_vehicle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A field mask that indicates which - ``DeliveryVehicle`` fields to update. Note that the - update_mask must contain at least one field. - - This is a comma-separated list of fully qualified names - of fields. Example: - ``"remaining_vehicle_journey_segments"``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([delivery_vehicle, 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, delivery_api.UpdateDeliveryVehicleRequest): - request = delivery_api.UpdateDeliveryVehicleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if delivery_vehicle is not None: - request.delivery_vehicle = delivery_vehicle - 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_delivery_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.delivery_vehicle.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_tasks(self, - request: Optional[Union[delivery_api.BatchCreateTasksRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_api.BatchCreateTasksResponse: - r"""Creates and returns a batch of new ``Task`` objects. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_batch_create_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - requests = fleetengine_delivery_v1.CreateTaskRequest() - requests.parent = "parent_value" - requests.task_id = "task_id_value" - requests.task.type_ = "UNAVAILABLE" - requests.task.state = "CLOSED" - - request = fleetengine_delivery_v1.BatchCreateTasksRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_tasks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest, dict]): - The request object. The ``BatchCreateTask`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse: - The BatchCreateTask 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, delivery_api.BatchCreateTasksRequest): - request = delivery_api.BatchCreateTasksRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_tasks] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_task(self, - request: Optional[Union[delivery_api.CreateTaskRequest, dict]] = None, - *, - parent: Optional[str] = None, - task: Optional[tasks.Task] = None, - task_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Creates and returns a new ``Task`` object. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_create_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.CreateTaskRequest( - parent="parent_value", - task_id="task_id_value", - task=task, - ) - - # Make the request - response = client.create_task(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.CreateTaskRequest, dict]): - The request object. The ``CreateTask`` request message. - parent (str): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - task (google.maps.fleetengine_delivery_v1.types.Task): - Required. The Task entity to create. When creating a - Task, the following fields are required: - - - ``type`` - - ``state`` (must be set to ``OPEN``) - - ``tracking_id`` (must not be set for ``UNAVAILABLE`` - or ``SCHEDULED_STOP`` tasks, but required for all - other task types) - - ``planned_location`` (optional for ``UNAVAILABLE`` - tasks) - - ``task_duration`` - - Note: The Task's ``name`` field is ignored. All other - Task fields must not be set; otherwise, an error is - returned. - - This corresponds to the ``task`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - task_id (str): - Required. The Task ID must be unique, but it should be - not a shipment tracking ID. To store a shipment tracking - ID, use the ``tracking_id`` field. Note that multiple - tasks can have the same ``tracking_id``. Task IDs are - subject to the following restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form - C] (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII - characters: '/', ':', '?', ',', or '#'. - - This corresponds to the ``task_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, task, task_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, delivery_api.CreateTaskRequest): - request = delivery_api.CreateTaskRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if task is not None: - request.task = task - if task_id is not None: - request.task_id = task_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_task] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_task(self, - request: Optional[Union[delivery_api.GetTaskRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Gets information about a ``Task``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_get_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskRequest( - name="name_value", - ) - - # Make the request - response = client.get_task(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.GetTaskRequest, dict]): - The request object. The ``GetTask`` request message. - name (str): - Required. Must be in the format - ``providers/{provider}/tasks/{task}``. The ``provider`` - must be the Google Cloud Project ID. For example, - ``sample-cloud-project``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - 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, delivery_api.GetTaskRequest): - request = delivery_api.GetTaskRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_task] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_task(self, - request: Optional[Union[delivery_api.UpdateTaskRequest, dict]] = None, - *, - task: Optional[tasks.Task] = 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, str]] = (), - ) -> tasks.Task: - r"""Updates ``Task`` data. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_update_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.UpdateTaskRequest( - task=task, - ) - - # Make the request - response = client.update_task(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest, dict]): - The request object. The ``UpdateTask`` request message. - task (google.maps.fleetengine_delivery_v1.types.Task): - Required. The Task associated with the update. The - following fields are maintained by Fleet Engine. Do not - update them using ``Task.update``. - - - ``last_location``. - - ``last_location_snappable``. - - ``name``. - - ``remaining_vehicle_journey_segments``. - - ``task_outcome_location_source``. - - Note: You cannot change the value of ``task_outcome`` - once you set it. - - If the Task has been assigned to a delivery vehicle, - then don't set the Task state to CLOSED using - ``Task.update``. Instead, remove the ``VehicleStop`` - that contains the Task from the delivery vehicle, which - automatically sets the Task state to CLOSED. - - This corresponds to the ``task`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The field mask that indicates which Task - fields to update. Note: The ``update_mask`` must contain - at least one field. - - This is a comma-separated list of fully qualified names - of fields. Example: - ``"task_outcome,task_outcome_time,task_outcome_location"``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([task, 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, delivery_api.UpdateTaskRequest): - request = delivery_api.UpdateTaskRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if task is not None: - request.task = task - 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_task] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.task.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_tasks(self, - request: Optional[Union[delivery_api.ListTasksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTasksPager: - r"""Gets all ``Task``\ s that meet the specified filtering criteria. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_list_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListTasksRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tasks(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.ListTasksRequest, dict]): - The request object. The ``ListTasks`` request message. - parent (str): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksPager: - The ListTasks response that contains the set of Tasks that meet the filter - criteria in the ListTasksRequest. - - 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, delivery_api.ListTasksRequest): - request = delivery_api.ListTasksRequest(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_tasks] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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.ListTasksPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_task_tracking_info(self, - request: Optional[Union[delivery_api.GetTaskTrackingInfoRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> task_tracking_info.TaskTrackingInfo: - r"""Returns the specified ``TaskTrackingInfo`` instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_get_task_tracking_info(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( - name="name_value", - ) - - # Make the request - response = client.get_task_tracking_info(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest, dict]): - The request object. The ``GetTaskTrackingInfoRequest`` request message. - name (str): - Required. Must be in the format - ``providers/{provider}/taskTrackingInfo/{tracking_id}``. - The ``provider`` must be the Google Cloud Project ID, - and the ``tracking_id`` must be the tracking ID - associated with the task. An example name can be - ``providers/sample-cloud-project/taskTrackingInfo/sample-tracking-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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo: - The TaskTrackingInfo message. The message contains task tracking - information which will be used for display. If a - tracking ID is associated with multiple Tasks, Fleet - Engine uses a heuristic to decide which Task's - TaskTrackingInfo to select. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, delivery_api.GetTaskTrackingInfoRequest): - request = delivery_api.GetTaskTrackingInfoRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_task_tracking_info] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_delivery_vehicles(self, - request: Optional[Union[delivery_api.ListDeliveryVehiclesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDeliveryVehiclesPager: - r"""Gets all ``DeliveryVehicle``\ s that meet the specified - filtering criteria. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_delivery_v1 - - def sample_list_delivery_vehicles(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_delivery_vehicles(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest, dict]): - The request object. The ``ListDeliveryVehicles`` request message. - parent (str): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesPager: - The ListDeliveryVehicles response message. - - 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, delivery_api.ListDeliveryVehiclesRequest): - request = delivery_api.ListDeliveryVehiclesRequest(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_delivery_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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.ListDeliveryVehiclesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DeliveryServiceClient": - 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__ = ( - "DeliveryServiceClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py deleted file mode 100644 index 71e6a9f33252..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py +++ /dev/null @@ -1,299 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import tasks - - -class ListTasksPager: - """A pager for iterating through ``list_tasks`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tasks`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTasks`` requests and continue to iterate - through the ``tasks`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., delivery_api.ListTasksResponse], - request: delivery_api.ListTasksRequest, - response: delivery_api.ListTasksResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_delivery_v1.types.ListTasksRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.ListTasksResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = delivery_api.ListTasksRequest(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[delivery_api.ListTasksResponse]: - 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[tasks.Task]: - for page in self.pages: - yield from page.tasks - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTasksAsyncPager: - """A pager for iterating through ``list_tasks`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tasks`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTasks`` requests and continue to iterate - through the ``tasks`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` - attributes are available on the 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[delivery_api.ListTasksResponse]], - request: delivery_api.ListTasksRequest, - response: delivery_api.ListTasksResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_delivery_v1.types.ListTasksRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.ListTasksResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = delivery_api.ListTasksRequest(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[delivery_api.ListTasksResponse]: - 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[tasks.Task]: - async def async_generator(): - async for page in self.pages: - for response in page.tasks: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDeliveryVehiclesPager: - """A pager for iterating through ``list_delivery_vehicles`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``delivery_vehicles`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDeliveryVehicles`` requests and continue to iterate - through the ``delivery_vehicles`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., delivery_api.ListDeliveryVehiclesResponse], - request: delivery_api.ListDeliveryVehiclesRequest, - response: delivery_api.ListDeliveryVehiclesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = delivery_api.ListDeliveryVehiclesRequest(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[delivery_api.ListDeliveryVehiclesResponse]: - 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[delivery_vehicles.DeliveryVehicle]: - for page in self.pages: - yield from page.delivery_vehicles - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDeliveryVehiclesAsyncPager: - """A pager for iterating through ``list_delivery_vehicles`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``delivery_vehicles`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDeliveryVehicles`` requests and continue to iterate - through the ``delivery_vehicles`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` - attributes are available on the 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[delivery_api.ListDeliveryVehiclesResponse]], - request: delivery_api.ListDeliveryVehiclesRequest, - response: delivery_api.ListDeliveryVehiclesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = delivery_api.ListDeliveryVehiclesRequest(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[delivery_api.ListDeliveryVehiclesResponse]: - 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[delivery_vehicles.DeliveryVehicle]: - async def async_generator(): - async for page in self.pages: - for response in page.delivery_vehicles: - 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-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/README.rst deleted file mode 100644 index db6050755ee5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`DeliveryServiceTransport` is the ABC for all transports. -- public child `DeliveryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `DeliveryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseDeliveryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `DeliveryServiceRestTransport` 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-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py deleted file mode 100644 index bdf0ae0905a7..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_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 DeliveryServiceTransport -from .grpc import DeliveryServiceGrpcTransport -from .grpc_asyncio import DeliveryServiceGrpcAsyncIOTransport -from .rest import DeliveryServiceRestTransport -from .rest import DeliveryServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DeliveryServiceTransport]] -_transport_registry['grpc'] = DeliveryServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DeliveryServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DeliveryServiceRestTransport - -__all__ = ( - 'DeliveryServiceTransport', - 'DeliveryServiceGrpcTransport', - 'DeliveryServiceGrpcAsyncIOTransport', - 'DeliveryServiceRestTransport', - 'DeliveryServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py deleted file mode 100644 index fba0b4384257..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py +++ /dev/null @@ -1,373 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.fleetengine_delivery_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.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DeliveryServiceTransport(abc.ABC): - """Abstract transport class for DeliveryService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_delivery_vehicle: gapic_v1.method.wrap_method( - self.create_delivery_vehicle, - 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_delivery_vehicle: gapic_v1.method.wrap_method( - self.get_delivery_vehicle, - 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.update_delivery_vehicle: gapic_v1.method.wrap_method( - self.update_delivery_vehicle, - 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.batch_create_tasks: gapic_v1.method.wrap_method( - self.batch_create_tasks, - 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.create_task: gapic_v1.method.wrap_method( - self.create_task, - 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_task: gapic_v1.method.wrap_method( - self.get_task, - 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.update_task: gapic_v1.method.wrap_method( - self.update_task, - 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_tasks: gapic_v1.method.wrap_method( - self.list_tasks, - 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_task_tracking_info: gapic_v1.method.wrap_method( - self.get_task_tracking_info, - 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_delivery_vehicles: gapic_v1.method.wrap_method( - self.list_delivery_vehicles, - 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 create_delivery_vehicle(self) -> Callable[ - [delivery_api.CreateDeliveryVehicleRequest], - Union[ - delivery_vehicles.DeliveryVehicle, - Awaitable[delivery_vehicles.DeliveryVehicle] - ]]: - raise NotImplementedError() - - @property - def get_delivery_vehicle(self) -> Callable[ - [delivery_api.GetDeliveryVehicleRequest], - Union[ - delivery_vehicles.DeliveryVehicle, - Awaitable[delivery_vehicles.DeliveryVehicle] - ]]: - raise NotImplementedError() - - @property - def update_delivery_vehicle(self) -> Callable[ - [delivery_api.UpdateDeliveryVehicleRequest], - Union[ - delivery_vehicles.DeliveryVehicle, - Awaitable[delivery_vehicles.DeliveryVehicle] - ]]: - raise NotImplementedError() - - @property - def batch_create_tasks(self) -> Callable[ - [delivery_api.BatchCreateTasksRequest], - Union[ - delivery_api.BatchCreateTasksResponse, - Awaitable[delivery_api.BatchCreateTasksResponse] - ]]: - raise NotImplementedError() - - @property - def create_task(self) -> Callable[ - [delivery_api.CreateTaskRequest], - Union[ - tasks.Task, - Awaitable[tasks.Task] - ]]: - raise NotImplementedError() - - @property - def get_task(self) -> Callable[ - [delivery_api.GetTaskRequest], - Union[ - tasks.Task, - Awaitable[tasks.Task] - ]]: - raise NotImplementedError() - - @property - def update_task(self) -> Callable[ - [delivery_api.UpdateTaskRequest], - Union[ - tasks.Task, - Awaitable[tasks.Task] - ]]: - raise NotImplementedError() - - @property - def list_tasks(self) -> Callable[ - [delivery_api.ListTasksRequest], - Union[ - delivery_api.ListTasksResponse, - Awaitable[delivery_api.ListTasksResponse] - ]]: - raise NotImplementedError() - - @property - def get_task_tracking_info(self) -> Callable[ - [delivery_api.GetTaskTrackingInfoRequest], - Union[ - task_tracking_info.TaskTrackingInfo, - Awaitable[task_tracking_info.TaskTrackingInfo] - ]]: - raise NotImplementedError() - - @property - def list_delivery_vehicles(self) -> Callable[ - [delivery_api.ListDeliveryVehiclesRequest], - Union[ - delivery_api.ListDeliveryVehiclesResponse, - Awaitable[delivery_api.ListDeliveryVehiclesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DeliveryServiceTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py deleted file mode 100644 index 03a7d345d054..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py +++ /dev/null @@ -1,516 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -from .base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO - - -class DeliveryServiceGrpcTransport(DeliveryServiceTransport): - """gRPC backend transport for DeliveryService. - - The Last Mile Delivery service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'fleetengine.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: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'fleetengine.googleapis.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_delivery_vehicle(self) -> Callable[ - [delivery_api.CreateDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - r"""Return a callable for the create delivery vehicle method over gRPC. - - Creates and returns a new ``DeliveryVehicle``. - - Returns: - Callable[[~.CreateDeliveryVehicleRequest], - ~.DeliveryVehicle]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: - self._stubs['create_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/CreateDeliveryVehicle', - request_serializer=delivery_api.CreateDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['create_delivery_vehicle'] - - @property - def get_delivery_vehicle(self) -> Callable[ - [delivery_api.GetDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - r"""Return a callable for the get delivery vehicle method over gRPC. - - Returns the specified ``DeliveryVehicle`` instance. - - Returns: - Callable[[~.GetDeliveryVehicleRequest], - ~.DeliveryVehicle]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: - self._stubs['get_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetDeliveryVehicle', - request_serializer=delivery_api.GetDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['get_delivery_vehicle'] - - @property - def update_delivery_vehicle(self) -> Callable[ - [delivery_api.UpdateDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - r"""Return a callable for the update delivery vehicle method over gRPC. - - Writes updated ``DeliveryVehicle`` data to Fleet Engine, and - assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update - the name of the ``DeliveryVehicle``. You *can* update - ``remaining_vehicle_journey_segments``, but it must contain all - of the ``VehicleJourneySegment``\ s to be persisted on the - ``DeliveryVehicle``. The ``task_id``\ s are retrieved from - ``remaining_vehicle_journey_segments``, and their corresponding - ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have - not yet been assigned. - - Returns: - Callable[[~.UpdateDeliveryVehicleRequest], - ~.DeliveryVehicle]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: - self._stubs['update_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/UpdateDeliveryVehicle', - request_serializer=delivery_api.UpdateDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['update_delivery_vehicle'] - - @property - def batch_create_tasks(self) -> Callable[ - [delivery_api.BatchCreateTasksRequest], - delivery_api.BatchCreateTasksResponse]: - r"""Return a callable for the batch create tasks method over gRPC. - - Creates and returns a batch of new ``Task`` objects. - - Returns: - Callable[[~.BatchCreateTasksRequest], - ~.BatchCreateTasksResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tasks' not in self._stubs: - self._stubs['batch_create_tasks'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/BatchCreateTasks', - request_serializer=delivery_api.BatchCreateTasksRequest.serialize, - response_deserializer=delivery_api.BatchCreateTasksResponse.deserialize, - ) - return self._stubs['batch_create_tasks'] - - @property - def create_task(self) -> Callable[ - [delivery_api.CreateTaskRequest], - tasks.Task]: - r"""Return a callable for the create task method over gRPC. - - Creates and returns a new ``Task`` object. - - Returns: - Callable[[~.CreateTaskRequest], - ~.Task]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_task' not in self._stubs: - self._stubs['create_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/CreateTask', - request_serializer=delivery_api.CreateTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['create_task'] - - @property - def get_task(self) -> Callable[ - [delivery_api.GetTaskRequest], - tasks.Task]: - r"""Return a callable for the get task method over gRPC. - - Gets information about a ``Task``. - - Returns: - Callable[[~.GetTaskRequest], - ~.Task]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_task' not in self._stubs: - self._stubs['get_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetTask', - request_serializer=delivery_api.GetTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['get_task'] - - @property - def update_task(self) -> Callable[ - [delivery_api.UpdateTaskRequest], - tasks.Task]: - r"""Return a callable for the update task method over gRPC. - - Updates ``Task`` data. - - Returns: - Callable[[~.UpdateTaskRequest], - ~.Task]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_task' not in self._stubs: - self._stubs['update_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/UpdateTask', - request_serializer=delivery_api.UpdateTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['update_task'] - - @property - def list_tasks(self) -> Callable[ - [delivery_api.ListTasksRequest], - delivery_api.ListTasksResponse]: - r"""Return a callable for the list tasks method over gRPC. - - Gets all ``Task``\ s that meet the specified filtering criteria. - - Returns: - Callable[[~.ListTasksRequest], - ~.ListTasksResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tasks' not in self._stubs: - self._stubs['list_tasks'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/ListTasks', - request_serializer=delivery_api.ListTasksRequest.serialize, - response_deserializer=delivery_api.ListTasksResponse.deserialize, - ) - return self._stubs['list_tasks'] - - @property - def get_task_tracking_info(self) -> Callable[ - [delivery_api.GetTaskTrackingInfoRequest], - task_tracking_info.TaskTrackingInfo]: - r"""Return a callable for the get task tracking info method over gRPC. - - Returns the specified ``TaskTrackingInfo`` instance. - - Returns: - Callable[[~.GetTaskTrackingInfoRequest], - ~.TaskTrackingInfo]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_task_tracking_info' not in self._stubs: - self._stubs['get_task_tracking_info'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetTaskTrackingInfo', - request_serializer=delivery_api.GetTaskTrackingInfoRequest.serialize, - response_deserializer=task_tracking_info.TaskTrackingInfo.deserialize, - ) - return self._stubs['get_task_tracking_info'] - - @property - def list_delivery_vehicles(self) -> Callable[ - [delivery_api.ListDeliveryVehiclesRequest], - delivery_api.ListDeliveryVehiclesResponse]: - r"""Return a callable for the list delivery vehicles method over gRPC. - - Gets all ``DeliveryVehicle``\ s that meet the specified - filtering criteria. - - Returns: - Callable[[~.ListDeliveryVehiclesRequest], - ~.ListDeliveryVehiclesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_delivery_vehicles' not in self._stubs: - self._stubs['list_delivery_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/ListDeliveryVehicles', - request_serializer=delivery_api.ListDeliveryVehiclesRequest.serialize, - response_deserializer=delivery_api.ListDeliveryVehiclesResponse.deserialize, - ) - return self._stubs['list_delivery_vehicles'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DeliveryServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py deleted file mode 100644 index e39deda49df2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,672 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -from .base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DeliveryServiceGrpcTransport - - -class DeliveryServiceGrpcAsyncIOTransport(DeliveryServiceTransport): - """gRPC AsyncIO backend transport for DeliveryService. - - The Last Mile Delivery service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'fleetengine.googleapis.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 = 'fleetengine.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: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_delivery_vehicle(self) -> Callable[ - [delivery_api.CreateDeliveryVehicleRequest], - Awaitable[delivery_vehicles.DeliveryVehicle]]: - r"""Return a callable for the create delivery vehicle method over gRPC. - - Creates and returns a new ``DeliveryVehicle``. - - Returns: - Callable[[~.CreateDeliveryVehicleRequest], - Awaitable[~.DeliveryVehicle]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: - self._stubs['create_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/CreateDeliveryVehicle', - request_serializer=delivery_api.CreateDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['create_delivery_vehicle'] - - @property - def get_delivery_vehicle(self) -> Callable[ - [delivery_api.GetDeliveryVehicleRequest], - Awaitable[delivery_vehicles.DeliveryVehicle]]: - r"""Return a callable for the get delivery vehicle method over gRPC. - - Returns the specified ``DeliveryVehicle`` instance. - - Returns: - Callable[[~.GetDeliveryVehicleRequest], - Awaitable[~.DeliveryVehicle]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: - self._stubs['get_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetDeliveryVehicle', - request_serializer=delivery_api.GetDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['get_delivery_vehicle'] - - @property - def update_delivery_vehicle(self) -> Callable[ - [delivery_api.UpdateDeliveryVehicleRequest], - Awaitable[delivery_vehicles.DeliveryVehicle]]: - r"""Return a callable for the update delivery vehicle method over gRPC. - - Writes updated ``DeliveryVehicle`` data to Fleet Engine, and - assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update - the name of the ``DeliveryVehicle``. You *can* update - ``remaining_vehicle_journey_segments``, but it must contain all - of the ``VehicleJourneySegment``\ s to be persisted on the - ``DeliveryVehicle``. The ``task_id``\ s are retrieved from - ``remaining_vehicle_journey_segments``, and their corresponding - ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have - not yet been assigned. - - Returns: - Callable[[~.UpdateDeliveryVehicleRequest], - Awaitable[~.DeliveryVehicle]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_delivery_vehicle' not in self._stubs: - self._stubs['update_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/UpdateDeliveryVehicle', - request_serializer=delivery_api.UpdateDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['update_delivery_vehicle'] - - @property - def batch_create_tasks(self) -> Callable[ - [delivery_api.BatchCreateTasksRequest], - Awaitable[delivery_api.BatchCreateTasksResponse]]: - r"""Return a callable for the batch create tasks method over gRPC. - - Creates and returns a batch of new ``Task`` objects. - - Returns: - Callable[[~.BatchCreateTasksRequest], - Awaitable[~.BatchCreateTasksResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tasks' not in self._stubs: - self._stubs['batch_create_tasks'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/BatchCreateTasks', - request_serializer=delivery_api.BatchCreateTasksRequest.serialize, - response_deserializer=delivery_api.BatchCreateTasksResponse.deserialize, - ) - return self._stubs['batch_create_tasks'] - - @property - def create_task(self) -> Callable[ - [delivery_api.CreateTaskRequest], - Awaitable[tasks.Task]]: - r"""Return a callable for the create task method over gRPC. - - Creates and returns a new ``Task`` object. - - Returns: - Callable[[~.CreateTaskRequest], - Awaitable[~.Task]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_task' not in self._stubs: - self._stubs['create_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/CreateTask', - request_serializer=delivery_api.CreateTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['create_task'] - - @property - def get_task(self) -> Callable[ - [delivery_api.GetTaskRequest], - Awaitable[tasks.Task]]: - r"""Return a callable for the get task method over gRPC. - - Gets information about a ``Task``. - - Returns: - Callable[[~.GetTaskRequest], - Awaitable[~.Task]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_task' not in self._stubs: - self._stubs['get_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetTask', - request_serializer=delivery_api.GetTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['get_task'] - - @property - def update_task(self) -> Callable[ - [delivery_api.UpdateTaskRequest], - Awaitable[tasks.Task]]: - r"""Return a callable for the update task method over gRPC. - - Updates ``Task`` data. - - Returns: - Callable[[~.UpdateTaskRequest], - Awaitable[~.Task]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_task' not in self._stubs: - self._stubs['update_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/UpdateTask', - request_serializer=delivery_api.UpdateTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['update_task'] - - @property - def list_tasks(self) -> Callable[ - [delivery_api.ListTasksRequest], - Awaitable[delivery_api.ListTasksResponse]]: - r"""Return a callable for the list tasks method over gRPC. - - Gets all ``Task``\ s that meet the specified filtering criteria. - - Returns: - Callable[[~.ListTasksRequest], - Awaitable[~.ListTasksResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tasks' not in self._stubs: - self._stubs['list_tasks'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/ListTasks', - request_serializer=delivery_api.ListTasksRequest.serialize, - response_deserializer=delivery_api.ListTasksResponse.deserialize, - ) - return self._stubs['list_tasks'] - - @property - def get_task_tracking_info(self) -> Callable[ - [delivery_api.GetTaskTrackingInfoRequest], - Awaitable[task_tracking_info.TaskTrackingInfo]]: - r"""Return a callable for the get task tracking info method over gRPC. - - Returns the specified ``TaskTrackingInfo`` instance. - - Returns: - Callable[[~.GetTaskTrackingInfoRequest], - Awaitable[~.TaskTrackingInfo]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_task_tracking_info' not in self._stubs: - self._stubs['get_task_tracking_info'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetTaskTrackingInfo', - request_serializer=delivery_api.GetTaskTrackingInfoRequest.serialize, - response_deserializer=task_tracking_info.TaskTrackingInfo.deserialize, - ) - return self._stubs['get_task_tracking_info'] - - @property - def list_delivery_vehicles(self) -> Callable[ - [delivery_api.ListDeliveryVehiclesRequest], - Awaitable[delivery_api.ListDeliveryVehiclesResponse]]: - r"""Return a callable for the list delivery vehicles method over gRPC. - - Gets all ``DeliveryVehicle``\ s that meet the specified - filtering criteria. - - Returns: - Callable[[~.ListDeliveryVehiclesRequest], - Awaitable[~.ListDeliveryVehiclesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_delivery_vehicles' not in self._stubs: - self._stubs['list_delivery_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/ListDeliveryVehicles', - request_serializer=delivery_api.ListDeliveryVehiclesRequest.serialize, - response_deserializer=delivery_api.ListDeliveryVehiclesResponse.deserialize, - ) - return self._stubs['list_delivery_vehicles'] - - 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_delivery_vehicle: self._wrap_method( - self.create_delivery_vehicle, - 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_delivery_vehicle: self._wrap_method( - self.get_delivery_vehicle, - 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.update_delivery_vehicle: self._wrap_method( - self.update_delivery_vehicle, - 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.batch_create_tasks: self._wrap_method( - self.batch_create_tasks, - 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.create_task: self._wrap_method( - self.create_task, - 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_task: self._wrap_method( - self.get_task, - 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.update_task: self._wrap_method( - self.update_task, - 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_tasks: self._wrap_method( - self.list_tasks, - 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_task_tracking_info: self._wrap_method( - self.get_task_tracking_info, - 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_delivery_vehicles: self._wrap_method( - self.list_delivery_vehicles, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'DeliveryServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py deleted file mode 100644 index 941973102e68..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py +++ /dev/null @@ -1,1318 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks - - -from .rest_base import _BaseDeliveryServiceRestTransport -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 - - -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 DeliveryServiceRestInterceptor: - """Interceptor for DeliveryService. - - 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 DeliveryServiceRestTransport. - - .. code-block:: python - class MyCustomDeliveryServiceInterceptor(DeliveryServiceRestInterceptor): - def pre_batch_create_tasks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_tasks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_delivery_vehicle(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_delivery_vehicle(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_task(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_task(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_delivery_vehicle(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_delivery_vehicle(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_task(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_task(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_task_tracking_info(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_task_tracking_info(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_delivery_vehicles(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_delivery_vehicles(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_tasks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_tasks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_delivery_vehicle(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_delivery_vehicle(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_task(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_task(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DeliveryServiceRestTransport(interceptor=MyCustomDeliveryServiceInterceptor()) - client = DeliveryServiceClient(transport=transport) - - - """ - def pre_batch_create_tasks(self, request: delivery_api.BatchCreateTasksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.BatchCreateTasksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_create_tasks - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_batch_create_tasks(self, response: delivery_api.BatchCreateTasksResponse) -> delivery_api.BatchCreateTasksResponse: - """Post-rpc interceptor for batch_create_tasks - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - def pre_create_delivery_vehicle(self, request: delivery_api.CreateDeliveryVehicleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.CreateDeliveryVehicleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_delivery_vehicle - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_create_delivery_vehicle(self, response: delivery_vehicles.DeliveryVehicle) -> delivery_vehicles.DeliveryVehicle: - """Post-rpc interceptor for create_delivery_vehicle - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - def pre_create_task(self, request: delivery_api.CreateTaskRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.CreateTaskRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_task - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_create_task(self, response: tasks.Task) -> tasks.Task: - """Post-rpc interceptor for create_task - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - def pre_get_delivery_vehicle(self, request: delivery_api.GetDeliveryVehicleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.GetDeliveryVehicleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_delivery_vehicle - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_get_delivery_vehicle(self, response: delivery_vehicles.DeliveryVehicle) -> delivery_vehicles.DeliveryVehicle: - """Post-rpc interceptor for get_delivery_vehicle - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - def pre_get_task(self, request: delivery_api.GetTaskRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.GetTaskRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_task - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_get_task(self, response: tasks.Task) -> tasks.Task: - """Post-rpc interceptor for get_task - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - def pre_get_task_tracking_info(self, request: delivery_api.GetTaskTrackingInfoRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.GetTaskTrackingInfoRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_task_tracking_info - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_get_task_tracking_info(self, response: task_tracking_info.TaskTrackingInfo) -> task_tracking_info.TaskTrackingInfo: - """Post-rpc interceptor for get_task_tracking_info - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - def pre_list_delivery_vehicles(self, request: delivery_api.ListDeliveryVehiclesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.ListDeliveryVehiclesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_delivery_vehicles - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_list_delivery_vehicles(self, response: delivery_api.ListDeliveryVehiclesResponse) -> delivery_api.ListDeliveryVehiclesResponse: - """Post-rpc interceptor for list_delivery_vehicles - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - def pre_list_tasks(self, request: delivery_api.ListTasksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.ListTasksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_tasks - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_list_tasks(self, response: delivery_api.ListTasksResponse) -> delivery_api.ListTasksResponse: - """Post-rpc interceptor for list_tasks - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - def pre_update_delivery_vehicle(self, request: delivery_api.UpdateDeliveryVehicleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.UpdateDeliveryVehicleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_delivery_vehicle - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_update_delivery_vehicle(self, response: delivery_vehicles.DeliveryVehicle) -> delivery_vehicles.DeliveryVehicle: - """Post-rpc interceptor for update_delivery_vehicle - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - def pre_update_task(self, request: delivery_api.UpdateTaskRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.UpdateTaskRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_task - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_update_task(self, response: tasks.Task) -> tasks.Task: - """Post-rpc interceptor for update_task - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DeliveryServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DeliveryServiceRestInterceptor - - -class DeliveryServiceRestTransport(_BaseDeliveryServiceRestTransport): - """REST backend synchronous transport for DeliveryService. - - The Last Mile Delivery service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'fleetengine.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[DeliveryServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 DeliveryServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _BatchCreateTasks(_BaseDeliveryServiceRestTransport._BaseBatchCreateTasks, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.BatchCreateTasks") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: delivery_api.BatchCreateTasksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_api.BatchCreateTasksResponse: - r"""Call the batch create tasks method over HTTP. - - Args: - request (~.delivery_api.BatchCreateTasksRequest): - The request object. The ``BatchCreateTask`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.delivery_api.BatchCreateTasksResponse: - The ``BatchCreateTask`` response message. - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_http_options() - request, metadata = self._interceptor.pre_batch_create_tasks(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_transcoded_request(http_options, request) - - body = _BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._BatchCreateTasks._get_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 = delivery_api.BatchCreateTasksResponse() - pb_resp = delivery_api.BatchCreateTasksResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_tasks(resp) - return resp - - class _CreateDeliveryVehicle(_BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.CreateDeliveryVehicle") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: delivery_api.CreateDeliveryVehicleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Call the create delivery vehicle method over HTTP. - - Args: - request (~.delivery_api.CreateDeliveryVehicleRequest): - The request object. The ``CreateDeliveryVehicle`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.delivery_vehicles.DeliveryVehicle: - The ``DeliveryVehicle`` message. A delivery vehicle - transports shipments from a depot to a delivery - location, and from a pickup location to the depot. In - some cases, delivery vehicles also transport shipments - directly from the pickup location to the delivery - location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``DeliveryVehicle.current_route_segment`` field in the - gRPC API and the ``DeliveryVehicle.currentRouteSegment`` - field in the REST API refer to the same field. - - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_http_options() - request, metadata = self._interceptor.pre_create_delivery_vehicle(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_transcoded_request(http_options, request) - - body = _BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._CreateDeliveryVehicle._get_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 = delivery_vehicles.DeliveryVehicle() - pb_resp = delivery_vehicles.DeliveryVehicle.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_delivery_vehicle(resp) - return resp - - class _CreateTask(_BaseDeliveryServiceRestTransport._BaseCreateTask, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.CreateTask") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: delivery_api.CreateTaskRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tasks.Task: - r"""Call the create task method over HTTP. - - Args: - request (~.delivery_api.CreateTaskRequest): - The request object. The ``CreateTask`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tasks.Task: - A Task in the Delivery API represents a single action to - track. In general, there is a distinction between - shipment-related Tasks and break Tasks. A shipment can - have multiple Tasks associated with it. For example, - there could be one Task for the pickup, and one for the - drop-off or transfer. Also, different Tasks for a given - shipment can be handled by different vehicles. For - example, one vehicle could handle the pickup, driving - the shipment to the hub, while another vehicle drives - the same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``Task.journey_sharing_info`` field in the gRPC API and - the ``Task.journeySharingInfo`` field in the REST API - refer to the same field. - - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseCreateTask._get_http_options() - request, metadata = self._interceptor.pre_create_task(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseCreateTask._get_transcoded_request(http_options, request) - - body = _BaseDeliveryServiceRestTransport._BaseCreateTask._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseCreateTask._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._CreateTask._get_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 = tasks.Task() - pb_resp = tasks.Task.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_task(resp) - return resp - - class _GetDeliveryVehicle(_BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.GetDeliveryVehicle") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: delivery_api.GetDeliveryVehicleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Call the get delivery vehicle method over HTTP. - - Args: - request (~.delivery_api.GetDeliveryVehicleRequest): - The request object. The ``GetDeliveryVehicle`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.delivery_vehicles.DeliveryVehicle: - The ``DeliveryVehicle`` message. A delivery vehicle - transports shipments from a depot to a delivery - location, and from a pickup location to the depot. In - some cases, delivery vehicles also transport shipments - directly from the pickup location to the delivery - location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``DeliveryVehicle.current_route_segment`` field in the - gRPC API and the ``DeliveryVehicle.currentRouteSegment`` - field in the REST API refer to the same field. - - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle._get_http_options() - request, metadata = self._interceptor.pre_get_delivery_vehicle(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._GetDeliveryVehicle._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = delivery_vehicles.DeliveryVehicle() - pb_resp = delivery_vehicles.DeliveryVehicle.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_delivery_vehicle(resp) - return resp - - class _GetTask(_BaseDeliveryServiceRestTransport._BaseGetTask, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.GetTask") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: delivery_api.GetTaskRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tasks.Task: - r"""Call the get task method over HTTP. - - Args: - request (~.delivery_api.GetTaskRequest): - The request object. The ``GetTask`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tasks.Task: - A Task in the Delivery API represents a single action to - track. In general, there is a distinction between - shipment-related Tasks and break Tasks. A shipment can - have multiple Tasks associated with it. For example, - there could be one Task for the pickup, and one for the - drop-off or transfer. Also, different Tasks for a given - shipment can be handled by different vehicles. For - example, one vehicle could handle the pickup, driving - the shipment to the hub, while another vehicle drives - the same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``Task.journey_sharing_info`` field in the gRPC API and - the ``Task.journeySharingInfo`` field in the REST API - refer to the same field. - - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseGetTask._get_http_options() - request, metadata = self._interceptor.pre_get_task(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseGetTask._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseGetTask._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._GetTask._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tasks.Task() - pb_resp = tasks.Task.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_task(resp) - return resp - - class _GetTaskTrackingInfo(_BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.GetTaskTrackingInfo") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: delivery_api.GetTaskTrackingInfoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> task_tracking_info.TaskTrackingInfo: - r"""Call the get task tracking info method over HTTP. - - Args: - request (~.delivery_api.GetTaskTrackingInfoRequest): - The request object. The ``GetTaskTrackingInfoRequest`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.task_tracking_info.TaskTrackingInfo: - The ``TaskTrackingInfo`` message. The message contains - task tracking information which will be used for - display. If a tracking ID is associated with multiple - Tasks, Fleet Engine uses a heuristic to decide which - Task's TaskTrackingInfo to select. - - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo._get_http_options() - request, metadata = self._interceptor.pre_get_task_tracking_info(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._GetTaskTrackingInfo._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = task_tracking_info.TaskTrackingInfo() - pb_resp = task_tracking_info.TaskTrackingInfo.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_task_tracking_info(resp) - return resp - - class _ListDeliveryVehicles(_BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.ListDeliveryVehicles") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: delivery_api.ListDeliveryVehiclesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_api.ListDeliveryVehiclesResponse: - r"""Call the list delivery vehicles method over HTTP. - - Args: - request (~.delivery_api.ListDeliveryVehiclesRequest): - The request object. The ``ListDeliveryVehicles`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.delivery_api.ListDeliveryVehiclesResponse: - The ``ListDeliveryVehicles`` response message. - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles._get_http_options() - request, metadata = self._interceptor.pre_list_delivery_vehicles(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._ListDeliveryVehicles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = delivery_api.ListDeliveryVehiclesResponse() - pb_resp = delivery_api.ListDeliveryVehiclesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_delivery_vehicles(resp) - return resp - - class _ListTasks(_BaseDeliveryServiceRestTransport._BaseListTasks, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.ListTasks") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: delivery_api.ListTasksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_api.ListTasksResponse: - r"""Call the list tasks method over HTTP. - - Args: - request (~.delivery_api.ListTasksRequest): - The request object. The ``ListTasks`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.delivery_api.ListTasksResponse: - The ``ListTasks`` response that contains the set of - Tasks that meet the filter criteria in the - ``ListTasksRequest``. - - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseListTasks._get_http_options() - request, metadata = self._interceptor.pre_list_tasks(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseListTasks._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseListTasks._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._ListTasks._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = delivery_api.ListTasksResponse() - pb_resp = delivery_api.ListTasksResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_tasks(resp) - return resp - - class _UpdateDeliveryVehicle(_BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.UpdateDeliveryVehicle") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: delivery_api.UpdateDeliveryVehicleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Call the update delivery vehicle method over HTTP. - - Args: - request (~.delivery_api.UpdateDeliveryVehicleRequest): - The request object. The ``UpdateDeliveryVehicle`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.delivery_vehicles.DeliveryVehicle: - The ``DeliveryVehicle`` message. A delivery vehicle - transports shipments from a depot to a delivery - location, and from a pickup location to the depot. In - some cases, delivery vehicles also transport shipments - directly from the pickup location to the delivery - location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``DeliveryVehicle.current_route_segment`` field in the - gRPC API and the ``DeliveryVehicle.currentRouteSegment`` - field in the REST API refer to the same field. - - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_http_options() - request, metadata = self._interceptor.pre_update_delivery_vehicle(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_transcoded_request(http_options, request) - - body = _BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._UpdateDeliveryVehicle._get_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 = delivery_vehicles.DeliveryVehicle() - pb_resp = delivery_vehicles.DeliveryVehicle.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_delivery_vehicle(resp) - return resp - - class _UpdateTask(_BaseDeliveryServiceRestTransport._BaseUpdateTask, DeliveryServiceRestStub): - def __hash__(self): - return hash("DeliveryServiceRestTransport.UpdateTask") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: delivery_api.UpdateTaskRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tasks.Task: - r"""Call the update task method over HTTP. - - Args: - request (~.delivery_api.UpdateTaskRequest): - The request object. The ``UpdateTask`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tasks.Task: - A Task in the Delivery API represents a single action to - track. In general, there is a distinction between - shipment-related Tasks and break Tasks. A shipment can - have multiple Tasks associated with it. For example, - there could be one Task for the pickup, and one for the - drop-off or transfer. Also, different Tasks for a given - shipment can be handled by different vehicles. For - example, one vehicle could handle the pickup, driving - the shipment to the hub, while another vehicle drives - the same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``Task.journey_sharing_info`` field in the gRPC API and - the ``Task.journeySharingInfo`` field in the REST API - refer to the same field. - - """ - - http_options = _BaseDeliveryServiceRestTransport._BaseUpdateTask._get_http_options() - request, metadata = self._interceptor.pre_update_task(request, metadata) - transcoded_request = _BaseDeliveryServiceRestTransport._BaseUpdateTask._get_transcoded_request(http_options, request) - - body = _BaseDeliveryServiceRestTransport._BaseUpdateTask._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseDeliveryServiceRestTransport._BaseUpdateTask._get_query_params_json(transcoded_request) - - # Send the request - response = DeliveryServiceRestTransport._UpdateTask._get_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 = tasks.Task() - pb_resp = tasks.Task.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_task(resp) - return resp - - @property - def batch_create_tasks(self) -> Callable[ - [delivery_api.BatchCreateTasksRequest], - delivery_api.BatchCreateTasksResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateTasks(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_delivery_vehicle(self) -> Callable[ - [delivery_api.CreateDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateDeliveryVehicle(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_task(self) -> Callable[ - [delivery_api.CreateTaskRequest], - tasks.Task]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateTask(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_delivery_vehicle(self) -> Callable[ - [delivery_api.GetDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDeliveryVehicle(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_task(self) -> Callable[ - [delivery_api.GetTaskRequest], - tasks.Task]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetTask(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_task_tracking_info(self) -> Callable[ - [delivery_api.GetTaskTrackingInfoRequest], - task_tracking_info.TaskTrackingInfo]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetTaskTrackingInfo(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_delivery_vehicles(self) -> Callable[ - [delivery_api.ListDeliveryVehiclesRequest], - delivery_api.ListDeliveryVehiclesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDeliveryVehicles(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_tasks(self) -> Callable[ - [delivery_api.ListTasksRequest], - delivery_api.ListTasksResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListTasks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_delivery_vehicle(self) -> Callable[ - [delivery_api.UpdateDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDeliveryVehicle(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_task(self) -> Callable[ - [delivery_api.UpdateTaskRequest], - tasks.Task]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateTask(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DeliveryServiceRestTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest_base.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest_base.py deleted file mode 100644 index bd01a83a74f0..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest_base.py +++ /dev/null @@ -1,514 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 DeliveryServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks - - -class _BaseDeliveryServiceRestTransport(DeliveryServiceTransport): - """Base REST backend transport for DeliveryService. - - 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 = 'fleetengine.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: 'fleetengine.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 _BaseBatchCreateTasks: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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=providers/*}/tasks:batchCreate', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.BatchCreateTasksRequest.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(_BaseDeliveryServiceRestTransport._BaseBatchCreateTasks._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateDeliveryVehicle: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "deliveryVehicleId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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=providers/*}/deliveryVehicles', - 'body': 'delivery_vehicle', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.CreateDeliveryVehicleRequest.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(_BaseDeliveryServiceRestTransport._BaseCreateDeliveryVehicle._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateTask: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "taskId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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=providers/*}/tasks', - 'body': 'task', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.CreateTaskRequest.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(_BaseDeliveryServiceRestTransport._BaseCreateTask._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetDeliveryVehicle: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_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=providers/*/deliveryVehicles/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.GetDeliveryVehicleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseDeliveryServiceRestTransport._BaseGetDeliveryVehicle._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetTask: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_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=providers/*/tasks/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.GetTaskRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseDeliveryServiceRestTransport._BaseGetTask._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetTaskTrackingInfo: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_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=providers/*/taskTrackingInfo/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.GetTaskTrackingInfoRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseDeliveryServiceRestTransport._BaseGetTaskTrackingInfo._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListDeliveryVehicles: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_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=providers/*}/deliveryVehicles', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.ListDeliveryVehiclesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseDeliveryServiceRestTransport._BaseListDeliveryVehicles._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListTasks: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_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=providers/*}/tasks', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.ListTasksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseDeliveryServiceRestTransport._BaseListTasks._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateDeliveryVehicle: - 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': '/v1/{delivery_vehicle.name=providers/*/deliveryVehicles/*}', - 'body': 'delivery_vehicle', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.UpdateDeliveryVehicleRequest.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(_BaseDeliveryServiceRestTransport._BaseUpdateDeliveryVehicle._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateTask: - 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': '/v1/{task.name=providers/*/tasks/*}', - 'body': 'task', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = delivery_api.UpdateTaskRequest.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(_BaseDeliveryServiceRestTransport._BaseUpdateTask._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseDeliveryServiceRestTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py deleted file mode 100644 index e2051b3b85ad..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__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 .common import ( - DeliveryVehicleAttribute, - DeliveryVehicleLocation, - TaskAttribute, - TimeWindow, - DeliveryVehicleLocationSensor, - DeliveryVehicleNavigationStatus, -) -from .delivery_api import ( - BatchCreateTasksRequest, - BatchCreateTasksResponse, - CreateDeliveryVehicleRequest, - CreateTaskRequest, - GetDeliveryVehicleRequest, - GetTaskRequest, - GetTaskTrackingInfoRequest, - ListDeliveryVehiclesRequest, - ListDeliveryVehiclesResponse, - ListTasksRequest, - ListTasksResponse, - UpdateDeliveryVehicleRequest, - UpdateTaskRequest, -) -from .delivery_vehicles import ( - DeliveryVehicle, - LocationInfo, - VehicleJourneySegment, - VehicleStop, -) -from .header import ( - DeliveryRequestHeader, -) -from .task_tracking_info import ( - TaskTrackingInfo, -) -from .tasks import ( - Task, - TaskTrackingViewConfig, -) - -__all__ = ( - 'DeliveryVehicleAttribute', - 'DeliveryVehicleLocation', - 'TaskAttribute', - 'TimeWindow', - 'DeliveryVehicleLocationSensor', - 'DeliveryVehicleNavigationStatus', - 'BatchCreateTasksRequest', - 'BatchCreateTasksResponse', - 'CreateDeliveryVehicleRequest', - 'CreateTaskRequest', - 'GetDeliveryVehicleRequest', - 'GetTaskRequest', - 'GetTaskTrackingInfoRequest', - 'ListDeliveryVehiclesRequest', - 'ListDeliveryVehiclesResponse', - 'ListTasksRequest', - 'ListTasksResponse', - 'UpdateDeliveryVehicleRequest', - 'UpdateTaskRequest', - 'DeliveryVehicle', - 'LocationInfo', - 'VehicleJourneySegment', - 'VehicleStop', - 'DeliveryRequestHeader', - 'TaskTrackingInfo', - 'Task', - 'TaskTrackingViewConfig', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py deleted file mode 100644 index f0fa11ac4ff5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.delivery.v1', - manifest={ - 'DeliveryVehicleLocationSensor', - 'DeliveryVehicleNavigationStatus', - 'DeliveryVehicleAttribute', - 'DeliveryVehicleLocation', - 'TimeWindow', - 'TaskAttribute', - }, -) - - -class DeliveryVehicleLocationSensor(proto.Enum): - r"""The sensor or methodology used to determine the location. - - Values: - UNKNOWN_SENSOR (0): - The sensor is unspecified or unknown. - GPS (1): - GPS or Assisted GPS. - NETWORK (2): - Assisted GPS, cell tower ID, or WiFi access - point. - PASSIVE (3): - Cell tower ID or WiFi access point. - ROAD_SNAPPED_LOCATION_PROVIDER (4): - A location determined by the mobile device to - be the most likely road position. - CUSTOMER_SUPPLIED_LOCATION (5): - A customer-supplied location from an independent source. - Typically, this value is used for a location provided from - sources other than the mobile device running Driver SDK. If - the original source is described by one of the other enum - values, use that value. Locations marked - CUSTOMER_SUPPLIED_LOCATION are typically provided via a - DeliveryVehicle's - ``last_location.supplemental_location_sensor``. - FLEET_ENGINE_LOCATION (6): - A location calculated by Fleet Engine based - on the signals available to it. Output only. - This value will be rejected if it is received in - a request. - FUSED_LOCATION_PROVIDER (100): - Android's Fused Location Provider. - CORE_LOCATION (200): - The location provider on Apple operating - systems. - """ - UNKNOWN_SENSOR = 0 - GPS = 1 - NETWORK = 2 - PASSIVE = 3 - ROAD_SNAPPED_LOCATION_PROVIDER = 4 - CUSTOMER_SUPPLIED_LOCATION = 5 - FLEET_ENGINE_LOCATION = 6 - FUSED_LOCATION_PROVIDER = 100 - CORE_LOCATION = 200 - - -class DeliveryVehicleNavigationStatus(proto.Enum): - r"""The vehicle's navigation status. - - Values: - UNKNOWN_NAVIGATION_STATUS (0): - Unspecified navigation status. - NO_GUIDANCE (1): - The Driver app's navigation is in ``FREE_NAV`` mode. - ENROUTE_TO_DESTINATION (2): - Turn-by-turn navigation is available and the Driver app - navigation has entered ``GUIDED_NAV`` mode. - OFF_ROUTE (3): - The vehicle has gone off the suggested route. - ARRIVED_AT_DESTINATION (4): - The vehicle is within approximately 50m of - the destination. - """ - UNKNOWN_NAVIGATION_STATUS = 0 - NO_GUIDANCE = 1 - ENROUTE_TO_DESTINATION = 2 - OFF_ROUTE = 3 - ARRIVED_AT_DESTINATION = 4 - - -class DeliveryVehicleAttribute(proto.Message): - r"""Describes a vehicle attribute as a key-value pair. The - "key:value" string length cannot exceed 256 characters. - - 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: - key (str): - The attribute's key. - value (str): - The attribute's value. - string_value (str): - String typed attribute value. - - Note: This is identical to the ``value`` field which will - eventually be deprecated. For create or update methods, - either field can be used, but it's strongly recommended to - use ``string_value``. If both ``string_value`` and ``value`` - are set, they must be identical or an error will be thrown. - Both fields are populated in responses. - - This field is a member of `oneof`_ ``delivery_vehicle_attribute_value``. - bool_value (bool): - Boolean typed attribute value. - - This field is a member of `oneof`_ ``delivery_vehicle_attribute_value``. - number_value (float): - Double typed attribute value. - - This field is a member of `oneof`_ ``delivery_vehicle_attribute_value``. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - string_value: str = proto.Field( - proto.STRING, - number=3, - oneof='delivery_vehicle_attribute_value', - ) - bool_value: bool = proto.Field( - proto.BOOL, - number=4, - oneof='delivery_vehicle_attribute_value', - ) - number_value: float = proto.Field( - proto.DOUBLE, - number=5, - oneof='delivery_vehicle_attribute_value', - ) - - -class DeliveryVehicleLocation(proto.Message): - r"""The location, speed, and heading of a vehicle at a point in - time. - - Attributes: - location (google.type.latlng_pb2.LatLng): - The location of the vehicle. When it is sent to Fleet - Engine, the vehicle's location is a GPS location. When you - receive it in a response, the vehicle's location can be - either a GPS location, a supplemental location, or some - other estimated location. The source is specified in - ``location_sensor``. - horizontal_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Deprecated: Use ``latlng_accuracy`` instead. - latlng_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``location`` in meters as a radius. - heading (google.protobuf.wrappers_pb2.Int32Value): - Direction the vehicle is moving in degrees. 0 represents - North. The valid range is [0,360). - bearing_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Deprecated: Use ``heading_accuracy`` instead. - heading_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``heading`` in degrees. - altitude (google.protobuf.wrappers_pb2.DoubleValue): - Altitude in meters above WGS84. - vertical_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Deprecated: Use ``altitude_accuracy`` instead. - altitude_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``altitude`` in meters. - speed_kmph (google.protobuf.wrappers_pb2.Int32Value): - Speed of the vehicle in kilometers per hour. Deprecated: Use - ``speed`` instead. - speed (google.protobuf.wrappers_pb2.DoubleValue): - Speed of the vehicle in meters/second - speed_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``speed`` in meters/second. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when ``location`` was reported by the sensor - according to the sensor's clock. - server_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the server - received the location information. - location_sensor (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocationSensor): - Provider of location data (for example, ``GPS``). - is_road_snapped (google.protobuf.wrappers_pb2.BoolValue): - Whether ``location`` is snapped to a road. - is_gps_sensor_enabled (google.protobuf.wrappers_pb2.BoolValue): - Input only. Indicates whether the GPS sensor - is enabled on the mobile device. - time_since_update (google.protobuf.wrappers_pb2.Int32Value): - Input only. Time (in seconds) since this - location was first sent to the server. This will - be zero for the first update. If the time is - unknown (for example, when the app restarts), - this value resets to zero. - num_stale_updates (google.protobuf.wrappers_pb2.Int32Value): - Input only. Deprecated: Other signals are now - used to determine if a location is stale. - raw_location (google.type.latlng_pb2.LatLng): - Raw vehicle location (unprocessed by - road-snapper). - raw_location_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp associated with the raw location. - raw_location_sensor (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocationSensor): - Source of the raw location. Defaults to ``GPS``. - raw_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``raw_location`` as a radius, in meters. - supplemental_location (google.type.latlng_pb2.LatLng): - Supplemental location provided by the - integrating app. - supplemental_location_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp associated with the supplemental - location. - supplemental_location_sensor (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocationSensor): - Source of the supplemental location. Defaults to - ``CUSTOMER_SUPPLIED_LOCATION``. - supplemental_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``supplemental_location`` as a radius, in - meters. - road_snapped (bool): - Deprecated: Use ``is_road_snapped`` instead. - """ - - location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - horizontal_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=8, - message=wrappers_pb2.DoubleValue, - ) - latlng_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=22, - message=wrappers_pb2.DoubleValue, - ) - heading: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - bearing_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=10, - message=wrappers_pb2.DoubleValue, - ) - heading_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=23, - message=wrappers_pb2.DoubleValue, - ) - altitude: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.DoubleValue, - ) - vertical_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=9, - message=wrappers_pb2.DoubleValue, - ) - altitude_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=24, - message=wrappers_pb2.DoubleValue, - ) - speed_kmph: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int32Value, - ) - speed: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.DoubleValue, - ) - speed_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=7, - message=wrappers_pb2.DoubleValue, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - server_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=13, - message=timestamp_pb2.Timestamp, - ) - location_sensor: 'DeliveryVehicleLocationSensor' = proto.Field( - proto.ENUM, - number=11, - enum='DeliveryVehicleLocationSensor', - ) - is_road_snapped: wrappers_pb2.BoolValue = proto.Field( - proto.MESSAGE, - number=27, - message=wrappers_pb2.BoolValue, - ) - is_gps_sensor_enabled: wrappers_pb2.BoolValue = proto.Field( - proto.MESSAGE, - number=12, - message=wrappers_pb2.BoolValue, - ) - time_since_update: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=14, - message=wrappers_pb2.Int32Value, - ) - num_stale_updates: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=15, - message=wrappers_pb2.Int32Value, - ) - raw_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=16, - message=latlng_pb2.LatLng, - ) - raw_location_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=17, - message=timestamp_pb2.Timestamp, - ) - raw_location_sensor: 'DeliveryVehicleLocationSensor' = proto.Field( - proto.ENUM, - number=28, - enum='DeliveryVehicleLocationSensor', - ) - raw_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=25, - message=wrappers_pb2.DoubleValue, - ) - supplemental_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=18, - message=latlng_pb2.LatLng, - ) - supplemental_location_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - supplemental_location_sensor: 'DeliveryVehicleLocationSensor' = proto.Field( - proto.ENUM, - number=20, - enum='DeliveryVehicleLocationSensor', - ) - supplemental_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=21, - message=wrappers_pb2.DoubleValue, - ) - road_snapped: bool = proto.Field( - proto.BOOL, - number=26, - ) - - -class TimeWindow(proto.Message): - r"""A time range. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The start time of the time window - (inclusive). - end_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The end time of the time window - (inclusive). - """ - - 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, - ) - - -class TaskAttribute(proto.Message): - r"""Describes a task attribute as a key-value pair. The - "key:value" string length cannot exceed 256 characters. - - 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: - key (str): - The attribute's key. Keys may not contain the - colon character (:). - string_value (str): - String typed attribute value. - - This field is a member of `oneof`_ ``task_attribute_value``. - bool_value (bool): - Boolean typed attribute value. - - This field is a member of `oneof`_ ``task_attribute_value``. - number_value (float): - Double typed attribute value. - - This field is a member of `oneof`_ ``task_attribute_value``. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - string_value: str = proto.Field( - proto.STRING, - number=2, - oneof='task_attribute_value', - ) - bool_value: bool = proto.Field( - proto.BOOL, - number=3, - oneof='task_attribute_value', - ) - number_value: float = proto.Field( - proto.DOUBLE, - number=4, - oneof='task_attribute_value', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py deleted file mode 100644 index e32df11b607b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py +++ /dev/null @@ -1,603 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.fleetengine_delivery_v1.types import delivery_vehicles as mfd_delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import header as mfd_header -from google.maps.fleetengine_delivery_v1.types import tasks as mfd_tasks -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.delivery.v1', - manifest={ - 'CreateDeliveryVehicleRequest', - 'GetDeliveryVehicleRequest', - 'ListDeliveryVehiclesRequest', - 'ListDeliveryVehiclesResponse', - 'UpdateDeliveryVehicleRequest', - 'BatchCreateTasksRequest', - 'BatchCreateTasksResponse', - 'CreateTaskRequest', - 'GetTaskRequest', - 'UpdateTaskRequest', - 'ListTasksRequest', - 'ListTasksResponse', - 'GetTaskTrackingInfoRequest', - }, -) - - -class CreateDeliveryVehicleRequest(proto.Message): - r"""The ``CreateDeliveryVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - delivery_vehicle_id (str): - Required. The Delivery Vehicle ID must be unique and subject - to the following restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): - Required. The ``DeliveryVehicle`` entity to create. When - creating a new delivery vehicle, you may set the following - optional fields: - - - type - - last_location - - attributes - - Note: The DeliveryVehicle's ``name`` field is ignored. All - other DeliveryVehicle fields must not be set; otherwise, an - error is returned. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - delivery_vehicle_id: str = proto.Field( - proto.STRING, - number=4, - ) - delivery_vehicle: mfd_delivery_vehicles.DeliveryVehicle = proto.Field( - proto.MESSAGE, - number=5, - message=mfd_delivery_vehicles.DeliveryVehicle, - ) - - -class GetDeliveryVehicleRequest(proto.Message): - r"""The ``GetDeliveryVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - name (str): - Required. Must be in the format - ``providers/{provider}/deliveryVehicles/{delivery_vehicle}``. - The ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListDeliveryVehiclesRequest(proto.Message): - r"""The ``ListDeliveryVehicles`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - page_size (int): - Optional. The maximum number of vehicles to - return. The service may return fewer than this - number. If you don't specify this number, then - the server determines the number of results to - return. - page_token (str): - Optional. A page token, received from a previous - ``ListDeliveryVehicles`` call. You must provide this in - order to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListDeliveryVehicles`` must match the call that provided - the page token. - filter (str): - Optional. A filter query to apply when listing delivery - vehicles. See http://aip.dev/160 for examples of the filter - syntax. If you don't specify a value, or if you specify an - empty string for the filter, then all delivery vehicles are - returned. - - Note that the only queries supported for - ``ListDeliveryVehicles`` are on vehicle attributes (for - example, ``attributes. = `` or - ``attributes. = AND attributes. = ``). - Also, all attributes are stored as strings, so the only - supported comparisons against attributes are string - comparisons. In order to compare against number or boolean - values, the values must be explicitly quoted to be treated - as strings (for example, ``attributes. = "10"`` or - ``attributes. = "true"``). - - The maximum number of restrictions allowed in a filter query - is 50. A restriction is a part of the query of the form - ``attribute. ``, for example - ``attributes.foo = bar`` is 1 restriction. - viewport (google.geo.type.types.Viewport): - Optional. A filter that limits the vehicles - returned to those whose last known location was - in the rectangular area defined by the viewport. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - filter: str = proto.Field( - proto.STRING, - number=6, - ) - viewport: ggt_viewport.Viewport = proto.Field( - proto.MESSAGE, - number=7, - message=ggt_viewport.Viewport, - ) - - -class ListDeliveryVehiclesResponse(proto.Message): - r"""The ``ListDeliveryVehicles`` response message. - - Attributes: - delivery_vehicles (MutableSequence[google.maps.fleetengine_delivery_v1.types.DeliveryVehicle]): - The set of delivery vehicles that meet the - requested filtering criteria. When no filter is - specified, the request returns all delivery - vehicles. A successful response can also be - empty. An empty response indicates that no - delivery vehicles were found meeting the - requested filter criteria. - next_page_token (str): - You can pass this token in the - ``ListDeliveryVehiclesRequest`` to continue to list results. - When all of the results are returned, this field won't be in - the response, or it will be an empty string. - total_size (int): - The total number of delivery vehicles that - match the request criteria, across all pages. - """ - - @property - def raw_page(self): - return self - - delivery_vehicles: MutableSequence[mfd_delivery_vehicles.DeliveryVehicle] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mfd_delivery_vehicles.DeliveryVehicle, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT64, - number=3, - ) - - -class UpdateDeliveryVehicleRequest(proto.Message): - r"""The ``UpdateDeliveryVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): - Required. The ``DeliveryVehicle`` entity update to apply. - Note: You cannot update the name of the ``DeliveryVehicle``. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A field mask that indicates which - ``DeliveryVehicle`` fields to update. Note that the - update_mask must contain at least one field. - - This is a comma-separated list of fully qualified names of - fields. Example: ``"remaining_vehicle_journey_segments"``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - delivery_vehicle: mfd_delivery_vehicles.DeliveryVehicle = proto.Field( - proto.MESSAGE, - number=3, - message=mfd_delivery_vehicles.DeliveryVehicle, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class BatchCreateTasksRequest(proto.Message): - r"""The ``BatchCreateTask`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request header. Note: If - you set this field, then the header field in the - ``CreateTaskRequest`` messages must either be empty, or it - must match this field. - parent (str): - Required. The parent resource shared by all tasks. This - value must be in the format ``providers/{provider}``. The - ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. The parent field in the - ``CreateTaskRequest`` messages must either be empty, or it - must match this field. - requests (MutableSequence[google.maps.fleetengine_delivery_v1.types.CreateTaskRequest]): - Required. The request message that specifies - the resources to create. Note: You can create a - maximum of 500 tasks in a batch. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - requests: MutableSequence['CreateTaskRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='CreateTaskRequest', - ) - - -class BatchCreateTasksResponse(proto.Message): - r"""The ``BatchCreateTask`` response message. - - Attributes: - tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.Task]): - The created Tasks. - """ - - tasks: MutableSequence[mfd_tasks.Task] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mfd_tasks.Task, - ) - - -class CreateTaskRequest(proto.Message): - r"""The ``CreateTask`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - task_id (str): - Required. The Task ID must be unique, but it should be not a - shipment tracking ID. To store a shipment tracking ID, use - the ``tracking_id`` field. Note that multiple tasks can have - the same ``tracking_id``. Task IDs are subject to the - following restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - task (google.maps.fleetengine_delivery_v1.types.Task): - Required. The Task entity to create. When creating a Task, - the following fields are required: - - - ``type`` - - ``state`` (must be set to ``OPEN``) - - ``tracking_id`` (must not be set for ``UNAVAILABLE`` or - ``SCHEDULED_STOP`` tasks, but required for all other task - types) - - ``planned_location`` (optional for ``UNAVAILABLE`` tasks) - - ``task_duration`` - - Note: The Task's ``name`` field is ignored. All other Task - fields must not be set; otherwise, an error is returned. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - task_id: str = proto.Field( - proto.STRING, - number=5, - ) - task: mfd_tasks.Task = proto.Field( - proto.MESSAGE, - number=4, - message=mfd_tasks.Task, - ) - - -class GetTaskRequest(proto.Message): - r"""The ``GetTask`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - name (str): - Required. Must be in the format - ``providers/{provider}/tasks/{task}``. The ``provider`` must - be the Google Cloud Project ID. For example, - ``sample-cloud-project``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateTaskRequest(proto.Message): - r"""The ``UpdateTask`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - task (google.maps.fleetengine_delivery_v1.types.Task): - Required. The Task associated with the update. The following - fields are maintained by Fleet Engine. Do not update them - using ``Task.update``. - - - ``last_location``. - - ``last_location_snappable``. - - ``name``. - - ``remaining_vehicle_journey_segments``. - - ``task_outcome_location_source``. - - Note: You cannot change the value of ``task_outcome`` once - you set it. - - If the Task has been assigned to a delivery vehicle, then - don't set the Task state to CLOSED using ``Task.update``. - Instead, remove the ``VehicleStop`` that contains the Task - from the delivery vehicle, which automatically sets the Task - state to CLOSED. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The field mask that indicates which Task fields to - update. Note: The ``update_mask`` must contain at least one - field. - - This is a comma-separated list of fully qualified names of - fields. Example: - ``"task_outcome,task_outcome_time,task_outcome_location"``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - task: mfd_tasks.Task = proto.Field( - proto.MESSAGE, - number=3, - message=mfd_tasks.Task, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class ListTasksRequest(proto.Message): - r"""The ``ListTasks`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - page_size (int): - Optional. The maximum number of Tasks to - return. The service may return fewer than this - value. If you don't specify this value, then the - server determines the number of results to - return. - page_token (str): - Optional. A page token received from a previous - ``ListTasks`` call. You can provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListTasks`` must match the call that provided the page - token. - filter (str): - Optional. A filter query to apply when listing Tasks. See - http://aip.dev/160 for examples of filter syntax. If you - don't specify a value, or if you filter on an empty string, - then all Tasks are returned. For information about the Task - properties that you can filter on, see `List - tasks `__. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - filter: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ListTasksResponse(proto.Message): - r"""The ``ListTasks`` response that contains the set of Tasks that meet - the filter criteria in the ``ListTasksRequest``. - - Attributes: - tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.Task]): - The set of Tasks that meet the requested - filtering criteria. When no filter is specified, - the request returns all tasks. A successful - response can also be empty. An empty response - indicates that no Tasks were found meeting the - requested filter criteria. - next_page_token (str): - Pass this token in the ``ListTasksRequest`` to continue to - list results. If all results have been returned, then this - field is either an empty string, or it doesn't appear in the - response. - total_size (int): - The total number of Tasks that match the - request criteria, across all pages. - """ - - @property - def raw_page(self): - return self - - tasks: MutableSequence[mfd_tasks.Task] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mfd_tasks.Task, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT64, - number=3, - ) - - -class GetTaskTrackingInfoRequest(proto.Message): - r"""The ``GetTaskTrackingInfoRequest`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - name (str): - Required. Must be in the format - ``providers/{provider}/taskTrackingInfo/{tracking_id}``. The - ``provider`` must be the Google Cloud Project ID, and the - ``tracking_id`` must be the tracking ID associated with the - task. An example name can be - ``providers/sample-cloud-project/taskTrackingInfo/sample-tracking-id``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py deleted file mode 100644 index 2ded1f83bf92..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py +++ /dev/null @@ -1,414 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.fleetengine_delivery_v1.types import common -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.delivery.v1', - manifest={ - 'DeliveryVehicle', - 'LocationInfo', - 'VehicleJourneySegment', - 'VehicleStop', - }, -) - - -class DeliveryVehicle(proto.Message): - r"""The ``DeliveryVehicle`` message. A delivery vehicle transports - shipments from a depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery vehicles also - transport shipments directly from the pickup location to the - delivery location. - - Note: gRPC and REST APIs use different field naming conventions. For - example, the ``DeliveryVehicle.current_route_segment`` field in the - gRPC API and the ``DeliveryVehicle.currentRouteSegment`` field in - the REST API refer to the same field. - - Attributes: - name (str): - The unique name of this Delivery Vehicle. The format is - ``providers/{provider}/deliveryVehicles/{vehicle}``. - last_location (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocation): - The last reported location of the Delivery - Vehicle. - navigation_status (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleNavigationStatus): - The Delivery Vehicle's navigation status. - current_route_segment (bytes): - The encoded polyline specifying the route that the - navigation recommends taking to the next waypoint. Your - driver app updates this when a stop is reached or passed, - and when the navigation reroutes. These ``LatLng``\ s are - returned in - ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0].path`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments[0].path`` - (REST) for all active Tasks assigned to the Vehicle. - - There are a few cases where this field might not be used to - populate - ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0].path`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments[0].path`` - (REST): - - - The endpoint of the ``current_route_segment`` does not - match - ``DeliveryVehicle.remaining_vehicle_journey_segments[0].stop`` - (gRPC) or - ``DeliveryVehicle.remainingVehicleJourneySegments[0].stop`` - (REST). - - - The driver app has not updated its location recently, so - the last updated value for this field might be stale. - - - The driver app has recently updated its location, but the - ``current_route_segment`` is stale, and points to a - previous vehicle stop. - - In these cases, Fleet Engine populates this field with a - route from the most recently passed VehicleStop to the - upcoming VehicleStop to ensure that the consumer of this - field has the best available information on the current path - of the Delivery Vehicle. - current_route_segment_end_point (google.type.latlng_pb2.LatLng): - The location where the ``current_route_segment`` ends. This - is not currently populated by the driver app, but you can - supply it on ``UpdateDeliveryVehicle`` calls. It is either - the ``LatLng`` from the upcoming vehicle stop, or the last - ``LatLng`` of the ``current_route_segment``. Fleet Engine - will then do its best to interpolate to an actual - ``VehicleStop``. - - This field is ignored in ``UpdateDeliveryVehicle`` calls if - the ``current_route_segment`` field is empty. - remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The remaining driving distance for the - ``current_route_segment``. The Driver app typically provides - this field, but there are some circumstances in which Fleet - Engine will override the value sent by the app. For more - information, see - [DeliveryVehicle.current_route_segment][maps.fleetengine.delivery.v1.DeliveryVehicle.current_route_segment]. - This field is returned in - ``Task.remaining_vehicle_journey_segments[0].driving_distance_meters`` - (gRPC) or - ``Task.remainingVehicleJourneySegments[0].drivingDistanceMeters`` - (REST) for all active ``Task``\ s assigned to the Delivery - Vehicle. - - Fleet Engine ignores this field in - ``UpdateDeliveryVehicleRequest`` if the - ``current_route_segment`` field is empty. - remaining_duration (google.protobuf.duration_pb2.Duration): - The remaining driving time for the - ``current_route_segment``. The Driver app typically provides - this field, but there are some circumstances in which Fleet - Engine will override the value sent by the app. For more - information, see - [DeliveryVehicle.current_route_segment][maps.fleetengine.delivery.v1.DeliveryVehicle.current_route_segment]. - This field is returned in - ``Task.remaining_vehicle_journey_segments[0].driving_duration`` - (gRPC) or - ``Task.remainingVehicleJourneySegments[0].drivingDuration`` - (REST) for all active tasks assigned to the Delivery - Vehicle. - - Fleet Engine ignores this field in - ``UpdateDeliveryVehicleRequest`` if the - ``current_route_segment`` field is empty. - remaining_vehicle_journey_segments (MutableSequence[google.maps.fleetengine_delivery_v1.types.VehicleJourneySegment]): - The journey segments assigned to this Delivery Vehicle, - starting from the Vehicle's most recently reported location. - This field won't be populated in the response of - ``ListDeliveryVehicles``. - attributes (MutableSequence[google.maps.fleetengine_delivery_v1.types.DeliveryVehicleAttribute]): - A list of custom Delivery Vehicle attributes. - A Delivery Vehicle can have at most 100 - attributes, and each attribute must have a - unique key. - type_ (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle.DeliveryVehicleType): - The type of this delivery vehicle. If unset, this will - default to ``AUTO``. - """ - class DeliveryVehicleType(proto.Enum): - r"""The type of delivery vehicle. - - Values: - DELIVERY_VEHICLE_TYPE_UNSPECIFIED (0): - The value is unused. - AUTO (1): - An automobile. - TWO_WHEELER (2): - A motorcycle, moped, or other two-wheeled - vehicle - BICYCLE (3): - Human-powered transport. - PEDESTRIAN (4): - A human transporter, typically walking or - running, traveling along pedestrian pathways. - """ - DELIVERY_VEHICLE_TYPE_UNSPECIFIED = 0 - AUTO = 1 - TWO_WHEELER = 2 - BICYCLE = 3 - PEDESTRIAN = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - last_location: common.DeliveryVehicleLocation = proto.Field( - proto.MESSAGE, - number=2, - message=common.DeliveryVehicleLocation, - ) - navigation_status: common.DeliveryVehicleNavigationStatus = proto.Field( - proto.ENUM, - number=3, - enum=common.DeliveryVehicleNavigationStatus, - ) - current_route_segment: bytes = proto.Field( - proto.BYTES, - number=4, - ) - current_route_segment_end_point: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=5, - message=latlng_pb2.LatLng, - ) - remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int32Value, - ) - remaining_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - remaining_vehicle_journey_segments: MutableSequence['VehicleJourneySegment'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='VehicleJourneySegment', - ) - attributes: MutableSequence[common.DeliveryVehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=common.DeliveryVehicleAttribute, - ) - type_: DeliveryVehicleType = proto.Field( - proto.ENUM, - number=10, - enum=DeliveryVehicleType, - ) - - -class LocationInfo(proto.Message): - r"""A location with any additional identifiers. - - Attributes: - point (google.type.latlng_pb2.LatLng): - The location's coordinates. - """ - - point: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - - -class VehicleJourneySegment(proto.Message): - r"""Represents a Vehicle’s travel segment - from its previous - stop to the current stop. If it is the first active stop, then - it is from the Vehicle’s current location to this stop. - - Attributes: - stop (google.maps.fleetengine_delivery_v1.types.VehicleStop): - Specifies the stop location, along with the ``Task``\ s - associated with the stop. Some fields of the VehicleStop - might not be present if this journey segment is part of - ``JourneySharingInfo``. - driving_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - Output only. The travel distance from the previous stop to - this stop. If the current stop is the first stop in the list - of journey segments, then the starting point is the - vehicle's location recorded at the time that this stop was - added to the list. This field might not be present if this - journey segment is part of ``JourneySharingInfo``. - driving_duration (google.protobuf.duration_pb2.Duration): - Output only. The travel time from the previous stop to this - stop. If the current stop is the first stop in the list of - journey segments, then the starting point is the Vehicle's - location recorded at the time that this stop was added to - the list. - - If this field is defined in the path - ``Task.remaining_vehicle_journey_segments[0].driving_duration`` - (gRPC) or - ``Task.remainingVehicleJourneySegments[0].drivingDuration`` - (REST), then it may be populated with the value from - ``DeliveryVehicle.remaining_duration`` (gRPC) or - ``DeliveryVehicle.remainingDuration`` (REST). This provides - the remaining driving duration from the driver app's latest - known location rather than the driving time from the - previous stop. - path (MutableSequence[google.type.latlng_pb2.LatLng]): - Output only. The path from the previous stop to this stop. - If the current stop is the first stop in the list of journey - segments, then this is the path from the vehicle's current - location to this stop at the time that the stop was added to - the list. This field might not be present if this journey - segment is part of ``JourneySharingInfo``. - - If this field is defined in the path - ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0].path`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments[0].path`` - (REST), then it may be populated with the ``LatLng``\ s - decoded from ``DeliveryVehicle.current_route_segment`` - (gRPC) or ``DeliveryVehicle.currentRouteSegment`` (REST). - This provides the driving path from the driver app's latest - known location rather than the path from the previous stop. - """ - - stop: 'VehicleStop' = proto.Field( - proto.MESSAGE, - number=1, - message='VehicleStop', - ) - driving_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - driving_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - path: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=latlng_pb2.LatLng, - ) - - -class VehicleStop(proto.Message): - r"""Describes a point where a Vehicle stops to perform one or more - ``Task``\ s. - - Attributes: - planned_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): - Required. The location of the stop. Note that the locations - in the ``Task``\ s might not exactly match this location, - but will be within a short distance of it. This field won't - be populated in the response of a ``GetTask`` call. - tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.VehicleStop.TaskInfo]): - The list of ``Task``\ s to be performed at this stop. This - field won't be populated in the response of a ``GetTask`` - call. - state (google.maps.fleetengine_delivery_v1.types.VehicleStop.State): - The state of the ``VehicleStop``. This field won't be - populated in the response of a ``GetTask`` call. - """ - class State(proto.Enum): - r"""The current state of a ``VehicleStop``. - - Values: - STATE_UNSPECIFIED (0): - Unknown. - NEW (1): - Created, but not actively routing. - ENROUTE (2): - Assigned and actively routing. - ARRIVED (3): - Arrived at stop. Assumes that when the - Vehicle is routing to the next stop, that all - previous stops have been completed. - """ - STATE_UNSPECIFIED = 0 - NEW = 1 - ENROUTE = 2 - ARRIVED = 3 - - class TaskInfo(proto.Message): - r"""Additional information about the Task performed at this stop. - - Attributes: - task_id (str): - The Task ID. This field won't be populated in the response - of a ``GetTask`` call. Task IDs are subject to the following - restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - task_duration (google.protobuf.duration_pb2.Duration): - Output only. The time required to perform the - Task. - target_time_window (google.maps.fleetengine_delivery_v1.types.TimeWindow): - Output only. The time window during which the task should be - completed. This is only set in the response to - ``GetDeliveryVehicle``. - """ - - task_id: str = proto.Field( - proto.STRING, - number=1, - ) - task_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - target_time_window: common.TimeWindow = proto.Field( - proto.MESSAGE, - number=3, - message=common.TimeWindow, - ) - - planned_location: 'LocationInfo' = proto.Field( - proto.MESSAGE, - number=1, - message='LocationInfo', - ) - tasks: MutableSequence[TaskInfo] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=TaskInfo, - ) - state: State = proto.Field( - proto.ENUM, - number=3, - enum=State, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.py deleted file mode 100644 index 4764c19a73c6..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.delivery.v1', - manifest={ - 'DeliveryRequestHeader', - }, -) - - -class DeliveryRequestHeader(proto.Message): - r"""A RequestHeader contains fields common to all Delivery RPC - requests. - - Attributes: - language_code (str): - The BCP-47 language code, such as en-US or sr-Latn. For more - information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - If none is specified, the response may be in any language, - with a preference for English if such a name exists. Field - value example: ``en-US``. - region_code (str): - Required. CLDR region code of the region where the request - originates. Field value example: ``US``. - sdk_version (str): - Version of the calling SDK, if applicable. The version - format is "major.minor.patch", example: ``1.1.2``. - os_version (str): - Version of the operating system on which the calling SDK is - running. Field value examples: ``4.4.1``, ``12.1``. - device_model (str): - Model of the device on which the calling SDK is running. - Field value examples: ``iPhone12,1``, ``SM-G920F``. - sdk_type (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader.SdkType): - The type of SDK sending the request. - maps_sdk_version (str): - Version of the MapSDK which the calling SDK depends on, if - applicable. The version format is "major.minor.patch", - example: ``5.2.1``. - nav_sdk_version (str): - Version of the NavSDK which the calling SDK depends on, if - applicable. The version format is "major.minor.patch", - example: ``2.1.0``. - platform (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader.Platform): - Platform of the calling SDK. - manufacturer (str): - Manufacturer of the Android device from the calling SDK, - only applicable for the Android SDKs. Field value example: - ``Samsung``. - android_api_level (int): - Android API level of the calling SDK, only applicable for - the Android SDKs. Field value example: ``23``. - trace_id (str): - Optional ID that can be provided for logging - purposes in order to identify the request. - """ - class SdkType(proto.Enum): - r"""Possible types of SDK. - - Values: - SDK_TYPE_UNSPECIFIED (0): - The default value. This value is used if the ``sdk_type`` is - omitted. - CONSUMER (1): - The calling SDK is Consumer. - DRIVER (2): - The calling SDK is Driver. - JAVASCRIPT (3): - The calling SDK is JavaScript. - """ - SDK_TYPE_UNSPECIFIED = 0 - CONSUMER = 1 - DRIVER = 2 - JAVASCRIPT = 3 - - class Platform(proto.Enum): - r"""The platform of the calling SDK. - - Values: - PLATFORM_UNSPECIFIED (0): - The default value. This value is used if the - platform is omitted. - ANDROID (1): - The request is coming from Android. - IOS (2): - The request is coming from iOS. - WEB (3): - The request is coming from the web. - """ - PLATFORM_UNSPECIFIED = 0 - ANDROID = 1 - IOS = 2 - WEB = 3 - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=2, - ) - sdk_version: str = proto.Field( - proto.STRING, - number=3, - ) - os_version: str = proto.Field( - proto.STRING, - number=4, - ) - device_model: str = proto.Field( - proto.STRING, - number=5, - ) - sdk_type: SdkType = proto.Field( - proto.ENUM, - number=6, - enum=SdkType, - ) - maps_sdk_version: str = proto.Field( - proto.STRING, - number=7, - ) - nav_sdk_version: str = proto.Field( - proto.STRING, - number=8, - ) - platform: Platform = proto.Field( - proto.ENUM, - number=9, - enum=Platform, - ) - manufacturer: str = proto.Field( - proto.STRING, - number=10, - ) - android_api_level: int = proto.Field( - proto.INT32, - number=11, - ) - trace_id: str = proto.Field( - proto.STRING, - number=12, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py deleted file mode 100644 index 8ad90dd9b068..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.fleetengine_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import tasks -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.delivery.v1', - manifest={ - 'TaskTrackingInfo', - }, -) - - -class TaskTrackingInfo(proto.Message): - r"""The ``TaskTrackingInfo`` message. The message contains task tracking - information which will be used for display. If a tracking ID is - associated with multiple Tasks, Fleet Engine uses a heuristic to - decide which Task's TaskTrackingInfo to select. - - Attributes: - name (str): - Must be in the format - ``providers/{provider}/taskTrackingInfo/{tracking}``, where - ``tracking`` represents the tracking ID. - tracking_id (str): - Immutable. The tracking ID of a Task. - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - vehicle_location (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocation): - The vehicle's last location. - route_polyline_points (MutableSequence[google.type.latlng_pb2.LatLng]): - A list of points which when connected forms a - polyline of the vehicle's expected route to the - location of this task. - remaining_stop_count (google.protobuf.wrappers_pb2.Int32Value): - Indicates the number of stops the vehicle - remaining until the task stop is reached, - including the task stop. For example, if the - vehicle's next stop is the task stop, the value - will be 1. - remaining_driving_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The total remaining distance in meters to the - ``VehicleStop`` of interest. - estimated_arrival_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp that indicates the estimated - arrival time to the stop location. - estimated_task_completion_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp that indicates the estimated - completion time of a Task. - state (google.maps.fleetengine_delivery_v1.types.Task.State): - The current execution state of the Task. - task_outcome (google.maps.fleetengine_delivery_v1.types.Task.TaskOutcome): - The outcome of attempting to execute a Task. - task_outcome_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp that indicates when the Task's - outcome was set by the provider. - planned_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): - Immutable. The location where the Task will - be completed. - target_time_window (google.maps.fleetengine_delivery_v1.types.TimeWindow): - The time window during which the task should - be completed. - attributes (MutableSequence[google.maps.fleetengine_delivery_v1.types.TaskAttribute]): - The custom attributes set on the task. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - tracking_id: str = proto.Field( - proto.STRING, - number=2, - ) - vehicle_location: common.DeliveryVehicleLocation = proto.Field( - proto.MESSAGE, - number=3, - message=common.DeliveryVehicleLocation, - ) - route_polyline_points: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=latlng_pb2.LatLng, - ) - remaining_stop_count: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int32Value, - ) - remaining_driving_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int32Value, - ) - estimated_arrival_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - estimated_task_completion_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - state: tasks.Task.State = proto.Field( - proto.ENUM, - number=11, - enum=tasks.Task.State, - ) - task_outcome: tasks.Task.TaskOutcome = proto.Field( - proto.ENUM, - number=9, - enum=tasks.Task.TaskOutcome, - ) - task_outcome_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - planned_location: delivery_vehicles.LocationInfo = proto.Field( - proto.MESSAGE, - number=10, - message=delivery_vehicles.LocationInfo, - ) - target_time_window: common.TimeWindow = proto.Field( - proto.MESSAGE, - number=13, - message=common.TimeWindow, - ) - attributes: MutableSequence[common.TaskAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=common.TaskAttribute, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py deleted file mode 100644 index ecb26f920108..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.fleetengine_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.delivery.v1', - manifest={ - 'Task', - 'TaskTrackingViewConfig', - }, -) - - -class Task(proto.Message): - r"""A Task in the Delivery API represents a single action to track. In - general, there is a distinction between shipment-related Tasks and - break Tasks. A shipment can have multiple Tasks associated with it. - For example, there could be one Task for the pickup, and one for the - drop-off or transfer. Also, different Tasks for a given shipment can - be handled by different vehicles. For example, one vehicle could - handle the pickup, driving the shipment to the hub, while another - vehicle drives the same shipment from the hub to the drop-off - location. - - Note: gRPC and REST APIs use different field naming conventions. For - example, the ``Task.journey_sharing_info`` field in the gRPC API and - the ``Task.journeySharingInfo`` field in the REST API refer to the - same field. - - Attributes: - name (str): - Must be in the format ``providers/{provider}/tasks/{task}``. - type_ (google.maps.fleetengine_delivery_v1.types.Task.Type): - Required. Immutable. Defines the type of the - Task. For example, a break or shipment. - state (google.maps.fleetengine_delivery_v1.types.Task.State): - Required. The current execution state of the - Task. - task_outcome (google.maps.fleetengine_delivery_v1.types.Task.TaskOutcome): - The outcome of the Task. - task_outcome_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp that indicates when the ``Task``'s outcome was - set by the provider. - task_outcome_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): - The location where the ``Task``'s outcome was set. This - value is updated as part of ``UpdateTask``. If this value - isn't explicitly updated by the provider, then Fleet Engine - populates it by default with the last known vehicle location - (the *raw* location). - task_outcome_location_source (google.maps.fleetengine_delivery_v1.types.Task.TaskOutcomeLocationSource): - Indicates where the value of the ``task_outcome_location`` - came from. - tracking_id (str): - Immutable. This field facilitates the storing of an ID so - you can avoid using a complicated mapping. You cannot set - ``tracking_id`` for Tasks of type ``UNAVAILABLE`` and - ``SCHEDULED_STOP``. These IDs are subject to the following - restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - delivery_vehicle_id (str): - Output only. The ID of the vehicle that is executing this - Task. Delivery Vehicle IDs are subject to the following - restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - planned_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): - Immutable. The location where the Task will be completed. - Optional for ``UNAVAILABLE`` Tasks, but required for all - other Tasks. - task_duration (google.protobuf.duration_pb2.Duration): - Required. Immutable. The time needed to - execute a Task at this location. - target_time_window (google.maps.fleetengine_delivery_v1.types.TimeWindow): - The time window during which the task should - be completed. - journey_sharing_info (google.maps.fleetengine_delivery_v1.types.Task.JourneySharingInfo): - Output only. Journey sharing-specific fields. Not populated - when state is ``CLOSED``. - task_tracking_view_config (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig): - The configuration for task tracking that - specifies which data elements are visible to the - end users under what circumstances. - attributes (MutableSequence[google.maps.fleetengine_delivery_v1.types.TaskAttribute]): - A list of custom Task attributes. Each - attribute must have a unique key. - """ - class Type(proto.Enum): - r"""The type of Task. - - Values: - TYPE_UNSPECIFIED (0): - Default, the Task type is unknown. - PICKUP (1): - A pickup Task is the action taken for picking up a shipment - from a customer. Depot or feeder vehicle pickups should use - the ``SCHEDULED_STOP`` type. - DELIVERY (2): - A delivery Task is the action taken for delivering a - shipment to an end customer. Depot or feeder vehicle - dropoffs should use the ``SCHEDULED_STOP`` type. - SCHEDULED_STOP (3): - A scheduled stop Task is used for planning - purposes. For example, it could represent - picking up or dropping off shipments from feeder - vehicles or depots. It shouldn't be used for any - shipments that are picked up or dropped off from - an end customer. - UNAVAILABLE (4): - A Task that means the Vehicle is not - available for service. For example, this can - happen when the driver takes a break, or when - the vehicle is being refueled. - """ - TYPE_UNSPECIFIED = 0 - PICKUP = 1 - DELIVERY = 2 - SCHEDULED_STOP = 3 - UNAVAILABLE = 4 - - class State(proto.Enum): - r"""The state of a Task. This indicates the Tasks's progress. - - Values: - STATE_UNSPECIFIED (0): - Default. Used for an unspecified or - unrecognized Task state. - OPEN (1): - Either the Task has not yet been assigned to a delivery - vehicle, or the delivery vehicle has not yet passed the - ``Task``'s assigned vehicle stop. - CLOSED (2): - When the vehicle passes the vehicle stop for - this Task. - """ - STATE_UNSPECIFIED = 0 - OPEN = 1 - CLOSED = 2 - - class TaskOutcome(proto.Enum): - r"""The outcome of attempting to execute a Task. When ``TaskState`` is - closed, ``TaskOutcome`` indicates whether it was completed - successfully. - - Values: - TASK_OUTCOME_UNSPECIFIED (0): - The Task outcome before its value is set. - SUCCEEDED (1): - The Task completed successfully. - FAILED (2): - Either the Task couldn't be completed, or it - was cancelled. - """ - TASK_OUTCOME_UNSPECIFIED = 0 - SUCCEEDED = 1 - FAILED = 2 - - class TaskOutcomeLocationSource(proto.Enum): - r"""The identity of the source that populated the - ``task_outcome_location``. - - Values: - TASK_OUTCOME_LOCATION_SOURCE_UNSPECIFIED (0): - The task outcome before it is set. - PROVIDER (2): - The provider-specified the ``task_outcome_location``. - LAST_VEHICLE_LOCATION (3): - The provider didn't specify the ``task_outcome_location``, - so Fleet Engine used the last known vehicle location. - """ - TASK_OUTCOME_LOCATION_SOURCE_UNSPECIFIED = 0 - PROVIDER = 2 - LAST_VEHICLE_LOCATION = 3 - - class JourneySharingInfo(proto.Message): - r"""Journey sharing specific fields. - - Attributes: - remaining_vehicle_journey_segments (MutableSequence[google.maps.fleetengine_delivery_v1.types.VehicleJourneySegment]): - Tracking information for the stops that the assigned vehicle - will make before it completes this Task. Note that this list - can contain stops from other tasks. - - The first segment, - ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0]`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments[0]`` - (REST), contains route information from the driver's last - known location to the upcoming ``VehicleStop``. Current - route information usually comes from the driver app, except - for some cases noted in the documentation for - [DeliveryVehicle.current_route_segment][maps.fleetengine.delivery.v1.DeliveryVehicle.current_route_segment]. - The other segments in - ``Task.journey_sharing_info.remaining_vehicle_journey_segments`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments`` - (REST) are populated by Fleet Engine. They provide route - information between the remaining ``VehicleStops``. - last_location (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocation): - Indicates the vehicle's last reported - location of the assigned vehicle. - last_location_snappable (bool): - Indicates whether the vehicle's lastLocation can be snapped - to the ``current_route_segment``. This value is False if - either ``last_location`` or ``current_route_segment`` don't - exist. This value is computed by Fleet Engine. Updates from - clients are ignored. - """ - - remaining_vehicle_journey_segments: MutableSequence[delivery_vehicles.VehicleJourneySegment] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=delivery_vehicles.VehicleJourneySegment, - ) - last_location: common.DeliveryVehicleLocation = proto.Field( - proto.MESSAGE, - number=2, - message=common.DeliveryVehicleLocation, - ) - last_location_snappable: bool = proto.Field( - proto.BOOL, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - state: State = proto.Field( - proto.ENUM, - number=3, - enum=State, - ) - task_outcome: TaskOutcome = proto.Field( - proto.ENUM, - number=9, - enum=TaskOutcome, - ) - task_outcome_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - task_outcome_location: delivery_vehicles.LocationInfo = proto.Field( - proto.MESSAGE, - number=11, - message=delivery_vehicles.LocationInfo, - ) - task_outcome_location_source: TaskOutcomeLocationSource = proto.Field( - proto.ENUM, - number=12, - enum=TaskOutcomeLocationSource, - ) - tracking_id: str = proto.Field( - proto.STRING, - number=4, - ) - delivery_vehicle_id: str = proto.Field( - proto.STRING, - number=5, - ) - planned_location: delivery_vehicles.LocationInfo = proto.Field( - proto.MESSAGE, - number=6, - message=delivery_vehicles.LocationInfo, - ) - task_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - target_time_window: common.TimeWindow = proto.Field( - proto.MESSAGE, - number=14, - message=common.TimeWindow, - ) - journey_sharing_info: JourneySharingInfo = proto.Field( - proto.MESSAGE, - number=8, - message=JourneySharingInfo, - ) - task_tracking_view_config: 'TaskTrackingViewConfig' = proto.Field( - proto.MESSAGE, - number=13, - message='TaskTrackingViewConfig', - ) - attributes: MutableSequence[common.TaskAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=15, - message=common.TaskAttribute, - ) - - -class TaskTrackingViewConfig(proto.Message): - r"""The configuration message that defines when a data element of - a Task should be visible to the end users. - - Attributes: - route_polyline_points_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when route polyline - points can be visible. If this field is not - specified, the project level default visibility - configuration for this data will be used. - estimated_arrival_time_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when estimated - arrival time can be visible. If this field is - not specified, the project level default - visibility configuration for this data will be - used. - estimated_task_completion_time_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when estimated task - completion time can be visible. If this field is - not specified, the project level default - visibility configuration for this data will be - used. - remaining_driving_distance_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when remaining - driving distance can be visible. If this field - is not specified, the project level default - visibility configuration for this data will be - used. - remaining_stop_count_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when remaining stop - count can be visible. If this field is not - specified, the project level default visibility - configuration for this data will be used. - vehicle_location_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when vehicle - location can be visible. If this field is not - specified, the project level default visibility - configuration for this data will be used. - """ - - class VisibilityOption(proto.Message): - r"""The option message that defines when a data element should be - visible to the end users. - - 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: - remaining_stop_count_threshold (int): - This data element is visible to the end users if the - remaining stop count <= remaining_stop_count_threshold. - - This field is a member of `oneof`_ ``visibility_option``. - duration_until_estimated_arrival_time_threshold (google.protobuf.duration_pb2.Duration): - This data element is visible to the end users if the ETA to - the stop <= duration_until_estimated_arrival_time_threshold. - - This field is a member of `oneof`_ ``visibility_option``. - remaining_driving_distance_meters_threshold (int): - This data element is visible to the end users if the - remaining driving distance in meters <= - remaining_driving_distance_meters_threshold. - - This field is a member of `oneof`_ ``visibility_option``. - always (bool): - If set to true, this data element is always - visible to the end users with no thresholds. - This field cannot be set to false. - - This field is a member of `oneof`_ ``visibility_option``. - never (bool): - If set to true, this data element is always - hidden from the end users with no thresholds. - This field cannot be set to false. - - This field is a member of `oneof`_ ``visibility_option``. - """ - - remaining_stop_count_threshold: int = proto.Field( - proto.INT32, - number=1, - oneof='visibility_option', - ) - duration_until_estimated_arrival_time_threshold: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - oneof='visibility_option', - message=duration_pb2.Duration, - ) - remaining_driving_distance_meters_threshold: int = proto.Field( - proto.INT32, - number=3, - oneof='visibility_option', - ) - always: bool = proto.Field( - proto.BOOL, - number=4, - oneof='visibility_option', - ) - never: bool = proto.Field( - proto.BOOL, - number=5, - oneof='visibility_option', - ) - - route_polyline_points_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=1, - message=VisibilityOption, - ) - estimated_arrival_time_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=2, - message=VisibilityOption, - ) - estimated_task_completion_time_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=3, - message=VisibilityOption, - ) - remaining_driving_distance_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=4, - message=VisibilityOption, - ) - remaining_stop_count_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=5, - message=VisibilityOption, - ) - vehicle_location_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=6, - message=VisibilityOption, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini b/owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/noxfile.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/noxfile.py deleted file mode 100644 index c0bf4d81c131..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery' - -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/fleetengine_delivery_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/fleetengine_delivery_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-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py deleted file mode 100644 index 04dfa5f0bb70..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateTasks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_BatchCreateTasks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_batch_create_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - requests = fleetengine_delivery_v1.CreateTaskRequest() - requests.parent = "parent_value" - requests.task_id = "task_id_value" - requests.task.type_ = "UNAVAILABLE" - requests.task.state = "CLOSED" - - request = fleetengine_delivery_v1.BatchCreateTasksRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_tasks(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_BatchCreateTasks_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py deleted file mode 100644 index e22a2a94aeb1..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateTasks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_BatchCreateTasks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_batch_create_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - requests = fleetengine_delivery_v1.CreateTaskRequest() - requests.parent = "parent_value" - requests.task_id = "task_id_value" - requests.task.type_ = "UNAVAILABLE" - requests.task.state = "CLOSED" - - request = fleetengine_delivery_v1.BatchCreateTasksRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_tasks(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_BatchCreateTasks_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py deleted file mode 100644 index 0c37cfba37dd..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_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 CreateDeliveryVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_create_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( - parent="parent_value", - delivery_vehicle_id="delivery_vehicle_id_value", - ) - - # Make the request - response = await client.create_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py deleted file mode 100644 index 2db42c6068e4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_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 CreateDeliveryVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_create_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( - parent="parent_value", - delivery_vehicle_id="delivery_vehicle_id_value", - ) - - # Make the request - response = client.create_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py deleted file mode 100644 index 057d6ba4de47..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_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 CreateTask -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_CreateTask_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_create_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.CreateTaskRequest( - parent="parent_value", - task_id="task_id_value", - task=task, - ) - - # Make the request - response = await client.create_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_CreateTask_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py deleted file mode 100644 index ab663bc61458..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_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 CreateTask -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_CreateTask_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_create_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.CreateTaskRequest( - parent="parent_value", - task_id="task_id_value", - task=task, - ) - - # Make the request - response = client.create_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_CreateTask_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py deleted file mode 100644 index 7ec99a4b6b6b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_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 GetDeliveryVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_get_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py deleted file mode 100644 index 13994becb4b5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_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 GetDeliveryVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_get_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.get_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_async.py deleted file mode 100644 index 11afdf35a194..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_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 GetTask -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetTask_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_get_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskRequest( - name="name_value", - ) - - # Make the request - response = await client.get_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetTask_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_sync.py deleted file mode 100644 index 47f7f5d20c3b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_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 GetTask -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetTask_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_get_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskRequest( - name="name_value", - ) - - # Make the request - response = client.get_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetTask_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py deleted file mode 100644 index e8f168c07e55..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_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 GetTaskTrackingInfo -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_get_task_tracking_info(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( - name="name_value", - ) - - # Make the request - response = await client.get_task_tracking_info(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py deleted file mode 100644 index aac42ad23bd4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_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 GetTaskTrackingInfo -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_get_task_tracking_info(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( - name="name_value", - ) - - # Make the request - response = client.get_task_tracking_info(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py deleted file mode 100644 index 92cd353762c2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_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 ListDeliveryVehicles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_list_delivery_vehicles(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_delivery_vehicles(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py deleted file mode 100644 index eb7f3d5332fa..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_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 ListDeliveryVehicles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_list_delivery_vehicles(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_delivery_vehicles(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_async.py deleted file mode 100644 index 5a75c67090bb..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_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 ListTasks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_ListTasks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_list_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListTasksRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tasks(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_ListTasks_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_sync.py deleted file mode 100644 index 5fa38d62c1fb..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_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 ListTasks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_ListTasks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_list_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListTasksRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tasks(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_ListTasks_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py deleted file mode 100644 index 48cb75ccb089..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_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 UpdateDeliveryVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_update_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( - ) - - # Make the request - response = await client.update_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py deleted file mode 100644 index b79b67bf7ab0..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_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 UpdateDeliveryVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_update_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( - ) - - # Make the request - response = client.update_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_async.py deleted file mode 100644 index e5b4c9099c2f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_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 UpdateTask -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_UpdateTask_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -async def sample_update_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.UpdateTaskRequest( - task=task, - ) - - # Make the request - response = await client.update_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_UpdateTask_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_sync.py deleted file mode 100644 index cdb247237fa2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_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 UpdateTask -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_UpdateTask_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_delivery_v1 - - -def sample_update_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.UpdateTaskRequest( - task=task, - ) - - # Make the request - response = client.update_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_UpdateTask_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json deleted file mode 100644 index 884ac226d0e4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json +++ /dev/null @@ -1,1665 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "maps.fleetengine.delivery.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-fleetengine-delivery", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.batch_create_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.BatchCreateTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "BatchCreateTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse", - "shortName": "batch_create_tasks" - }, - "description": "Sample for BatchCreateTasks", - "file": "fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_BatchCreateTasks_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.batch_create_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.BatchCreateTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "BatchCreateTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse", - "shortName": "batch_create_tasks" - }, - "description": "Sample for BatchCreateTasks", - "file": "fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_BatchCreateTasks_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.create_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "CreateDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "delivery_vehicle", - "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" - }, - { - "name": "delivery_vehicle_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "create_delivery_vehicle" - }, - "description": "Sample for CreateDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.create_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "CreateDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "delivery_vehicle", - "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" - }, - { - "name": "delivery_vehicle_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "create_delivery_vehicle" - }, - "description": "Sample for CreateDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.create_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "CreateTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.CreateTaskRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "task", - "type": "google.maps.fleetengine_delivery_v1.types.Task" - }, - { - "name": "task_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "create_task" - }, - "description": "Sample for CreateTask", - "file": "fleetengine_v1_generated_delivery_service_create_task_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_CreateTask_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": "fleetengine_v1_generated_delivery_service_create_task_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.create_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "CreateTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.CreateTaskRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "task", - "type": "google.maps.fleetengine_delivery_v1.types.Task" - }, - { - "name": "task_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "create_task" - }, - "description": "Sample for CreateTask", - "file": "fleetengine_v1_generated_delivery_service_create_task_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_CreateTask_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": "fleetengine_v1_generated_delivery_service_create_task_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.get_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "get_delivery_vehicle" - }, - "description": "Sample for GetDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.get_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "get_delivery_vehicle" - }, - "description": "Sample for GetDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.get_task_tracking_info", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTaskTrackingInfo", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetTaskTrackingInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo", - "shortName": "get_task_tracking_info" - }, - "description": "Sample for GetTaskTrackingInfo", - "file": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_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": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.get_task_tracking_info", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTaskTrackingInfo", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetTaskTrackingInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo", - "shortName": "get_task_tracking_info" - }, - "description": "Sample for GetTaskTrackingInfo", - "file": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_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": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.get_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetTaskRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "get_task" - }, - "description": "Sample for GetTask", - "file": "fleetengine_v1_generated_delivery_service_get_task_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetTask_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": "fleetengine_v1_generated_delivery_service_get_task_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.get_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetTaskRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "get_task" - }, - "description": "Sample for GetTask", - "file": "fleetengine_v1_generated_delivery_service_get_task_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetTask_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": "fleetengine_v1_generated_delivery_service_get_task_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.list_delivery_vehicles", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListDeliveryVehicles", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "ListDeliveryVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesAsyncPager", - "shortName": "list_delivery_vehicles" - }, - "description": "Sample for ListDeliveryVehicles", - "file": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_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": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.list_delivery_vehicles", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListDeliveryVehicles", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "ListDeliveryVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesPager", - "shortName": "list_delivery_vehicles" - }, - "description": "Sample for ListDeliveryVehicles", - "file": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_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": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.list_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "ListTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.ListTasksRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksAsyncPager", - "shortName": "list_tasks" - }, - "description": "Sample for ListTasks", - "file": "fleetengine_v1_generated_delivery_service_list_tasks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_ListTasks_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": "fleetengine_v1_generated_delivery_service_list_tasks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.list_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "ListTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.ListTasksRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksPager", - "shortName": "list_tasks" - }, - "description": "Sample for ListTasks", - "file": "fleetengine_v1_generated_delivery_service_list_tasks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_ListTasks_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": "fleetengine_v1_generated_delivery_service_list_tasks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.update_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "UpdateDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest" - }, - { - "name": "delivery_vehicle", - "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" - }, - { - "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, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "update_delivery_vehicle" - }, - "description": "Sample for UpdateDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.update_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "UpdateDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest" - }, - { - "name": "delivery_vehicle", - "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" - }, - { - "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, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "update_delivery_vehicle" - }, - "description": "Sample for UpdateDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_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": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.update_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "UpdateTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest" - }, - { - "name": "task", - "type": "google.maps.fleetengine_delivery_v1.types.Task" - }, - { - "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, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "update_task" - }, - "description": "Sample for UpdateTask", - "file": "fleetengine_v1_generated_delivery_service_update_task_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateTask_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": "fleetengine_v1_generated_delivery_service_update_task_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.update_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "UpdateTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest" - }, - { - "name": "task", - "type": "google.maps.fleetengine_delivery_v1.types.Task" - }, - { - "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, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "update_task" - }, - "description": "Sample for UpdateTask", - "file": "fleetengine_v1_generated_delivery_service_update_task_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateTask_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": "fleetengine_v1_generated_delivery_service_update_task_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py deleted file mode 100644 index 8dc89e72edee..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py +++ /dev/null @@ -1,185 +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 fleetengine_deliveryCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_tasks': ('parent', 'requests', 'header', ), - 'create_delivery_vehicle': ('parent', 'delivery_vehicle_id', 'delivery_vehicle', 'header', ), - 'create_task': ('parent', 'task_id', 'task', 'header', ), - 'get_delivery_vehicle': ('name', 'header', ), - 'get_task': ('name', 'header', ), - 'get_task_tracking_info': ('name', 'header', ), - 'list_delivery_vehicles': ('parent', 'header', 'page_size', 'page_token', 'filter', 'viewport', ), - 'list_tasks': ('parent', 'header', 'page_size', 'page_token', 'filter', ), - 'update_delivery_vehicle': ('delivery_vehicle', 'update_mask', 'header', ), - 'update_task': ('task', 'update_mask', 'header', ), - } - - 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=fleetengine_deliveryCallTransformer(), -): - """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 fleetengine_delivery 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-fleetengine-delivery/v1/setup.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/setup.py deleted file mode 100644 index 7fb3e991da0e..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery' - - -description = "Google Maps Fleetengine Delivery API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/fleetengine_delivery/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-fleetengine-delivery" - -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-fleetengine-delivery/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.7.txt deleted file mode 100644 index 277853c664a0..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/tests/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_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-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py deleted file mode 100644 index d3dae258b7ff..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py +++ /dev/null @@ -1,9124 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.fleetengine_delivery_v1.services.delivery_service import DeliveryServiceAsyncClient -from google.maps.fleetengine_delivery_v1.services.delivery_service import DeliveryServiceClient -from google.maps.fleetengine_delivery_v1.services.delivery_service import pagers -from google.maps.fleetengine_delivery_v1.services.delivery_service import transports -from google.maps.fleetengine_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import header -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_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 DeliveryServiceClient._get_default_mtls_endpoint(None) is None - assert DeliveryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DeliveryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DeliveryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DeliveryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DeliveryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert DeliveryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert DeliveryServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert DeliveryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - DeliveryServiceClient._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 DeliveryServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert DeliveryServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert DeliveryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - DeliveryServiceClient._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 DeliveryServiceClient._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 DeliveryServiceClient._get_client_cert_source(None, False) is None - assert DeliveryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert DeliveryServiceClient._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 DeliveryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert DeliveryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = DeliveryServiceClient._DEFAULT_UNIVERSE - default_endpoint = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert DeliveryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert DeliveryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - assert DeliveryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert DeliveryServiceClient._get_api_endpoint(None, None, default_universe, "always") == DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - assert DeliveryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - assert DeliveryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert DeliveryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - DeliveryServiceClient._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 DeliveryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert DeliveryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert DeliveryServiceClient._get_universe_domain(None, None) == DeliveryServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - DeliveryServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DeliveryServiceClient, "grpc"), - (DeliveryServiceAsyncClient, "grpc_asyncio"), - (DeliveryServiceClient, "rest"), -]) -def test_delivery_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 == ( - 'fleetengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://fleetengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DeliveryServiceGrpcTransport, "grpc"), - (transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DeliveryServiceRestTransport, "rest"), -]) -def test_delivery_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", [ - (DeliveryServiceClient, "grpc"), - (DeliveryServiceAsyncClient, "grpc_asyncio"), - (DeliveryServiceClient, "rest"), -]) -def test_delivery_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 == ( - 'fleetengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://fleetengine.googleapis.com' - ) - - -def test_delivery_service_client_get_transport_class(): - transport = DeliveryServiceClient.get_transport_class() - available_transports = [ - transports.DeliveryServiceGrpcTransport, - transports.DeliveryServiceRestTransport, - ] - assert transport in available_transports - - transport = DeliveryServiceClient.get_transport_class("grpc") - assert transport == transports.DeliveryServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc"), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest"), -]) -@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) -def test_delivery_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(DeliveryServiceClient, '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(DeliveryServiceClient, '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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", "true"), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", "false"), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest", "true"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_delivery_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", [ - DeliveryServiceClient, DeliveryServiceAsyncClient -]) -@mock.patch.object(DeliveryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeliveryServiceAsyncClient)) -def test_delivery_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", [ - DeliveryServiceClient, DeliveryServiceAsyncClient -]) -@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) -def test_delivery_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = DeliveryServiceClient._DEFAULT_UNIVERSE - default_endpoint = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DeliveryServiceClient._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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc"), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest"), -]) -def test_delivery_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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", grpc_helpers), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest", None), -]) -def test_delivery_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_delivery_service_client_client_options_from_dict(): - with mock.patch('google.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DeliveryServiceClient( - 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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", grpc_helpers), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_delivery_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( - "fleetengine.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="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.CreateDeliveryVehicleRequest, - dict, -]) -def test_create_delivery_vehicle(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - response = client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.CreateDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -def test_create_delivery_vehicle_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.CreateDeliveryVehicleRequest( - parent='parent_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_delivery_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.CreateDeliveryVehicleRequest( - parent='parent_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - -def test_create_delivery_vehicle_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_delivery_vehicle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_delivery_vehicle] = mock_rpc - request = {} - client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_delivery_vehicle(request) - - # Establish that a new wrapper 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_delivery_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_delivery_vehicle in client._client._transport._wrapped_methods - - # 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_delivery_vehicle] = mock_rpc - - request = {} - await client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_delivery_vehicle(request) - - # Establish that a new wrapper 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_delivery_vehicle_async(transport: str = 'grpc_asyncio', request_type=delivery_api.CreateDeliveryVehicleRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - response = await client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.CreateDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -@pytest.mark.asyncio -async def test_create_delivery_vehicle_async_from_dict(): - await test_create_delivery_vehicle_async(request_type=dict) - - -def test_create_delivery_vehicle_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_delivery_vehicle( - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_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].delivery_vehicle - mock_val = delivery_vehicles.DeliveryVehicle(name='name_value') - assert arg == mock_val - arg = args[0].delivery_vehicle_id - mock_val = 'delivery_vehicle_id_value' - assert arg == mock_val - - -def test_create_delivery_vehicle_flattened_error(): - client = DeliveryServiceClient( - credentials=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_delivery_vehicle( - delivery_api.CreateDeliveryVehicleRequest(), - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_id_value', - ) - -@pytest.mark.asyncio -async def test_create_delivery_vehicle_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_delivery_vehicle( - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_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].delivery_vehicle - mock_val = delivery_vehicles.DeliveryVehicle(name='name_value') - assert arg == mock_val - arg = args[0].delivery_vehicle_id - mock_val = 'delivery_vehicle_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_delivery_vehicle_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=async_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_delivery_vehicle( - delivery_api.CreateDeliveryVehicleRequest(), - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetDeliveryVehicleRequest, - dict, -]) -def test_get_delivery_vehicle(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - response = client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.GetDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -def test_get_delivery_vehicle_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.GetDeliveryVehicleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_delivery_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetDeliveryVehicleRequest( - name='name_value', - ) - -def test_get_delivery_vehicle_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_delivery_vehicle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_delivery_vehicle] = mock_rpc - request = {} - client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_delivery_vehicle(request) - - # Establish that a new wrapper 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_delivery_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_delivery_vehicle in client._client._transport._wrapped_methods - - # 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_delivery_vehicle] = mock_rpc - - request = {} - await client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_delivery_vehicle(request) - - # Establish that a new wrapper 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_delivery_vehicle_async(transport: str = 'grpc_asyncio', request_type=delivery_api.GetDeliveryVehicleRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - response = await client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.GetDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -@pytest.mark.asyncio -async def test_get_delivery_vehicle_async_from_dict(): - await test_get_delivery_vehicle_async(request_type=dict) - - -def test_get_delivery_vehicle_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_delivery_vehicle( - 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_delivery_vehicle_flattened_error(): - client = DeliveryServiceClient( - credentials=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_delivery_vehicle( - delivery_api.GetDeliveryVehicleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_delivery_vehicle_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_delivery_vehicle( - 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_delivery_vehicle_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=async_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_delivery_vehicle( - delivery_api.GetDeliveryVehicleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.UpdateDeliveryVehicleRequest, - dict, -]) -def test_update_delivery_vehicle(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - response = client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -def test_update_delivery_vehicle_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.UpdateDeliveryVehicleRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_delivery_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateDeliveryVehicleRequest( - ) - -def test_update_delivery_vehicle_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_delivery_vehicle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_delivery_vehicle] = mock_rpc - request = {} - client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_delivery_vehicle(request) - - # Establish that a new wrapper 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_delivery_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_delivery_vehicle in client._client._transport._wrapped_methods - - # 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_delivery_vehicle] = mock_rpc - - request = {} - await client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_delivery_vehicle(request) - - # Establish that a new wrapper 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_delivery_vehicle_async(transport: str = 'grpc_asyncio', request_type=delivery_api.UpdateDeliveryVehicleRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - response = await client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -@pytest.mark.asyncio -async def test_update_delivery_vehicle_async_from_dict(): - await test_update_delivery_vehicle_async(request_type=dict) - - -def test_update_delivery_vehicle_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_delivery_vehicle( - delivery_vehicle=delivery_vehicles.DeliveryVehicle(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].delivery_vehicle - mock_val = delivery_vehicles.DeliveryVehicle(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_delivery_vehicle_flattened_error(): - client = DeliveryServiceClient( - credentials=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_delivery_vehicle( - delivery_api.UpdateDeliveryVehicleRequest(), - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_delivery_vehicle_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_delivery_vehicle( - delivery_vehicle=delivery_vehicles.DeliveryVehicle(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].delivery_vehicle - mock_val = delivery_vehicles.DeliveryVehicle(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_delivery_vehicle_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=async_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_delivery_vehicle( - delivery_api.UpdateDeliveryVehicleRequest(), - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.BatchCreateTasksRequest, - dict, -]) -def test_batch_create_tasks(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.BatchCreateTasksResponse( - ) - response = client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.BatchCreateTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_api.BatchCreateTasksResponse) - - -def test_batch_create_tasks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.BatchCreateTasksRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_tasks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.BatchCreateTasksRequest( - parent='parent_value', - ) - -def test_batch_create_tasks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_tasks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_tasks] = mock_rpc - request = {} - client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_tasks(request) - - # Establish that a new wrapper 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_tasks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_tasks in client._client._transport._wrapped_methods - - # 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_tasks] = mock_rpc - - request = {} - await client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.batch_create_tasks(request) - - # Establish that a new wrapper 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_tasks_async(transport: str = 'grpc_asyncio', request_type=delivery_api.BatchCreateTasksRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.BatchCreateTasksResponse( - )) - response = await client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.BatchCreateTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_api.BatchCreateTasksResponse) - - -@pytest.mark.asyncio -async def test_batch_create_tasks_async_from_dict(): - await test_batch_create_tasks_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.CreateTaskRequest, - dict, -]) -def test_create_task(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - response = client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.CreateTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -def test_create_task_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.CreateTaskRequest( - parent='parent_value', - task_id='task_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_task(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.CreateTaskRequest( - parent='parent_value', - task_id='task_id_value', - ) - -def test_create_task_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_task in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_task] = mock_rpc - request = {} - client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_task(request) - - # Establish that a new wrapper 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_task_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_task in client._client._transport._wrapped_methods - - # 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_task] = mock_rpc - - request = {} - await client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_task(request) - - # Establish that a new wrapper 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_task_async(transport: str = 'grpc_asyncio', request_type=delivery_api.CreateTaskRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - response = await client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.CreateTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -@pytest.mark.asyncio -async def test_create_task_async_from_dict(): - await test_create_task_async(request_type=dict) - - -def test_create_task_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_task( - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_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].task - mock_val = tasks.Task(name='name_value') - assert arg == mock_val - arg = args[0].task_id - mock_val = 'task_id_value' - assert arg == mock_val - - -def test_create_task_flattened_error(): - client = DeliveryServiceClient( - credentials=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_task( - delivery_api.CreateTaskRequest(), - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_id_value', - ) - -@pytest.mark.asyncio -async def test_create_task_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_task( - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_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].task - mock_val = tasks.Task(name='name_value') - assert arg == mock_val - arg = args[0].task_id - mock_val = 'task_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_task_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=async_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_task( - delivery_api.CreateTaskRequest(), - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetTaskRequest, - dict, -]) -def test_get_task(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - response = client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.GetTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -def test_get_task_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.GetTaskRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_task(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetTaskRequest( - name='name_value', - ) - -def test_get_task_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_task in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_task] = mock_rpc - request = {} - client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_task(request) - - # Establish that a new wrapper 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_task_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_task in client._client._transport._wrapped_methods - - # 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_task] = mock_rpc - - request = {} - await client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_task(request) - - # Establish that a new wrapper 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_task_async(transport: str = 'grpc_asyncio', request_type=delivery_api.GetTaskRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - response = await client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.GetTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -@pytest.mark.asyncio -async def test_get_task_async_from_dict(): - await test_get_task_async(request_type=dict) - - -def test_get_task_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_task( - 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_task_flattened_error(): - client = DeliveryServiceClient( - credentials=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_task( - delivery_api.GetTaskRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_task_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_task( - 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_task_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=async_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_task( - delivery_api.GetTaskRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.UpdateTaskRequest, - dict, -]) -def test_update_task(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - response = client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -def test_update_task_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.UpdateTaskRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_task(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateTaskRequest( - ) - -def test_update_task_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_task in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_task] = mock_rpc - request = {} - client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_task(request) - - # Establish that a new wrapper 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_task_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_task in client._client._transport._wrapped_methods - - # 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_task] = mock_rpc - - request = {} - await client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_task(request) - - # Establish that a new wrapper 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_task_async(transport: str = 'grpc_asyncio', request_type=delivery_api.UpdateTaskRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - response = await client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -@pytest.mark.asyncio -async def test_update_task_async_from_dict(): - await test_update_task_async(request_type=dict) - - -def test_update_task_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_task( - task=tasks.Task(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].task - mock_val = tasks.Task(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_task_flattened_error(): - client = DeliveryServiceClient( - credentials=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_task( - delivery_api.UpdateTaskRequest(), - task=tasks.Task(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_task_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_task( - task=tasks.Task(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].task - mock_val = tasks.Task(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_task_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=async_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_task( - delivery_api.UpdateTaskRequest(), - task=tasks.Task(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.ListTasksRequest, - dict, -]) -def test_list_tasks(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListTasksResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.ListTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_tasks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.ListTasksRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_tasks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListTasksRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_tasks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_tasks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_tasks] = mock_rpc - request = {} - client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_tasks(request) - - # Establish that a new wrapper 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_tasks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_tasks in client._client._transport._wrapped_methods - - # 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_tasks] = mock_rpc - - request = {} - await client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_tasks(request) - - # Establish that a new wrapper 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_tasks_async(transport: str = 'grpc_asyncio', request_type=delivery_api.ListTasksRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.ListTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_tasks_async_from_dict(): - await test_list_tasks_async(request_type=dict) - - -def test_list_tasks_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListTasksResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tasks( - 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_tasks_flattened_error(): - client = DeliveryServiceClient( - credentials=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_tasks( - delivery_api.ListTasksRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_tasks_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListTasksResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_tasks( - 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_tasks_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=async_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_tasks( - delivery_api.ListTasksRequest(), - parent='parent_value', - ) - - -def test_list_tasks_pager(transport_name: str = "grpc"): - client = DeliveryServiceClient( - 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_tasks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_tasks(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, tasks.Task) - for i in results) -def test_list_tasks_pages(transport_name: str = "grpc"): - client = DeliveryServiceClient( - 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_tasks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, - ) - pages = list(client.list_tasks(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_tasks_async_pager(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_tasks(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, tasks.Task) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_tasks_async_pages(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - 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_tasks(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", [ - delivery_api.GetTaskTrackingInfoRequest, - dict, -]) -def test_get_task_tracking_info(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = task_tracking_info.TaskTrackingInfo( - name='name_value', - tracking_id='tracking_id_value', - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - ) - response = client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.GetTaskTrackingInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, task_tracking_info.TaskTrackingInfo) - assert response.name == 'name_value' - assert response.tracking_id == 'tracking_id_value' - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - - -def test_get_task_tracking_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 = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.GetTaskTrackingInfoRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_task_tracking_info(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetTaskTrackingInfoRequest( - name='name_value', - ) - -def test_get_task_tracking_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 = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_task_tracking_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_task_tracking_info] = mock_rpc - request = {} - client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_task_tracking_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_task_tracking_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 = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_task_tracking_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_task_tracking_info] = mock_rpc - - request = {} - await client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_task_tracking_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_task_tracking_info_async(transport: str = 'grpc_asyncio', request_type=delivery_api.GetTaskTrackingInfoRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo( - name='name_value', - tracking_id='tracking_id_value', - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - )) - response = await client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.GetTaskTrackingInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, task_tracking_info.TaskTrackingInfo) - assert response.name == 'name_value' - assert response.tracking_id == 'tracking_id_value' - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - - -@pytest.mark.asyncio -async def test_get_task_tracking_info_async_from_dict(): - await test_get_task_tracking_info_async(request_type=dict) - - -def test_get_task_tracking_info_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = task_tracking_info.TaskTrackingInfo() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_task_tracking_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_task_tracking_info_flattened_error(): - client = DeliveryServiceClient( - credentials=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_task_tracking_info( - delivery_api.GetTaskTrackingInfoRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_task_tracking_info_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = task_tracking_info.TaskTrackingInfo() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_task_tracking_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_task_tracking_info_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=async_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_task_tracking_info( - delivery_api.GetTaskTrackingInfoRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.ListDeliveryVehiclesRequest, - dict, -]) -def test_list_delivery_vehicles(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListDeliveryVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.ListDeliveryVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeliveryVehiclesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_delivery_vehicles_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.ListDeliveryVehiclesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_delivery_vehicles(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListDeliveryVehiclesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_delivery_vehicles_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_delivery_vehicles in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_delivery_vehicles] = mock_rpc - request = {} - client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_delivery_vehicles(request) - - # Establish that a new wrapper 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_delivery_vehicles_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_delivery_vehicles in client._client._transport._wrapped_methods - - # 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_delivery_vehicles] = mock_rpc - - request = {} - await client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_delivery_vehicles(request) - - # Establish that a new wrapper 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_delivery_vehicles_async(transport: str = 'grpc_asyncio', request_type=delivery_api.ListDeliveryVehiclesRequest): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.ListDeliveryVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeliveryVehiclesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_delivery_vehicles_async_from_dict(): - await test_list_delivery_vehicles_async(request_type=dict) - - -def test_list_delivery_vehicles_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListDeliveryVehiclesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_delivery_vehicles( - 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_delivery_vehicles_flattened_error(): - client = DeliveryServiceClient( - credentials=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_delivery_vehicles( - delivery_api.ListDeliveryVehiclesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_delivery_vehicles_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListDeliveryVehiclesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_delivery_vehicles( - 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_delivery_vehicles_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=async_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_delivery_vehicles( - delivery_api.ListDeliveryVehiclesRequest(), - parent='parent_value', - ) - - -def test_list_delivery_vehicles_pager(transport_name: str = "grpc"): - client = DeliveryServiceClient( - 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_delivery_vehicles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_delivery_vehicles(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, delivery_vehicles.DeliveryVehicle) - for i in results) -def test_list_delivery_vehicles_pages(transport_name: str = "grpc"): - client = DeliveryServiceClient( - 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_delivery_vehicles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - RuntimeError, - ) - pages = list(client.list_delivery_vehicles(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_delivery_vehicles_async_pager(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_delivery_vehicles(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, delivery_vehicles.DeliveryVehicle) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_delivery_vehicles_async_pages(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - 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_delivery_vehicles(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_delivery_vehicle_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_delivery_vehicle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_delivery_vehicle] = mock_rpc - - request = {} - client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_delivery_vehicle(request) - - # Establish 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_delivery_vehicle_rest_required_fields(request_type=delivery_api.CreateDeliveryVehicleRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["delivery_vehicle_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 "deliveryVehicleId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_delivery_vehicle._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "deliveryVehicleId" in jsonified_request - assert jsonified_request["deliveryVehicleId"] == request_init["delivery_vehicle_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["deliveryVehicleId"] = 'delivery_vehicle_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_delivery_vehicle._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("delivery_vehicle_id", "header", )) - 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 "deliveryVehicleId" in jsonified_request - assert jsonified_request["deliveryVehicleId"] == 'delivery_vehicle_id_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_delivery_vehicle(request) - - expected_params = [ - ( - "deliveryVehicleId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_delivery_vehicle_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_delivery_vehicle._get_unset_required_fields({}) - assert set(unset_fields) == (set(("deliveryVehicleId", "header", )) & set(("parent", "deliveryVehicleId", "deliveryVehicle", ))) - - -def test_create_delivery_vehicle_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'providers/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_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 = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_delivery_vehicle(**mock_args) - - # Establish that the underlying call 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=providers/*}/deliveryVehicles" % client.transport._host, args[1]) - - -def test_create_delivery_vehicle_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.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_delivery_vehicle( - delivery_api.CreateDeliveryVehicleRequest(), - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - -def test_get_delivery_vehicle_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_delivery_vehicle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_delivery_vehicle] = mock_rpc - - request = {} - client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_delivery_vehicle(request) - - # Establish 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_delivery_vehicle_rest_required_fields(request_type=delivery_api.GetDeliveryVehicleRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_delivery_vehicle._get_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_delivery_vehicle._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", )) - jsonified_request.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 = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_delivery_vehicle(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_delivery_vehicle_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_delivery_vehicle._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", )) & set(("name", ))) - - -def test_get_delivery_vehicle_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'providers/sample1/deliveryVehicles/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 = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_delivery_vehicle(**mock_args) - - # Establish that the underlying call 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=providers/*/deliveryVehicles/*}" % client.transport._host, args[1]) - - -def test_get_delivery_vehicle_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.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_delivery_vehicle( - delivery_api.GetDeliveryVehicleRequest(), - name='name_value', - ) - - -def test_update_delivery_vehicle_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_delivery_vehicle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_delivery_vehicle] = mock_rpc - - request = {} - client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_delivery_vehicle(request) - - # Establish 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_delivery_vehicle_rest_required_fields(request_type=delivery_api.UpdateDeliveryVehicleRequest): - transport_class = transports.DeliveryServiceRestTransport - - 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_delivery_vehicle._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_delivery_vehicle._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_delivery_vehicle(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_delivery_vehicle_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_delivery_vehicle._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", "updateMask", )) & set(("deliveryVehicle", "updateMask", ))) - - -def test_update_delivery_vehicle_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - - # get arguments that satisfy an http rule for this method - sample_request = {'delivery_vehicle': {'name': 'providers/sample1/deliveryVehicles/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - delivery_vehicle=delivery_vehicles.DeliveryVehicle(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 = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_delivery_vehicle(**mock_args) - - # Establish that the underlying call 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/{delivery_vehicle.name=providers/*/deliveryVehicles/*}" % client.transport._host, args[1]) - - -def test_update_delivery_vehicle_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.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_delivery_vehicle( - delivery_api.UpdateDeliveryVehicleRequest(), - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_batch_create_tasks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_tasks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_tasks] = mock_rpc - - request = {} - client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_tasks(request) - - # Establish 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_tasks_rest_required_fields(request_type=delivery_api.BatchCreateTasksRequest): - transport_class = transports.DeliveryServiceRestTransport - - 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_tasks._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_tasks._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 = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_api.BatchCreateTasksResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = delivery_api.BatchCreateTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_create_tasks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_tasks_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_tasks._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) - - -def test_create_task_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_task in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_task] = mock_rpc - - request = {} - client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_task(request) - - # Establish 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_task_rest_required_fields(request_type=delivery_api.CreateTaskRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["task_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 "taskId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_task._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "taskId" in jsonified_request - assert jsonified_request["taskId"] == request_init["task_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["taskId"] = 'task_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_task._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", "task_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 "taskId" in jsonified_request - assert jsonified_request["taskId"] == 'task_id_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_task(request) - - expected_params = [ - ( - "taskId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_task_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_task._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", "taskId", )) & set(("parent", "taskId", "task", ))) - - -def test_create_task_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'providers/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_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 = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_task(**mock_args) - - # Establish that the underlying call 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=providers/*}/tasks" % client.transport._host, args[1]) - - -def test_create_task_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.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_task( - delivery_api.CreateTaskRequest(), - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_id_value', - ) - - -def test_get_task_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_task in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_task] = mock_rpc - - request = {} - client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_task(request) - - # Establish 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_task_rest_required_fields(request_type=delivery_api.GetTaskRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_task._get_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_task._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", )) - jsonified_request.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 = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_task(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_task_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_task._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", )) & set(("name", ))) - - -def test_get_task_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'providers/sample1/tasks/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 = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_task(**mock_args) - - # Establish that the underlying call 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=providers/*/tasks/*}" % client.transport._host, args[1]) - - -def test_get_task_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.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_task( - delivery_api.GetTaskRequest(), - name='name_value', - ) - - -def test_update_task_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_task in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_task] = mock_rpc - - request = {} - client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_task(request) - - # Establish 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_task_rest_required_fields(request_type=delivery_api.UpdateTaskRequest): - transport_class = transports.DeliveryServiceRestTransport - - 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_task._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_task._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_task(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_task_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_task._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", "updateMask", )) & set(("task", "updateMask", ))) - - -def test_update_task_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - - # get arguments that satisfy an http rule for this method - sample_request = {'task': {'name': 'providers/sample1/tasks/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - task=tasks.Task(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 = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_task(**mock_args) - - # Establish that the underlying call 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/{task.name=providers/*/tasks/*}" % client.transport._host, args[1]) - - -def test_update_task_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.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_task( - delivery_api.UpdateTaskRequest(), - task=tasks.Task(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_tasks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_tasks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_tasks] = mock_rpc - - request = {} - client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_tasks(request) - - # Establish 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_tasks_rest_required_fields(request_type=delivery_api.ListTasksRequest): - transport_class = transports.DeliveryServiceRestTransport - - 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_tasks._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_tasks._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "header", "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 = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListTasksResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = delivery_api.ListTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_tasks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_tasks_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_tasks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "header", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_tasks_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListTasksResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'providers/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 = delivery_api.ListTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_tasks(**mock_args) - - # Establish that the underlying call 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=providers/*}/tasks" % client.transport._host, args[1]) - - -def test_list_tasks_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.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_tasks( - delivery_api.ListTasksRequest(), - parent='parent_value', - ) - - -def test_list_tasks_rest_pager(transport: str = 'rest'): - client = DeliveryServiceClient( - 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 = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(delivery_api.ListTasksResponse.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': 'providers/sample1'} - - pager = client.list_tasks(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tasks.Task) - for i in results) - - pages = list(client.list_tasks(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_task_tracking_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 = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_task_tracking_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_task_tracking_info] = mock_rpc - - request = {} - client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_task_tracking_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_task_tracking_info_rest_required_fields(request_type=delivery_api.GetTaskTrackingInfoRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_task_tracking_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_task_tracking_info._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", )) - jsonified_request.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 = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = task_tracking_info.TaskTrackingInfo() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = task_tracking_info.TaskTrackingInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_task_tracking_info(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_task_tracking_info_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_task_tracking_info._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", )) & set(("name", ))) - - -def test_get_task_tracking_info_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = task_tracking_info.TaskTrackingInfo() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'providers/sample1/taskTrackingInfo/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 = task_tracking_info.TaskTrackingInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_task_tracking_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/v1/{name=providers/*/taskTrackingInfo/*}" % client.transport._host, args[1]) - - -def test_get_task_tracking_info_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.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_task_tracking_info( - delivery_api.GetTaskTrackingInfoRequest(), - name='name_value', - ) - - -def test_list_delivery_vehicles_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_delivery_vehicles in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_delivery_vehicles] = mock_rpc - - request = {} - client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_delivery_vehicles(request) - - # Establish 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_delivery_vehicles_rest_required_fields(request_type=delivery_api.ListDeliveryVehiclesRequest): - transport_class = transports.DeliveryServiceRestTransport - - 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_delivery_vehicles._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_delivery_vehicles._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "header", "page_size", "page_token", "viewport", )) - 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 = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListDeliveryVehiclesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = delivery_api.ListDeliveryVehiclesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_delivery_vehicles(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_delivery_vehicles_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_delivery_vehicles._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "header", "pageSize", "pageToken", "viewport", )) & set(("parent", ))) - - -def test_list_delivery_vehicles_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListDeliveryVehiclesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'providers/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 = delivery_api.ListDeliveryVehiclesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_delivery_vehicles(**mock_args) - - # Establish that the underlying call 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=providers/*}/deliveryVehicles" % client.transport._host, args[1]) - - -def test_list_delivery_vehicles_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.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_delivery_vehicles( - delivery_api.ListDeliveryVehiclesRequest(), - parent='parent_value', - ) - - -def test_list_delivery_vehicles_rest_pager(transport: str = 'rest'): - client = DeliveryServiceClient( - 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 = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(delivery_api.ListDeliveryVehiclesResponse.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': 'providers/sample1'} - - pager = client.list_delivery_vehicles(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, delivery_vehicles.DeliveryVehicle) - for i in results) - - pages = list(client.list_delivery_vehicles(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.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeliveryServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DeliveryServiceClient( - 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 = DeliveryServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeliveryServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DeliveryServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DeliveryServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DeliveryServiceGrpcTransport, - transports.DeliveryServiceGrpcAsyncIOTransport, - transports.DeliveryServiceRestTransport, -]) -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 = DeliveryServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = DeliveryServiceClient( - 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_delivery_vehicle_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - call.return_value = delivery_vehicles.DeliveryVehicle() - client.create_delivery_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.CreateDeliveryVehicleRequest() - - assert args[0] == request_msg - - -# This 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_delivery_vehicle_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - call.return_value = delivery_vehicles.DeliveryVehicle() - client.get_delivery_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.GetDeliveryVehicleRequest() - - assert args[0] == request_msg - - -# This 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_delivery_vehicle_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - call.return_value = delivery_vehicles.DeliveryVehicle() - client.update_delivery_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.UpdateDeliveryVehicleRequest() - - assert args[0] == request_msg - - -# This 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_tasks_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - call.return_value = delivery_api.BatchCreateTasksResponse() - client.batch_create_tasks(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.BatchCreateTasksRequest() - - assert args[0] == request_msg - - -# This 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_task_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - call.return_value = tasks.Task() - client.create_task(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.CreateTaskRequest() - - assert args[0] == request_msg - - -# This 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_task_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - call.return_value = tasks.Task() - client.get_task(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.GetTaskRequest() - - assert args[0] == request_msg - - -# This 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_task_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - call.return_value = tasks.Task() - client.update_task(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.UpdateTaskRequest() - - assert args[0] == request_msg - - -# This 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_tasks_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - call.return_value = delivery_api.ListTasksResponse() - client.list_tasks(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.ListTasksRequest() - - assert args[0] == request_msg - - -# This 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_task_tracking_info_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - call.return_value = task_tracking_info.TaskTrackingInfo() - client.get_task_tracking_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.GetTaskTrackingInfoRequest() - - assert args[0] == request_msg - - -# This 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_delivery_vehicles_empty_call_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - call.return_value = delivery_api.ListDeliveryVehiclesResponse() - client.list_delivery_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.ListDeliveryVehiclesRequest() - - assert args[0] == request_msg - - -def test_create_delivery_vehicle_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - call.return_value = delivery_vehicles.DeliveryVehicle() - client.create_delivery_vehicle(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.CreateDeliveryVehicleRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_delivery_vehicle_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - call.return_value = delivery_vehicles.DeliveryVehicle() - client.get_delivery_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.GetDeliveryVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_delivery_vehicle_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - call.return_value = delivery_vehicles.DeliveryVehicle() - client.update_delivery_vehicle(request={"delivery_vehicle": {"name": "providers/sample1"}}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.UpdateDeliveryVehicleRequest(**{"delivery_vehicle": {"name": "providers/sample1"}}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_batch_create_tasks_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - call.return_value = delivery_api.BatchCreateTasksResponse() - client.batch_create_tasks(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.BatchCreateTasksRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_create_task_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - call.return_value = tasks.Task() - client.create_task(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.CreateTaskRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_task_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - call.return_value = tasks.Task() - client.get_task(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.GetTaskRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_task_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - call.return_value = tasks.Task() - client.update_task(request={"task": {"name": "providers/sample1"}}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.UpdateTaskRequest(**{"task": {"name": "providers/sample1"}}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_list_tasks_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - call.return_value = delivery_api.ListTasksResponse() - client.list_tasks(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.ListTasksRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_task_tracking_info_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - call.return_value = task_tracking_info.TaskTrackingInfo() - client.get_task_tracking_info(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.GetTaskTrackingInfoRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_list_delivery_vehicles_routing_parameters_request_1_grpc(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - call.return_value = delivery_api.ListDeliveryVehiclesResponse() - client.list_delivery_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.ListDeliveryVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_kind_grpc_asyncio(): - transport = DeliveryServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - 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_delivery_vehicle_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - await client.create_delivery_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.CreateDeliveryVehicleRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_delivery_vehicle_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - await client.get_delivery_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.GetDeliveryVehicleRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_delivery_vehicle_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - await client.update_delivery_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.UpdateDeliveryVehicleRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_tasks_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.BatchCreateTasksResponse( - )) - await client.batch_create_tasks(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.BatchCreateTasksRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_task_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - await client.create_task(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.CreateTaskRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_task_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - await client.get_task(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.GetTaskRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_task_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - await client.update_task(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.UpdateTaskRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_tasks_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_tasks(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.ListTasksRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_task_tracking_info_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo( - name='name_value', - tracking_id='tracking_id_value', - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - )) - await client.get_task_tracking_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.GetTaskTrackingInfoRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_delivery_vehicles_empty_call_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_delivery_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.ListDeliveryVehiclesRequest() - - assert args[0] == request_msg - - -@pytest.mark.asyncio -async def test_create_delivery_vehicle_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - await client.create_delivery_vehicle(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.CreateDeliveryVehicleRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_get_delivery_vehicle_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - await client.get_delivery_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.GetDeliveryVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_update_delivery_vehicle_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - await client.update_delivery_vehicle(request={"delivery_vehicle": {"name": "providers/sample1"}}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.UpdateDeliveryVehicleRequest(**{"delivery_vehicle": {"name": "providers/sample1"}}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_batch_create_tasks_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.BatchCreateTasksResponse( - )) - await client.batch_create_tasks(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.BatchCreateTasksRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_create_task_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - await client.create_task(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.CreateTaskRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_get_task_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - await client.get_task(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.GetTaskRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_update_task_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - await client.update_task(request={"task": {"name": "providers/sample1"}}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.UpdateTaskRequest(**{"task": {"name": "providers/sample1"}}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_list_tasks_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_tasks(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.ListTasksRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_get_task_tracking_info_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo( - name='name_value', - tracking_id='tracking_id_value', - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - )) - await client.get_task_tracking_info(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.GetTaskTrackingInfoRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_list_delivery_vehicles_routing_parameters_request_1_grpc_asyncio(): - client = DeliveryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_delivery_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.ListDeliveryVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_kind_rest(): - transport = DeliveryServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_delivery_vehicle_rest_bad_request(request_type=delivery_api.CreateDeliveryVehicleRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/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 - client.create_delivery_vehicle(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.CreateDeliveryVehicleRequest, - dict, -]) -def test_create_delivery_vehicle_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request_init["delivery_vehicle"] = {'name': 'name_value', 'last_location': {'location': {'latitude': 0.86, 'longitude': 0.971}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {'value': 541}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {'seconds': 751, 'nanos': 543}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'navigation_status': 1, 'current_route_segment': b'current_route_segment_blob', 'current_route_segment_end_point': {}, 'remaining_distance_meters': {}, 'remaining_duration': {'seconds': 751, 'nanos': 543}, 'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {'point': {}}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {'start_time': {}, 'end_time': {}}}], 'state': 1}, 'driving_distance_meters': {}, 'driving_duration': {}, 'path': {}}], 'attributes': [{'key': 'key_value', 'value': 'value_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}], '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 = delivery_api.CreateDeliveryVehicleRequest.meta.fields["delivery_vehicle"] - - 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["delivery_vehicle"].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["delivery_vehicle"][field])): - del request_init["delivery_vehicle"][field][i][subfield] - else: - del request_init["delivery_vehicle"][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 = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_delivery_vehicle(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_delivery_vehicle_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_create_delivery_vehicle") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_create_delivery_vehicle") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.CreateDeliveryVehicleRequest.pb(delivery_api.CreateDeliveryVehicleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = delivery_vehicles.DeliveryVehicle.to_json(delivery_vehicles.DeliveryVehicle()) - req.return_value.content = return_value - - request = delivery_api.CreateDeliveryVehicleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_vehicles.DeliveryVehicle() - - client.create_delivery_vehicle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_delivery_vehicle_rest_bad_request(request_type=delivery_api.GetDeliveryVehicleRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/deliveryVehicles/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 - client.get_delivery_vehicle(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetDeliveryVehicleRequest, - dict, -]) -def test_get_delivery_vehicle_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/deliveryVehicles/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 = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_delivery_vehicle(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_delivery_vehicle_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_get_delivery_vehicle") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_get_delivery_vehicle") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.GetDeliveryVehicleRequest.pb(delivery_api.GetDeliveryVehicleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = delivery_vehicles.DeliveryVehicle.to_json(delivery_vehicles.DeliveryVehicle()) - req.return_value.content = return_value - - request = delivery_api.GetDeliveryVehicleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_vehicles.DeliveryVehicle() - - client.get_delivery_vehicle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_delivery_vehicle_rest_bad_request(request_type=delivery_api.UpdateDeliveryVehicleRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'delivery_vehicle': {'name': 'providers/sample1/deliveryVehicles/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 - client.update_delivery_vehicle(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.UpdateDeliveryVehicleRequest, - dict, -]) -def test_update_delivery_vehicle_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'delivery_vehicle': {'name': 'providers/sample1/deliveryVehicles/sample2'}} - request_init["delivery_vehicle"] = {'name': 'providers/sample1/deliveryVehicles/sample2', 'last_location': {'location': {'latitude': 0.86, 'longitude': 0.971}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {'value': 541}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {'seconds': 751, 'nanos': 543}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'navigation_status': 1, 'current_route_segment': b'current_route_segment_blob', 'current_route_segment_end_point': {}, 'remaining_distance_meters': {}, 'remaining_duration': {'seconds': 751, 'nanos': 543}, 'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {'point': {}}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {'start_time': {}, 'end_time': {}}}], 'state': 1}, 'driving_distance_meters': {}, 'driving_duration': {}, 'path': {}}], 'attributes': [{'key': 'key_value', 'value': 'value_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}], '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 = delivery_api.UpdateDeliveryVehicleRequest.meta.fields["delivery_vehicle"] - - 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["delivery_vehicle"].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["delivery_vehicle"][field])): - del request_init["delivery_vehicle"][field][i][subfield] - else: - del request_init["delivery_vehicle"][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 = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_delivery_vehicle(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_delivery_vehicle_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_update_delivery_vehicle") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_update_delivery_vehicle") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.UpdateDeliveryVehicleRequest.pb(delivery_api.UpdateDeliveryVehicleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = delivery_vehicles.DeliveryVehicle.to_json(delivery_vehicles.DeliveryVehicle()) - req.return_value.content = return_value - - request = delivery_api.UpdateDeliveryVehicleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_vehicles.DeliveryVehicle() - - client.update_delivery_vehicle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_tasks_rest_bad_request(request_type=delivery_api.BatchCreateTasksRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/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 - client.batch_create_tasks(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.BatchCreateTasksRequest, - dict, -]) -def test_batch_create_tasks_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/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 = delivery_api.BatchCreateTasksResponse( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_api.BatchCreateTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_create_tasks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_api.BatchCreateTasksResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_tasks_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_batch_create_tasks") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_batch_create_tasks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.BatchCreateTasksRequest.pb(delivery_api.BatchCreateTasksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = delivery_api.BatchCreateTasksResponse.to_json(delivery_api.BatchCreateTasksResponse()) - req.return_value.content = return_value - - request = delivery_api.BatchCreateTasksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_api.BatchCreateTasksResponse() - - client.batch_create_tasks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_task_rest_bad_request(request_type=delivery_api.CreateTaskRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/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 - client.create_task(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.CreateTaskRequest, - dict, -]) -def test_create_task_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request_init["task"] = {'name': 'name_value', 'type_': 1, 'state': 1, 'task_outcome': 1, 'task_outcome_time': {'seconds': 751, 'nanos': 543}, 'task_outcome_location': {'point': {'latitude': 0.86, 'longitude': 0.971}}, 'task_outcome_location_source': 2, 'tracking_id': 'tracking_id_value', 'delivery_vehicle_id': 'delivery_vehicle_id_value', 'planned_location': {}, 'task_duration': {'seconds': 751, 'nanos': 543}, 'target_time_window': {'start_time': {}, 'end_time': {}}, 'journey_sharing_info': {'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {}}], 'state': 1}, 'driving_distance_meters': {'value': 541}, 'driving_duration': {}, 'path': {}}], 'last_location': {'location': {}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'last_location_snappable': True}, 'task_tracking_view_config': {'route_polyline_points_visibility': {'remaining_stop_count_threshold': 3219, 'duration_until_estimated_arrival_time_threshold': {}, 'remaining_driving_distance_meters_threshold': 4561, 'always': True, 'never': True}, 'estimated_arrival_time_visibility': {}, 'estimated_task_completion_time_visibility': {}, 'remaining_driving_distance_visibility': {}, 'remaining_stop_count_visibility': {}, 'vehicle_location_visibility': {}}, 'attributes': [{'key': 'key_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}]} - # 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 = delivery_api.CreateTaskRequest.meta.fields["task"] - - 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["task"].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["task"][field])): - del request_init["task"][field][i][subfield] - else: - del request_init["task"][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 = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_task(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_task_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_create_task") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_create_task") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.CreateTaskRequest.pb(delivery_api.CreateTaskRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = tasks.Task.to_json(tasks.Task()) - req.return_value.content = return_value - - request = delivery_api.CreateTaskRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tasks.Task() - - client.create_task(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_task_rest_bad_request(request_type=delivery_api.GetTaskRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/tasks/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 - client.get_task(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetTaskRequest, - dict, -]) -def test_get_task_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/tasks/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 = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_task(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_task_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_get_task") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_get_task") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.GetTaskRequest.pb(delivery_api.GetTaskRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = tasks.Task.to_json(tasks.Task()) - req.return_value.content = return_value - - request = delivery_api.GetTaskRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tasks.Task() - - client.get_task(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_task_rest_bad_request(request_type=delivery_api.UpdateTaskRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'task': {'name': 'providers/sample1/tasks/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 - client.update_task(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.UpdateTaskRequest, - dict, -]) -def test_update_task_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'task': {'name': 'providers/sample1/tasks/sample2'}} - request_init["task"] = {'name': 'providers/sample1/tasks/sample2', 'type_': 1, 'state': 1, 'task_outcome': 1, 'task_outcome_time': {'seconds': 751, 'nanos': 543}, 'task_outcome_location': {'point': {'latitude': 0.86, 'longitude': 0.971}}, 'task_outcome_location_source': 2, 'tracking_id': 'tracking_id_value', 'delivery_vehicle_id': 'delivery_vehicle_id_value', 'planned_location': {}, 'task_duration': {'seconds': 751, 'nanos': 543}, 'target_time_window': {'start_time': {}, 'end_time': {}}, 'journey_sharing_info': {'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {}}], 'state': 1}, 'driving_distance_meters': {'value': 541}, 'driving_duration': {}, 'path': {}}], 'last_location': {'location': {}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'last_location_snappable': True}, 'task_tracking_view_config': {'route_polyline_points_visibility': {'remaining_stop_count_threshold': 3219, 'duration_until_estimated_arrival_time_threshold': {}, 'remaining_driving_distance_meters_threshold': 4561, 'always': True, 'never': True}, 'estimated_arrival_time_visibility': {}, 'estimated_task_completion_time_visibility': {}, 'remaining_driving_distance_visibility': {}, 'remaining_stop_count_visibility': {}, 'vehicle_location_visibility': {}}, 'attributes': [{'key': 'key_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}]} - # 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 = delivery_api.UpdateTaskRequest.meta.fields["task"] - - 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["task"].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["task"][field])): - del request_init["task"][field][i][subfield] - else: - del request_init["task"][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 = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_task(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_task_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_update_task") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_update_task") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.UpdateTaskRequest.pb(delivery_api.UpdateTaskRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = tasks.Task.to_json(tasks.Task()) - req.return_value.content = return_value - - request = delivery_api.UpdateTaskRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tasks.Task() - - client.update_task(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tasks_rest_bad_request(request_type=delivery_api.ListTasksRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/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 - client.list_tasks(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.ListTasksRequest, - dict, -]) -def test_list_tasks_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/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 = delivery_api.ListTasksResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_api.ListTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_tasks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tasks_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_list_tasks") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_list_tasks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.ListTasksRequest.pb(delivery_api.ListTasksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = delivery_api.ListTasksResponse.to_json(delivery_api.ListTasksResponse()) - req.return_value.content = return_value - - request = delivery_api.ListTasksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_api.ListTasksResponse() - - client.list_tasks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_task_tracking_info_rest_bad_request(request_type=delivery_api.GetTaskTrackingInfoRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/taskTrackingInfo/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 - client.get_task_tracking_info(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetTaskTrackingInfoRequest, - dict, -]) -def test_get_task_tracking_info_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/taskTrackingInfo/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 = task_tracking_info.TaskTrackingInfo( - name='name_value', - tracking_id='tracking_id_value', - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = task_tracking_info.TaskTrackingInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_task_tracking_info(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, task_tracking_info.TaskTrackingInfo) - assert response.name == 'name_value' - assert response.tracking_id == 'tracking_id_value' - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_task_tracking_info_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_get_task_tracking_info") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_get_task_tracking_info") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.GetTaskTrackingInfoRequest.pb(delivery_api.GetTaskTrackingInfoRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = task_tracking_info.TaskTrackingInfo.to_json(task_tracking_info.TaskTrackingInfo()) - req.return_value.content = return_value - - request = delivery_api.GetTaskTrackingInfoRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = task_tracking_info.TaskTrackingInfo() - - client.get_task_tracking_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_delivery_vehicles_rest_bad_request(request_type=delivery_api.ListDeliveryVehiclesRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/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 - client.list_delivery_vehicles(request) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.ListDeliveryVehiclesRequest, - dict, -]) -def test_list_delivery_vehicles_rest_call_success(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/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 = delivery_api.ListDeliveryVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_api.ListDeliveryVehiclesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_delivery_vehicles(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeliveryVehiclesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_delivery_vehicles_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_list_delivery_vehicles") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_list_delivery_vehicles") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.ListDeliveryVehiclesRequest.pb(delivery_api.ListDeliveryVehiclesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = delivery_api.ListDeliveryVehiclesResponse.to_json(delivery_api.ListDeliveryVehiclesResponse()) - req.return_value.content = return_value - - request = delivery_api.ListDeliveryVehiclesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_api.ListDeliveryVehiclesResponse() - - client.list_delivery_vehicles(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = DeliveryServiceClient( - 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_delivery_vehicle_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - client.create_delivery_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.CreateDeliveryVehicleRequest() - - assert args[0] == request_msg - - -# This 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_delivery_vehicle_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - client.get_delivery_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.GetDeliveryVehicleRequest() - - assert args[0] == request_msg - - -# This 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_delivery_vehicle_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - client.update_delivery_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.UpdateDeliveryVehicleRequest() - - assert args[0] == request_msg - - -# This 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_tasks_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - client.batch_create_tasks(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.BatchCreateTasksRequest() - - assert args[0] == request_msg - - -# This 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_task_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - client.create_task(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.CreateTaskRequest() - - assert args[0] == request_msg - - -# This 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_task_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - client.get_task(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.GetTaskRequest() - - assert args[0] == request_msg - - -# This 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_task_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - client.update_task(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.UpdateTaskRequest() - - assert args[0] == request_msg - - -# This 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_tasks_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - client.list_tasks(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.ListTasksRequest() - - assert args[0] == request_msg - - -# This 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_task_tracking_info_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - client.get_task_tracking_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.GetTaskTrackingInfoRequest() - - assert args[0] == request_msg - - -# This 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_delivery_vehicles_empty_call_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - client.list_delivery_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = delivery_api.ListDeliveryVehiclesRequest() - - assert args[0] == request_msg - - -def test_create_delivery_vehicle_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - client.create_delivery_vehicle(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.CreateDeliveryVehicleRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_delivery_vehicle_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - client.get_delivery_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.GetDeliveryVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_delivery_vehicle_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - client.update_delivery_vehicle(request={"delivery_vehicle": {"name": "providers/sample1"}}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.UpdateDeliveryVehicleRequest(**{"delivery_vehicle": {"name": "providers/sample1"}}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_batch_create_tasks_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - client.batch_create_tasks(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.BatchCreateTasksRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_create_task_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - client.create_task(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.CreateTaskRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_task_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - client.get_task(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.GetTaskRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_task_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - client.update_task(request={"task": {"name": "providers/sample1"}}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.UpdateTaskRequest(**{"task": {"name": "providers/sample1"}}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_list_tasks_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - client.list_tasks(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.ListTasksRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_task_tracking_info_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - client.get_task_tracking_info(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.GetTaskTrackingInfoRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_list_delivery_vehicles_routing_parameters_request_1_rest(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - client.list_delivery_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = delivery_api.ListDeliveryVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DeliveryServiceGrpcTransport, - ) - -def test_delivery_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DeliveryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_delivery_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DeliveryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_delivery_vehicle', - 'get_delivery_vehicle', - 'update_delivery_vehicle', - 'batch_create_tasks', - 'create_task', - 'get_task', - 'update_task', - 'list_tasks', - 'get_task_tracking_info', - 'list_delivery_vehicles', - ) - 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_delivery_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.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DeliveryServiceTransport( - 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_delivery_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.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DeliveryServiceTransport() - adc.assert_called_once() - - -def test_delivery_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) - DeliveryServiceClient() - 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.DeliveryServiceGrpcTransport, - transports.DeliveryServiceGrpcAsyncIOTransport, - ], -) -def test_delivery_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/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DeliveryServiceGrpcTransport, - transports.DeliveryServiceGrpcAsyncIOTransport, - transports.DeliveryServiceRestTransport, - ], -) -def test_delivery_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.DeliveryServiceGrpcTransport, grpc_helpers), - (transports.DeliveryServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_delivery_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( - "fleetengine.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="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DeliveryServiceGrpcTransport, transports.DeliveryServiceGrpcAsyncIOTransport]) -def test_delivery_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_delivery_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.DeliveryServiceRestTransport ( - 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_delivery_service_host_no_port(transport_name): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://fleetengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_delivery_service_host_with_port(transport_name): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://fleetengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_delivery_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DeliveryServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DeliveryServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_delivery_vehicle._session - session2 = client2.transport.create_delivery_vehicle._session - assert session1 != session2 - session1 = client1.transport.get_delivery_vehicle._session - session2 = client2.transport.get_delivery_vehicle._session - assert session1 != session2 - session1 = client1.transport.update_delivery_vehicle._session - session2 = client2.transport.update_delivery_vehicle._session - assert session1 != session2 - session1 = client1.transport.batch_create_tasks._session - session2 = client2.transport.batch_create_tasks._session - assert session1 != session2 - session1 = client1.transport.create_task._session - session2 = client2.transport.create_task._session - assert session1 != session2 - session1 = client1.transport.get_task._session - session2 = client2.transport.get_task._session - assert session1 != session2 - session1 = client1.transport.update_task._session - session2 = client2.transport.update_task._session - assert session1 != session2 - session1 = client1.transport.list_tasks._session - session2 = client2.transport.list_tasks._session - assert session1 != session2 - session1 = client1.transport.get_task_tracking_info._session - session2 = client2.transport.get_task_tracking_info._session - assert session1 != session2 - session1 = client1.transport.list_delivery_vehicles._session - session2 = client2.transport.list_delivery_vehicles._session - assert session1 != session2 -def test_delivery_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DeliveryServiceGrpcTransport( - 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_delivery_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DeliveryServiceGrpcAsyncIOTransport( - 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.DeliveryServiceGrpcTransport, transports.DeliveryServiceGrpcAsyncIOTransport]) -def test_delivery_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.DeliveryServiceGrpcTransport, transports.DeliveryServiceGrpcAsyncIOTransport]) -def test_delivery_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_delivery_vehicle_path(): - provider = "squid" - vehicle = "clam" - expected = "providers/{provider}/deliveryVehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) - actual = DeliveryServiceClient.delivery_vehicle_path(provider, vehicle) - assert expected == actual - - -def test_parse_delivery_vehicle_path(): - expected = { - "provider": "whelk", - "vehicle": "octopus", - } - path = DeliveryServiceClient.delivery_vehicle_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_delivery_vehicle_path(path) - assert expected == actual - -def test_task_path(): - provider = "oyster" - task = "nudibranch" - expected = "providers/{provider}/tasks/{task}".format(provider=provider, task=task, ) - actual = DeliveryServiceClient.task_path(provider, task) - assert expected == actual - - -def test_parse_task_path(): - expected = { - "provider": "cuttlefish", - "task": "mussel", - } - path = DeliveryServiceClient.task_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_task_path(path) - assert expected == actual - -def test_task_tracking_info_path(): - provider = "winkle" - tracking = "nautilus" - expected = "providers/{provider}/taskTrackingInfo/{tracking}".format(provider=provider, tracking=tracking, ) - actual = DeliveryServiceClient.task_tracking_info_path(provider, tracking) - assert expected == actual - - -def test_parse_task_tracking_info_path(): - expected = { - "provider": "scallop", - "tracking": "abalone", - } - path = DeliveryServiceClient.task_tracking_info_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_task_tracking_info_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DeliveryServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DeliveryServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DeliveryServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DeliveryServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DeliveryServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DeliveryServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DeliveryServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DeliveryServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.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 = DeliveryServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DeliveryServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.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.DeliveryServiceTransport, '_prep_wrapped_messages') as prep: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DeliveryServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DeliveryServiceClient.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 = DeliveryServiceClient( - 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 = DeliveryServiceAsyncClient( - 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 = DeliveryServiceClient( - 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 = DeliveryServiceClient( - 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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport), -]) -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-fleetengine/v1/.coveragerc b/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc deleted file mode 100644 index 2611031f9d9f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/fleetengine/__init__.py - google/maps/fleetengine/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-fleetengine/v1/.flake8 b/owl-bot-staging/google-maps-fleetengine/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/MANIFEST.in b/owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in deleted file mode 100644 index 3dcb3007a4fb..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/fleetengine *.py -recursive-include google/maps/fleetengine_v1 *.py diff --git a/owl-bot-staging/google-maps-fleetengine/v1/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/README.rst deleted file mode 100644 index b9bd958ce86c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Fleetengine 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 Fleetengine 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-fleetengine/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/docs/conf.py b/owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py deleted file mode 100644 index de2c2c6df868..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine 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-fleetengine" -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-fleetengine-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-fleetengine.tex", - u"google-maps-fleetengine 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-fleetengine", - u"Google Maps Fleetengine 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-fleetengine", - u"google-maps-fleetengine Documentation", - author, - "google-maps-fleetengine", - "GAPIC library for Google Maps Fleetengine 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-fleetengine/v1/docs/fleetengine_v1/services_.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst deleted file mode 100644 index a23a0eb62775..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Maps Fleetengine v1 API -=========================================== -.. toctree:: - :maxdepth: 2 - - trip_service - vehicle_service diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst deleted file mode 100644 index 9cb42aff9bcf..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -TripService ------------------------------ - -.. automodule:: google.maps.fleetengine_v1.services.trip_service - :members: - :inherited-members: - -.. automodule:: google.maps.fleetengine_v1.services.trip_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst deleted file mode 100644 index 2e980bba2916..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Fleetengine v1 API -======================================== - -.. automodule:: google.maps.fleetengine_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst deleted file mode 100644 index e1bfe924fcca..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -VehicleService --------------------------------- - -.. automodule:: google.maps.fleetengine_v1.services.vehicle_service - :members: - :inherited-members: - -.. automodule:: google.maps.fleetengine_v1.services.vehicle_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst deleted file mode 100644 index 2b0090bf63a3..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - fleetengine_v1/services_ - fleetengine_v1/types_ diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py deleted file mode 100644 index 474efa60eda8..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.fleetengine import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.fleetengine_v1.services.trip_service.client import TripServiceClient -from google.maps.fleetengine_v1.services.trip_service.async_client import TripServiceAsyncClient -from google.maps.fleetengine_v1.services.vehicle_service.client import VehicleServiceClient -from google.maps.fleetengine_v1.services.vehicle_service.async_client import VehicleServiceAsyncClient - -from google.maps.fleetengine_v1.types.fleetengine import TerminalLocation -from google.maps.fleetengine_v1.types.fleetengine import TerminalPointId -from google.maps.fleetengine_v1.types.fleetengine import TripWaypoint -from google.maps.fleetengine_v1.types.fleetengine import VehicleAttribute -from google.maps.fleetengine_v1.types.fleetengine import VehicleLocation -from google.maps.fleetengine_v1.types.fleetengine import LocationSensor -from google.maps.fleetengine_v1.types.fleetengine import NavigationStatus -from google.maps.fleetengine_v1.types.fleetengine import PolylineFormatType -from google.maps.fleetengine_v1.types.fleetengine import TripType -from google.maps.fleetengine_v1.types.fleetengine import WaypointType -from google.maps.fleetengine_v1.types.header import RequestHeader -from google.maps.fleetengine_v1.types.traffic import ConsumableTrafficPolyline -from google.maps.fleetengine_v1.types.traffic import SpeedReadingInterval -from google.maps.fleetengine_v1.types.trip_api import CreateTripRequest -from google.maps.fleetengine_v1.types.trip_api import GetTripRequest -from google.maps.fleetengine_v1.types.trip_api import ReportBillableTripRequest -from google.maps.fleetengine_v1.types.trip_api import SearchTripsRequest -from google.maps.fleetengine_v1.types.trip_api import SearchTripsResponse -from google.maps.fleetengine_v1.types.trip_api import UpdateTripRequest -from google.maps.fleetengine_v1.types.trips import StopLocation -from google.maps.fleetengine_v1.types.trips import Trip -from google.maps.fleetengine_v1.types.trips import BillingPlatformIdentifier -from google.maps.fleetengine_v1.types.trips import TripStatus -from google.maps.fleetengine_v1.types.trips import TripView -from google.maps.fleetengine_v1.types.vehicle_api import CreateVehicleRequest -from google.maps.fleetengine_v1.types.vehicle_api import GetVehicleRequest -from google.maps.fleetengine_v1.types.vehicle_api import ListVehiclesRequest -from google.maps.fleetengine_v1.types.vehicle_api import ListVehiclesResponse -from google.maps.fleetengine_v1.types.vehicle_api import SearchVehiclesRequest -from google.maps.fleetengine_v1.types.vehicle_api import SearchVehiclesResponse -from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleAttributesRequest -from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleAttributesResponse -from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleRequest -from google.maps.fleetengine_v1.types.vehicle_api import VehicleAttributeList -from google.maps.fleetengine_v1.types.vehicle_api import VehicleMatch -from google.maps.fleetengine_v1.types.vehicle_api import Waypoint -from google.maps.fleetengine_v1.types.vehicles import BatteryInfo -from google.maps.fleetengine_v1.types.vehicles import DeviceSettings -from google.maps.fleetengine_v1.types.vehicles import LicensePlate -from google.maps.fleetengine_v1.types.vehicles import TrafficPolylineData -from google.maps.fleetengine_v1.types.vehicles import Vehicle -from google.maps.fleetengine_v1.types.vehicles import VisualTrafficReportPolylineRendering -from google.maps.fleetengine_v1.types.vehicles import BatteryStatus -from google.maps.fleetengine_v1.types.vehicles import LocationPowerSaveMode -from google.maps.fleetengine_v1.types.vehicles import PowerSource -from google.maps.fleetengine_v1.types.vehicles import VehicleState - -__all__ = ('TripServiceClient', - 'TripServiceAsyncClient', - 'VehicleServiceClient', - 'VehicleServiceAsyncClient', - 'TerminalLocation', - 'TerminalPointId', - 'TripWaypoint', - 'VehicleAttribute', - 'VehicleLocation', - 'LocationSensor', - 'NavigationStatus', - 'PolylineFormatType', - 'TripType', - 'WaypointType', - 'RequestHeader', - 'ConsumableTrafficPolyline', - 'SpeedReadingInterval', - 'CreateTripRequest', - 'GetTripRequest', - 'ReportBillableTripRequest', - 'SearchTripsRequest', - 'SearchTripsResponse', - 'UpdateTripRequest', - 'StopLocation', - 'Trip', - 'BillingPlatformIdentifier', - 'TripStatus', - 'TripView', - 'CreateVehicleRequest', - 'GetVehicleRequest', - 'ListVehiclesRequest', - 'ListVehiclesResponse', - 'SearchVehiclesRequest', - 'SearchVehiclesResponse', - 'UpdateVehicleAttributesRequest', - 'UpdateVehicleAttributesResponse', - 'UpdateVehicleRequest', - 'VehicleAttributeList', - 'VehicleMatch', - 'Waypoint', - 'BatteryInfo', - 'DeviceSettings', - 'LicensePlate', - 'TrafficPolylineData', - 'Vehicle', - 'VisualTrafficReportPolylineRendering', - 'BatteryStatus', - 'LocationPowerSaveMode', - 'PowerSource', - 'VehicleState', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/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-fleetengine/v1/google/maps/fleetengine/py.typed b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed deleted file mode 100644 index 47d8e9910cb6..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-fleetengine package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py deleted file mode 100644 index 74f5cd53382b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py +++ /dev/null @@ -1,124 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.fleetengine_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.trip_service import TripServiceClient -from .services.trip_service import TripServiceAsyncClient -from .services.vehicle_service import VehicleServiceClient -from .services.vehicle_service import VehicleServiceAsyncClient - -from .types.fleetengine import TerminalLocation -from .types.fleetengine import TerminalPointId -from .types.fleetengine import TripWaypoint -from .types.fleetengine import VehicleAttribute -from .types.fleetengine import VehicleLocation -from .types.fleetengine import LocationSensor -from .types.fleetengine import NavigationStatus -from .types.fleetengine import PolylineFormatType -from .types.fleetengine import TripType -from .types.fleetengine import WaypointType -from .types.header import RequestHeader -from .types.traffic import ConsumableTrafficPolyline -from .types.traffic import SpeedReadingInterval -from .types.trip_api import CreateTripRequest -from .types.trip_api import GetTripRequest -from .types.trip_api import ReportBillableTripRequest -from .types.trip_api import SearchTripsRequest -from .types.trip_api import SearchTripsResponse -from .types.trip_api import UpdateTripRequest -from .types.trips import StopLocation -from .types.trips import Trip -from .types.trips import BillingPlatformIdentifier -from .types.trips import TripStatus -from .types.trips import TripView -from .types.vehicle_api import CreateVehicleRequest -from .types.vehicle_api import GetVehicleRequest -from .types.vehicle_api import ListVehiclesRequest -from .types.vehicle_api import ListVehiclesResponse -from .types.vehicle_api import SearchVehiclesRequest -from .types.vehicle_api import SearchVehiclesResponse -from .types.vehicle_api import UpdateVehicleAttributesRequest -from .types.vehicle_api import UpdateVehicleAttributesResponse -from .types.vehicle_api import UpdateVehicleRequest -from .types.vehicle_api import VehicleAttributeList -from .types.vehicle_api import VehicleMatch -from .types.vehicle_api import Waypoint -from .types.vehicles import BatteryInfo -from .types.vehicles import DeviceSettings -from .types.vehicles import LicensePlate -from .types.vehicles import TrafficPolylineData -from .types.vehicles import Vehicle -from .types.vehicles import VisualTrafficReportPolylineRendering -from .types.vehicles import BatteryStatus -from .types.vehicles import LocationPowerSaveMode -from .types.vehicles import PowerSource -from .types.vehicles import VehicleState - -__all__ = ( - 'TripServiceAsyncClient', - 'VehicleServiceAsyncClient', -'BatteryInfo', -'BatteryStatus', -'BillingPlatformIdentifier', -'ConsumableTrafficPolyline', -'CreateTripRequest', -'CreateVehicleRequest', -'DeviceSettings', -'GetTripRequest', -'GetVehicleRequest', -'LicensePlate', -'ListVehiclesRequest', -'ListVehiclesResponse', -'LocationPowerSaveMode', -'LocationSensor', -'NavigationStatus', -'PolylineFormatType', -'PowerSource', -'ReportBillableTripRequest', -'RequestHeader', -'SearchTripsRequest', -'SearchTripsResponse', -'SearchVehiclesRequest', -'SearchVehiclesResponse', -'SpeedReadingInterval', -'StopLocation', -'TerminalLocation', -'TerminalPointId', -'TrafficPolylineData', -'Trip', -'TripServiceClient', -'TripStatus', -'TripType', -'TripView', -'TripWaypoint', -'UpdateTripRequest', -'UpdateVehicleAttributesRequest', -'UpdateVehicleAttributesResponse', -'UpdateVehicleRequest', -'Vehicle', -'VehicleAttribute', -'VehicleAttributeList', -'VehicleLocation', -'VehicleMatch', -'VehicleServiceClient', -'VehicleState', -'VisualTrafficReportPolylineRendering', -'Waypoint', -'WaypointType', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json deleted file mode 100644 index 1a6ac8f7d116..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json +++ /dev/null @@ -1,147 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.fleetengine_v1", - "protoPackage": "maps.fleetengine.v1", - "schema": "1.0", - "services": { - "TripService": { - "clients": { - "grpc": { - "libraryClient": "TripServiceClient", - "rpcs": { - "CreateTrip": { - "methods": [ - "create_trip" - ] - }, - "GetTrip": { - "methods": [ - "get_trip" - ] - }, - "ReportBillableTrip": { - "methods": [ - "report_billable_trip" - ] - }, - "SearchTrips": { - "methods": [ - "search_trips" - ] - }, - "UpdateTrip": { - "methods": [ - "update_trip" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TripServiceAsyncClient", - "rpcs": { - "CreateTrip": { - "methods": [ - "create_trip" - ] - }, - "GetTrip": { - "methods": [ - "get_trip" - ] - }, - "ReportBillableTrip": { - "methods": [ - "report_billable_trip" - ] - }, - "SearchTrips": { - "methods": [ - "search_trips" - ] - }, - "UpdateTrip": { - "methods": [ - "update_trip" - ] - } - } - } - } - }, - "VehicleService": { - "clients": { - "grpc": { - "libraryClient": "VehicleServiceClient", - "rpcs": { - "CreateVehicle": { - "methods": [ - "create_vehicle" - ] - }, - "GetVehicle": { - "methods": [ - "get_vehicle" - ] - }, - "ListVehicles": { - "methods": [ - "list_vehicles" - ] - }, - "SearchVehicles": { - "methods": [ - "search_vehicles" - ] - }, - "UpdateVehicle": { - "methods": [ - "update_vehicle" - ] - }, - "UpdateVehicleAttributes": { - "methods": [ - "update_vehicle_attributes" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VehicleServiceAsyncClient", - "rpcs": { - "CreateVehicle": { - "methods": [ - "create_vehicle" - ] - }, - "GetVehicle": { - "methods": [ - "get_vehicle" - ] - }, - "ListVehicles": { - "methods": [ - "list_vehicles" - ] - }, - "SearchVehicles": { - "methods": [ - "search_vehicles" - ] - }, - "UpdateVehicle": { - "methods": [ - "update_vehicle" - ] - }, - "UpdateVehicleAttributes": { - "methods": [ - "update_vehicle_attributes" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_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-fleetengine/v1/google/maps/fleetengine_v1/py.typed b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed deleted file mode 100644 index 47d8e9910cb6..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-fleetengine package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py deleted file mode 100644 index 268b90139486..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_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 TripServiceClient -from .async_client import TripServiceAsyncClient - -__all__ = ( - 'TripServiceClient', - 'TripServiceAsyncClient', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py deleted file mode 100644 index f32fa72743e2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py +++ /dev/null @@ -1,675 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.maps.fleetengine_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.fleetengine_v1.services.trip_service import pagers -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import traffic -from google.maps.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -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.type import latlng_pb2 # type: ignore -from .transports.base import TripServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TripServiceGrpcAsyncIOTransport -from .client import TripServiceClient - - -class TripServiceAsyncClient: - """Trip management service.""" - - _client: TripServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = TripServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TripServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = TripServiceClient._DEFAULT_UNIVERSE - - trip_path = staticmethod(TripServiceClient.trip_path) - parse_trip_path = staticmethod(TripServiceClient.parse_trip_path) - common_billing_account_path = staticmethod(TripServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TripServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TripServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(TripServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(TripServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(TripServiceClient.parse_common_organization_path) - common_project_path = staticmethod(TripServiceClient.common_project_path) - parse_common_project_path = staticmethod(TripServiceClient.parse_common_project_path) - common_location_path = staticmethod(TripServiceClient.common_location_path) - parse_common_location_path = staticmethod(TripServiceClient.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: - TripServiceAsyncClient: The constructed client. - """ - return TripServiceClient.from_service_account_info.__func__(TripServiceAsyncClient, 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: - TripServiceAsyncClient: The constructed client. - """ - return TripServiceClient.from_service_account_file.__func__(TripServiceAsyncClient, 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 TripServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> TripServiceTransport: - """Returns the transport used by the client instance. - - Returns: - TripServiceTransport: 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 = TripServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TripServiceTransport, Callable[..., TripServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the trip 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,TripServiceTransport,Callable[..., TripServiceTransport]]]): - 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 TripServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = TripServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_trip(self, - request: Optional[Union[trip_api.CreateTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Creates a trip in the Fleet Engine and returns the - new trip. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_create_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateTripRequest( - parent="parent_value", - trip_id="trip_id_value", - ) - - # Make the request - response = await client.create_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.CreateTripRequest, dict]]): - The request object. CreateTrip 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.CreateTripRequest): - request = trip_api.CreateTripRequest(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_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_trip(self, - request: Optional[Union[trip_api.GetTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Get information about a single trip. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_get_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetTripRequest( - name="name_value", - ) - - # Make the request - response = await client.get_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.GetTripRequest, dict]]): - The request object. GetTrip 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.GetTripRequest): - request = trip_api.GetTripRequest(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_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def report_billable_trip(self, - request: Optional[Union[trip_api.ReportBillableTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Report billable trip usage. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_report_billable_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.ReportBillableTripRequest( - name="name_value", - country_code="country_code_value", - ) - - # Make the request - await client.report_billable_trip(request=request) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.ReportBillableTripRequest, dict]]): - The request object. ReportBillableTrip 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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, trip_api.ReportBillableTripRequest): - request = trip_api.ReportBillableTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.report_billable_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def search_trips(self, - request: Optional[Union[trip_api.SearchTripsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchTripsAsyncPager: - r"""Get all the trips for a specific vehicle. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_search_trips(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchTripsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_trips(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.SearchTripsRequest, dict]]): - The request object. SearchTrips 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsAsyncPager: - SearchTrips response message. - - 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, trip_api.SearchTripsRequest): - request = trip_api.SearchTripsRequest(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_trips] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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.SearchTripsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_trip(self, - request: Optional[Union[trip_api.UpdateTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Updates trip data. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_update_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateTripRequest( - name="name_value", - ) - - # Make the request - response = await client.update_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.UpdateTripRequest, dict]]): - The request object. UpdateTrip 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.UpdateTripRequest): - request = trip_api.UpdateTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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) -> "TripServiceAsyncClient": - 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__ = ( - "TripServiceAsyncClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py deleted file mode 100644 index f419a120f8ca..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py +++ /dev/null @@ -1,1030 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.maps.fleetengine_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 - -from google.maps.fleetengine_v1.services.trip_service import pagers -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import traffic -from google.maps.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -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.type import latlng_pb2 # type: ignore -from .transports.base import TripServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TripServiceGrpcTransport -from .transports.grpc_asyncio import TripServiceGrpcAsyncIOTransport - - -class TripServiceClientMeta(type): - """Metaclass for the TripService 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[TripServiceTransport]] - _transport_registry["grpc"] = TripServiceGrpcTransport - _transport_registry["grpc_asyncio"] = TripServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[TripServiceTransport]: - """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 TripServiceClient(metaclass=TripServiceClientMeta): - """Trip management service.""" - - @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 = "fleetengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: - TripServiceClient: 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: - TripServiceClient: 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) -> TripServiceTransport: - """Returns the transport used by the client instance. - - Returns: - TripServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def trip_path(provider: str,trip: str,) -> str: - """Returns a fully-qualified trip string.""" - return "providers/{provider}/trips/{trip}".format(provider=provider, trip=trip, ) - - @staticmethod - def parse_trip_path(path: str) -> Dict[str,str]: - """Parses a trip path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/trips/(?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 = TripServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = TripServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = TripServiceClient._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 = TripServiceClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TripServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - TripServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, TripServiceTransport, Callable[..., TripServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the trip 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,TripServiceTransport,Callable[..., TripServiceTransport]]]): - 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 TripServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = TripServiceClient._read_environment_variables() - self._client_cert_source = TripServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = TripServiceClient._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 - - 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, TripServiceTransport) - if transport_provided: - # transport is a TripServiceTransport 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(TripServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - TripServiceClient._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[TripServiceTransport], Callable[..., TripServiceTransport]] = ( - TripServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., TripServiceTransport], 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, - ) - - def create_trip(self, - request: Optional[Union[trip_api.CreateTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Creates a trip in the Fleet Engine and returns the - new trip. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_create_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateTripRequest( - parent="parent_value", - trip_id="trip_id_value", - ) - - # Make the request - response = client.create_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.CreateTripRequest, dict]): - The request object. CreateTrip 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.CreateTripRequest): - request = trip_api.CreateTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_trip(self, - request: Optional[Union[trip_api.GetTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Get information about a single trip. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_get_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetTripRequest( - name="name_value", - ) - - # Make the request - response = client.get_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.GetTripRequest, dict]): - The request object. GetTrip 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.GetTripRequest): - request = trip_api.GetTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def report_billable_trip(self, - request: Optional[Union[trip_api.ReportBillableTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Report billable trip usage. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_report_billable_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.ReportBillableTripRequest( - name="name_value", - country_code="country_code_value", - ) - - # Make the request - client.report_billable_trip(request=request) - - Args: - request (Union[google.maps.fleetengine_v1.types.ReportBillableTripRequest, dict]): - The request object. ReportBillableTrip 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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, trip_api.ReportBillableTripRequest): - request = trip_api.ReportBillableTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.report_billable_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def search_trips(self, - request: Optional[Union[trip_api.SearchTripsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchTripsPager: - r"""Get all the trips for a specific vehicle. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_search_trips(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchTripsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_trips(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.SearchTripsRequest, dict]): - The request object. SearchTrips 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsPager: - SearchTrips response message. - - 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, trip_api.SearchTripsRequest): - request = trip_api.SearchTripsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_trips] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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.SearchTripsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_trip(self, - request: Optional[Union[trip_api.UpdateTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Updates trip data. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_update_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateTripRequest( - name="name_value", - ) - - # Make the request - response = client.update_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.UpdateTripRequest, dict]): - The request object. UpdateTrip 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.UpdateTripRequest): - request = trip_api.UpdateTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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) -> "TripServiceClient": - 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__ = ( - "TripServiceClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py deleted file mode 100644 index 8b5599f99cfa..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py +++ /dev/null @@ -1,163 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips - - -class SearchTripsPager: - """A pager for iterating through ``search_trips`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``trips`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchTrips`` requests and continue to iterate - through the ``trips`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., trip_api.SearchTripsResponse], - request: trip_api.SearchTripsRequest, - response: trip_api.SearchTripsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_v1.types.SearchTripsRequest): - The initial request object. - response (google.maps.fleetengine_v1.types.SearchTripsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = trip_api.SearchTripsRequest(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[trip_api.SearchTripsResponse]: - 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[trips.Trip]: - for page in self.pages: - yield from page.trips - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchTripsAsyncPager: - """A pager for iterating through ``search_trips`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``trips`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchTrips`` requests and continue to iterate - through the ``trips`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` - attributes are available on the 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[trip_api.SearchTripsResponse]], - request: trip_api.SearchTripsRequest, - response: trip_api.SearchTripsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_v1.types.SearchTripsRequest): - The initial request object. - response (google.maps.fleetengine_v1.types.SearchTripsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = trip_api.SearchTripsRequest(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[trip_api.SearchTripsResponse]: - 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[trips.Trip]: - async def async_generator(): - async for page in self.pages: - for response in page.trips: - 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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst deleted file mode 100644 index 97675873407f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`TripServiceTransport` is the ABC for all transports. -- public child `TripServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `TripServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseTripServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `TripServiceRestTransport` 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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py deleted file mode 100644 index 89de6013d759..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 TripServiceTransport -from .grpc import TripServiceGrpcTransport -from .grpc_asyncio import TripServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TripServiceTransport]] -_transport_registry['grpc'] = TripServiceGrpcTransport -_transport_registry['grpc_asyncio'] = TripServiceGrpcAsyncIOTransport - -__all__ = ( - 'TripServiceTransport', - 'TripServiceGrpcTransport', - 'TripServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py deleted file mode 100644 index 71595601d903..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.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. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.maps.fleetengine_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.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class TripServiceTransport(abc.ABC): - """Abstract transport class for TripService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_trip: gapic_v1.method.wrap_method( - self.create_trip, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.get_trip: gapic_v1.method.wrap_method( - self.get_trip, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.report_billable_trip: gapic_v1.method.wrap_method( - self.report_billable_trip, - default_timeout=None, - client_info=client_info, - ), - self.search_trips: gapic_v1.method.wrap_method( - self.search_trips, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_trip: gapic_v1.method.wrap_method( - self.update_trip, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.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_trip(self) -> Callable[ - [trip_api.CreateTripRequest], - Union[ - trips.Trip, - Awaitable[trips.Trip] - ]]: - raise NotImplementedError() - - @property - def get_trip(self) -> Callable[ - [trip_api.GetTripRequest], - Union[ - trips.Trip, - Awaitable[trips.Trip] - ]]: - raise NotImplementedError() - - @property - def report_billable_trip(self) -> Callable[ - [trip_api.ReportBillableTripRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def search_trips(self) -> Callable[ - [trip_api.SearchTripsRequest], - Union[ - trip_api.SearchTripsResponse, - Awaitable[trip_api.SearchTripsResponse] - ]]: - raise NotImplementedError() - - @property - def update_trip(self) -> Callable[ - [trip_api.UpdateTripRequest], - Union[ - trips.Trip, - Awaitable[trips.Trip] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'TripServiceTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py deleted file mode 100644 index 0c20dd7934fc..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py +++ /dev/null @@ -1,377 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.maps.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -from google.protobuf import empty_pb2 # type: ignore -from .base import TripServiceTransport, DEFAULT_CLIENT_INFO - - -class TripServiceGrpcTransport(TripServiceTransport): - """gRPC backend transport for TripService. - - Trip management service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'fleetengine.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: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'fleetengine.googleapis.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_trip(self) -> Callable[ - [trip_api.CreateTripRequest], - trips.Trip]: - r"""Return a callable for the create trip method over gRPC. - - Creates a trip in the Fleet Engine and returns the - new trip. - - Returns: - Callable[[~.CreateTripRequest], - ~.Trip]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_trip' not in self._stubs: - self._stubs['create_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/CreateTrip', - request_serializer=trip_api.CreateTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['create_trip'] - - @property - def get_trip(self) -> Callable[ - [trip_api.GetTripRequest], - trips.Trip]: - r"""Return a callable for the get trip method over gRPC. - - Get information about a single trip. - - Returns: - Callable[[~.GetTripRequest], - ~.Trip]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_trip' not in self._stubs: - self._stubs['get_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/GetTrip', - request_serializer=trip_api.GetTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['get_trip'] - - @property - def report_billable_trip(self) -> Callable[ - [trip_api.ReportBillableTripRequest], - empty_pb2.Empty]: - r"""Return a callable for the report billable trip method over gRPC. - - Report billable trip usage. - - Returns: - Callable[[~.ReportBillableTripRequest], - ~.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 'report_billable_trip' not in self._stubs: - self._stubs['report_billable_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/ReportBillableTrip', - request_serializer=trip_api.ReportBillableTripRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['report_billable_trip'] - - @property - def search_trips(self) -> Callable[ - [trip_api.SearchTripsRequest], - trip_api.SearchTripsResponse]: - r"""Return a callable for the search trips method over gRPC. - - Get all the trips for a specific vehicle. - - Returns: - Callable[[~.SearchTripsRequest], - ~.SearchTripsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_trips' not in self._stubs: - self._stubs['search_trips'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/SearchTrips', - request_serializer=trip_api.SearchTripsRequest.serialize, - response_deserializer=trip_api.SearchTripsResponse.deserialize, - ) - return self._stubs['search_trips'] - - @property - def update_trip(self) -> Callable[ - [trip_api.UpdateTripRequest], - trips.Trip]: - r"""Return a callable for the update trip method over gRPC. - - Updates trip data. - - Returns: - Callable[[~.UpdateTripRequest], - ~.Trip]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_trip' not in self._stubs: - self._stubs['update_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/UpdateTrip', - request_serializer=trip_api.UpdateTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['update_trip'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'TripServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py deleted file mode 100644 index b7b838015e6d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,454 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -from google.protobuf import empty_pb2 # type: ignore -from .base import TripServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import TripServiceGrpcTransport - - -class TripServiceGrpcAsyncIOTransport(TripServiceTransport): - """gRPC AsyncIO backend transport for TripService. - - Trip management service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'fleetengine.googleapis.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 = 'fleetengine.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: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_trip(self) -> Callable[ - [trip_api.CreateTripRequest], - Awaitable[trips.Trip]]: - r"""Return a callable for the create trip method over gRPC. - - Creates a trip in the Fleet Engine and returns the - new trip. - - Returns: - Callable[[~.CreateTripRequest], - Awaitable[~.Trip]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_trip' not in self._stubs: - self._stubs['create_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/CreateTrip', - request_serializer=trip_api.CreateTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['create_trip'] - - @property - def get_trip(self) -> Callable[ - [trip_api.GetTripRequest], - Awaitable[trips.Trip]]: - r"""Return a callable for the get trip method over gRPC. - - Get information about a single trip. - - Returns: - Callable[[~.GetTripRequest], - Awaitable[~.Trip]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_trip' not in self._stubs: - self._stubs['get_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/GetTrip', - request_serializer=trip_api.GetTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['get_trip'] - - @property - def report_billable_trip(self) -> Callable[ - [trip_api.ReportBillableTripRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the report billable trip method over gRPC. - - Report billable trip usage. - - Returns: - Callable[[~.ReportBillableTripRequest], - 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 'report_billable_trip' not in self._stubs: - self._stubs['report_billable_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/ReportBillableTrip', - request_serializer=trip_api.ReportBillableTripRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['report_billable_trip'] - - @property - def search_trips(self) -> Callable[ - [trip_api.SearchTripsRequest], - Awaitable[trip_api.SearchTripsResponse]]: - r"""Return a callable for the search trips method over gRPC. - - Get all the trips for a specific vehicle. - - Returns: - Callable[[~.SearchTripsRequest], - Awaitable[~.SearchTripsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_trips' not in self._stubs: - self._stubs['search_trips'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/SearchTrips', - request_serializer=trip_api.SearchTripsRequest.serialize, - response_deserializer=trip_api.SearchTripsResponse.deserialize, - ) - return self._stubs['search_trips'] - - @property - def update_trip(self) -> Callable[ - [trip_api.UpdateTripRequest], - Awaitable[trips.Trip]]: - r"""Return a callable for the update trip method over gRPC. - - Updates trip data. - - Returns: - Callable[[~.UpdateTripRequest], - Awaitable[~.Trip]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_trip' not in self._stubs: - self._stubs['update_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/UpdateTrip', - request_serializer=trip_api.UpdateTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['update_trip'] - - 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_trip: self._wrap_method( - self.create_trip, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.get_trip: self._wrap_method( - self.get_trip, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.report_billable_trip: self._wrap_method( - self.report_billable_trip, - default_timeout=None, - client_info=client_info, - ), - self.search_trips: self._wrap_method( - self.search_trips, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_trip: self._wrap_method( - self.update_trip, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'TripServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py deleted file mode 100644 index fc6cb2c02da7..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_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 VehicleServiceClient -from .async_client import VehicleServiceAsyncClient - -__all__ = ( - 'VehicleServiceClient', - 'VehicleServiceAsyncClient', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py deleted file mode 100644 index f5dcf834487a..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py +++ /dev/null @@ -1,827 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.maps.fleetengine_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.fleetengine_v1.services.vehicle_service import pagers -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import VehicleServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VehicleServiceGrpcAsyncIOTransport -from .client import VehicleServiceClient - - -class VehicleServiceAsyncClient: - """Vehicle management service.""" - - _client: VehicleServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = VehicleServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = VehicleServiceClient._DEFAULT_UNIVERSE - - vehicle_path = staticmethod(VehicleServiceClient.vehicle_path) - parse_vehicle_path = staticmethod(VehicleServiceClient.parse_vehicle_path) - common_billing_account_path = staticmethod(VehicleServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VehicleServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(VehicleServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(VehicleServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(VehicleServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(VehicleServiceClient.parse_common_organization_path) - common_project_path = staticmethod(VehicleServiceClient.common_project_path) - parse_common_project_path = staticmethod(VehicleServiceClient.parse_common_project_path) - common_location_path = staticmethod(VehicleServiceClient.common_location_path) - parse_common_location_path = staticmethod(VehicleServiceClient.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: - VehicleServiceAsyncClient: The constructed client. - """ - return VehicleServiceClient.from_service_account_info.__func__(VehicleServiceAsyncClient, 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: - VehicleServiceAsyncClient: The constructed client. - """ - return VehicleServiceClient.from_service_account_file.__func__(VehicleServiceAsyncClient, 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 VehicleServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> VehicleServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VehicleServiceTransport: 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 = VehicleServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, VehicleServiceTransport, Callable[..., VehicleServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the vehicle 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,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): - 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 VehicleServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = VehicleServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_vehicle(self, - request: Optional[Union[vehicle_api.CreateVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Instantiates a new vehicle associated with an on-demand - rideshare or deliveries provider. Each ``Vehicle`` must have a - unique vehicle ID. - - The following ``Vehicle`` fields are required when creating a - ``Vehicle``: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - The following ``Vehicle`` fields are ignored when creating a - ``Vehicle``: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_create_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateVehicleRequest( - parent="parent_value", - vehicle_id="vehicle_id_value", - ) - - # Make the request - response = await client.create_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.CreateVehicleRequest, dict]]): - The request object. ``CreateVehicle`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.CreateVehicleRequest): - request = vehicle_api.CreateVehicleRequest(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_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_vehicle(self, - request: Optional[Union[vehicle_api.GetVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Returns a vehicle from the Fleet Engine. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_get_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.GetVehicleRequest, dict]]): - The request object. ``GetVehicle`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.GetVehicleRequest): - request = vehicle_api.GetVehicleRequest(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_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_vehicle(self, - request: Optional[Union[vehicle_api.UpdateVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Writes updated vehicle data to the Fleet Engine. - - When updating a ``Vehicle``, the following fields cannot be - updated since they are managed by the server: - - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment_version`` - - ``waypoints_version`` - - The vehicle ``name`` also cannot be updated. - - If the ``attributes`` field is updated, **all** the vehicle's - attributes are replaced with the attributes provided in the - request. If you want to update only some attributes, see the - ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` - field can be updated, but must contain all the waypoints - currently on the vehicle, and no other waypoints. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_update_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.update_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.UpdateVehicleRequest, dict]]): - The request object. \`UpdateVehicle 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.UpdateVehicleRequest): - request = vehicle_api.UpdateVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_vehicle_attributes(self, - request: Optional[Union[vehicle_api.UpdateVehicleAttributesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.UpdateVehicleAttributesResponse: - r"""Partially updates a vehicle's attributes. Only the attributes - mentioned in the request will be updated, other attributes will - NOT be altered. Note: this is different in ``UpdateVehicle``, - where the whole ``attributes`` field will be replaced by the one - in ``UpdateVehicleRequest``, attributes not in the request would - be removed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_update_vehicle_attributes(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - attributes = fleetengine_v1.VehicleAttribute() - attributes.string_value = "string_value_value" - - request = fleetengine_v1.UpdateVehicleAttributesRequest( - name="name_value", - attributes=attributes, - ) - - # Make the request - response = await client.update_vehicle_attributes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest, dict]]): - The request object. ``UpdateVehicleAttributes`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse: - UpdateVehicleAttributes 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, vehicle_api.UpdateVehicleAttributesRequest): - request = vehicle_api.UpdateVehicleAttributesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_vehicle_attributes] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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_vehicles(self, - request: Optional[Union[vehicle_api.ListVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVehiclesAsyncPager: - r"""Returns a paginated list of vehicles associated with - a provider that match the request options. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_list_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.ListVehiclesRequest( - parent="parent_value", - vehicle_type_categories=['PEDESTRIAN'], - ) - - # Make the request - page_result = client.list_vehicles(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.ListVehiclesRequest, dict]]): - The request object. ``ListVehicles`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesAsyncPager: - ListVehicles response message. - - 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, vehicle_api.ListVehiclesRequest): - request = vehicle_api.ListVehiclesRequest(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_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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.ListVehiclesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_vehicles(self, - request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.SearchVehiclesResponse: - r"""Returns a list of vehicles that match the request - options. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - async def sample_search_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = await client.search_vehicles(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]]): - The request object. ``SearchVehicles`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.SearchVehiclesResponse: - SearchVehicles 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, vehicle_api.SearchVehiclesRequest): - request = vehicle_api.SearchVehiclesRequest(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_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._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) -> "VehicleServiceAsyncClient": - 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__ = ( - "VehicleServiceAsyncClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py deleted file mode 100644 index 7e670b5a6083..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py +++ /dev/null @@ -1,1182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.maps.fleetengine_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 - -from google.maps.fleetengine_v1.services.vehicle_service import pagers -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import VehicleServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VehicleServiceGrpcTransport -from .transports.grpc_asyncio import VehicleServiceGrpcAsyncIOTransport - - -class VehicleServiceClientMeta(type): - """Metaclass for the VehicleService 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[VehicleServiceTransport]] - _transport_registry["grpc"] = VehicleServiceGrpcTransport - _transport_registry["grpc_asyncio"] = VehicleServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[VehicleServiceTransport]: - """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 VehicleServiceClient(metaclass=VehicleServiceClientMeta): - """Vehicle management service.""" - - @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 = "fleetengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: - VehicleServiceClient: 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: - VehicleServiceClient: 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) -> VehicleServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VehicleServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def vehicle_path(provider: str,vehicle: str,) -> str: - """Returns a fully-qualified vehicle string.""" - return "providers/{provider}/vehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) - - @staticmethod - def parse_vehicle_path(path: str) -> Dict[str,str]: - """Parses a vehicle path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/vehicles/(?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 = VehicleServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = VehicleServiceClient._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 = VehicleServiceClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = VehicleServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - VehicleServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, VehicleServiceTransport, Callable[..., VehicleServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the vehicle 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,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): - 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 VehicleServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = VehicleServiceClient._read_environment_variables() - self._client_cert_source = VehicleServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = VehicleServiceClient._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 - - 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, VehicleServiceTransport) - if transport_provided: - # transport is a VehicleServiceTransport 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(VehicleServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - VehicleServiceClient._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[VehicleServiceTransport], Callable[..., VehicleServiceTransport]] = ( - VehicleServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., VehicleServiceTransport], 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, - ) - - def create_vehicle(self, - request: Optional[Union[vehicle_api.CreateVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Instantiates a new vehicle associated with an on-demand - rideshare or deliveries provider. Each ``Vehicle`` must have a - unique vehicle ID. - - The following ``Vehicle`` fields are required when creating a - ``Vehicle``: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - The following ``Vehicle`` fields are ignored when creating a - ``Vehicle``: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_create_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateVehicleRequest( - parent="parent_value", - vehicle_id="vehicle_id_value", - ) - - # Make the request - response = client.create_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.CreateVehicleRequest, dict]): - The request object. ``CreateVehicle`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.CreateVehicleRequest): - request = vehicle_api.CreateVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_vehicle(self, - request: Optional[Union[vehicle_api.GetVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Returns a vehicle from the Fleet Engine. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_get_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.get_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.GetVehicleRequest, dict]): - The request object. ``GetVehicle`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.GetVehicleRequest): - request = vehicle_api.GetVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_vehicle(self, - request: Optional[Union[vehicle_api.UpdateVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Writes updated vehicle data to the Fleet Engine. - - When updating a ``Vehicle``, the following fields cannot be - updated since they are managed by the server: - - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment_version`` - - ``waypoints_version`` - - The vehicle ``name`` also cannot be updated. - - If the ``attributes`` field is updated, **all** the vehicle's - attributes are replaced with the attributes provided in the - request. If you want to update only some attributes, see the - ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` - field can be updated, but must contain all the waypoints - currently on the vehicle, and no other waypoints. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_update_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.update_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.UpdateVehicleRequest, dict]): - The request object. \`UpdateVehicle 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.UpdateVehicleRequest): - request = vehicle_api.UpdateVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_vehicle_attributes(self, - request: Optional[Union[vehicle_api.UpdateVehicleAttributesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.UpdateVehicleAttributesResponse: - r"""Partially updates a vehicle's attributes. Only the attributes - mentioned in the request will be updated, other attributes will - NOT be altered. Note: this is different in ``UpdateVehicle``, - where the whole ``attributes`` field will be replaced by the one - in ``UpdateVehicleRequest``, attributes not in the request would - be removed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_update_vehicle_attributes(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - attributes = fleetengine_v1.VehicleAttribute() - attributes.string_value = "string_value_value" - - request = fleetengine_v1.UpdateVehicleAttributesRequest( - name="name_value", - attributes=attributes, - ) - - # Make the request - response = client.update_vehicle_attributes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest, dict]): - The request object. ``UpdateVehicleAttributes`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse: - UpdateVehicleAttributes 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, vehicle_api.UpdateVehicleAttributesRequest): - request = vehicle_api.UpdateVehicleAttributesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_vehicle_attributes] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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_vehicles(self, - request: Optional[Union[vehicle_api.ListVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVehiclesPager: - r"""Returns a paginated list of vehicles associated with - a provider that match the request options. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_list_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.ListVehiclesRequest( - parent="parent_value", - vehicle_type_categories=['PEDESTRIAN'], - ) - - # Make the request - page_result = client.list_vehicles(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.ListVehiclesRequest, dict]): - The request object. ``ListVehicles`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesPager: - ListVehicles response message. - - 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, vehicle_api.ListVehiclesRequest): - request = vehicle_api.ListVehiclesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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.ListVehiclesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_vehicles(self, - request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.SearchVehiclesResponse: - r"""Returns a list of vehicles that match the request - options. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 fleetengine_v1 - - def sample_search_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = client.search_vehicles(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]): - The request object. ``SearchVehicles`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_v1.types.SearchVehiclesResponse: - SearchVehicles 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, vehicle_api.SearchVehiclesRequest): - request = vehicle_api.SearchVehiclesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe 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) -> "VehicleServiceClient": - 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__ = ( - "VehicleServiceClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py deleted file mode 100644 index a37cce62d28f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py +++ /dev/null @@ -1,163 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles - - -class ListVehiclesPager: - """A pager for iterating through ``list_vehicles`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``vehicles`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListVehicles`` requests and continue to iterate - through the ``vehicles`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., vehicle_api.ListVehiclesResponse], - request: vehicle_api.ListVehiclesRequest, - response: vehicle_api.ListVehiclesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_v1.types.ListVehiclesRequest): - The initial request object. - response (google.maps.fleetengine_v1.types.ListVehiclesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = vehicle_api.ListVehiclesRequest(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[vehicle_api.ListVehiclesResponse]: - 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[vehicles.Vehicle]: - for page in self.pages: - yield from page.vehicles - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListVehiclesAsyncPager: - """A pager for iterating through ``list_vehicles`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``vehicles`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListVehicles`` requests and continue to iterate - through the ``vehicles`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` - attributes are available on the 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[vehicle_api.ListVehiclesResponse]], - request: vehicle_api.ListVehiclesRequest, - response: vehicle_api.ListVehiclesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_v1.types.ListVehiclesRequest): - The initial request object. - response (google.maps.fleetengine_v1.types.ListVehiclesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = vehicle_api.ListVehiclesRequest(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[vehicle_api.ListVehiclesResponse]: - 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[vehicles.Vehicle]: - async def async_generator(): - async for page in self.pages: - for response in page.vehicles: - 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-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst deleted file mode 100644 index cab31a918dfd..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`VehicleServiceTransport` is the ABC for all transports. -- public child `VehicleServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `VehicleServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseVehicleServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `VehicleServiceRestTransport` 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-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py deleted file mode 100644 index 6c5e9251815c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 VehicleServiceTransport -from .grpc import VehicleServiceGrpcTransport -from .grpc_asyncio import VehicleServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VehicleServiceTransport]] -_transport_registry['grpc'] = VehicleServiceGrpcTransport -_transport_registry['grpc_asyncio'] = VehicleServiceGrpcAsyncIOTransport - -__all__ = ( - 'VehicleServiceTransport', - 'VehicleServiceGrpcTransport', - 'VehicleServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py deleted file mode 100644 index 7f3a046bb15d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/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 abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.maps.fleetengine_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.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class VehicleServiceTransport(abc.ABC): - """Abstract transport class for VehicleService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_vehicle: gapic_v1.method.wrap_method( - self.create_vehicle, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.get_vehicle: gapic_v1.method.wrap_method( - self.get_vehicle, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_vehicle: gapic_v1.method.wrap_method( - self.update_vehicle, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_vehicle_attributes: gapic_v1.method.wrap_method( - self.update_vehicle_attributes, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.list_vehicles: gapic_v1.method.wrap_method( - self.list_vehicles, - default_timeout=None, - client_info=client_info, - ), - self.search_vehicles: gapic_v1.method.wrap_method( - self.search_vehicles, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.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_vehicle(self) -> Callable[ - [vehicle_api.CreateVehicleRequest], - Union[ - vehicles.Vehicle, - Awaitable[vehicles.Vehicle] - ]]: - raise NotImplementedError() - - @property - def get_vehicle(self) -> Callable[ - [vehicle_api.GetVehicleRequest], - Union[ - vehicles.Vehicle, - Awaitable[vehicles.Vehicle] - ]]: - raise NotImplementedError() - - @property - def update_vehicle(self) -> Callable[ - [vehicle_api.UpdateVehicleRequest], - Union[ - vehicles.Vehicle, - Awaitable[vehicles.Vehicle] - ]]: - raise NotImplementedError() - - @property - def update_vehicle_attributes(self) -> Callable[ - [vehicle_api.UpdateVehicleAttributesRequest], - Union[ - vehicle_api.UpdateVehicleAttributesResponse, - Awaitable[vehicle_api.UpdateVehicleAttributesResponse] - ]]: - raise NotImplementedError() - - @property - def list_vehicles(self) -> Callable[ - [vehicle_api.ListVehiclesRequest], - Union[ - vehicle_api.ListVehiclesResponse, - Awaitable[vehicle_api.ListVehiclesResponse] - ]]: - raise NotImplementedError() - - @property - def search_vehicles(self) -> Callable[ - [vehicle_api.SearchVehiclesRequest], - Union[ - vehicle_api.SearchVehiclesResponse, - Awaitable[vehicle_api.SearchVehiclesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'VehicleServiceTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py deleted file mode 100644 index 827cc20bd1dd..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py +++ /dev/null @@ -1,455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.maps.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from .base import VehicleServiceTransport, DEFAULT_CLIENT_INFO - - -class VehicleServiceGrpcTransport(VehicleServiceTransport): - """gRPC backend transport for VehicleService. - - Vehicle management service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'fleetengine.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: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'fleetengine.googleapis.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_vehicle(self) -> Callable[ - [vehicle_api.CreateVehicleRequest], - vehicles.Vehicle]: - r"""Return a callable for the create vehicle method over gRPC. - - Instantiates a new vehicle associated with an on-demand - rideshare or deliveries provider. Each ``Vehicle`` must have a - unique vehicle ID. - - The following ``Vehicle`` fields are required when creating a - ``Vehicle``: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - The following ``Vehicle`` fields are ignored when creating a - ``Vehicle``: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - - Returns: - Callable[[~.CreateVehicleRequest], - ~.Vehicle]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicle' not in self._stubs: - self._stubs['create_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/CreateVehicle', - request_serializer=vehicle_api.CreateVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['create_vehicle'] - - @property - def get_vehicle(self) -> Callable[ - [vehicle_api.GetVehicleRequest], - vehicles.Vehicle]: - r"""Return a callable for the get vehicle method over gRPC. - - Returns a vehicle from the Fleet Engine. - - Returns: - Callable[[~.GetVehicleRequest], - ~.Vehicle]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicle' not in self._stubs: - self._stubs['get_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/GetVehicle', - request_serializer=vehicle_api.GetVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['get_vehicle'] - - @property - def update_vehicle(self) -> Callable[ - [vehicle_api.UpdateVehicleRequest], - vehicles.Vehicle]: - r"""Return a callable for the update vehicle method over gRPC. - - Writes updated vehicle data to the Fleet Engine. - - When updating a ``Vehicle``, the following fields cannot be - updated since they are managed by the server: - - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment_version`` - - ``waypoints_version`` - - The vehicle ``name`` also cannot be updated. - - If the ``attributes`` field is updated, **all** the vehicle's - attributes are replaced with the attributes provided in the - request. If you want to update only some attributes, see the - ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` - field can be updated, but must contain all the waypoints - currently on the vehicle, and no other waypoints. - - Returns: - Callable[[~.UpdateVehicleRequest], - ~.Vehicle]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicle' not in self._stubs: - self._stubs['update_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/UpdateVehicle', - request_serializer=vehicle_api.UpdateVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['update_vehicle'] - - @property - def update_vehicle_attributes(self) -> Callable[ - [vehicle_api.UpdateVehicleAttributesRequest], - vehicle_api.UpdateVehicleAttributesResponse]: - r"""Return a callable for the update vehicle attributes method over gRPC. - - Partially updates a vehicle's attributes. Only the attributes - mentioned in the request will be updated, other attributes will - NOT be altered. Note: this is different in ``UpdateVehicle``, - where the whole ``attributes`` field will be replaced by the one - in ``UpdateVehicleRequest``, attributes not in the request would - be removed. - - Returns: - Callable[[~.UpdateVehicleAttributesRequest], - ~.UpdateVehicleAttributesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicle_attributes' not in self._stubs: - self._stubs['update_vehicle_attributes'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/UpdateVehicleAttributes', - request_serializer=vehicle_api.UpdateVehicleAttributesRequest.serialize, - response_deserializer=vehicle_api.UpdateVehicleAttributesResponse.deserialize, - ) - return self._stubs['update_vehicle_attributes'] - - @property - def list_vehicles(self) -> Callable[ - [vehicle_api.ListVehiclesRequest], - vehicle_api.ListVehiclesResponse]: - r"""Return a callable for the list vehicles method over gRPC. - - Returns a paginated list of vehicles associated with - a provider that match the request options. - - Returns: - Callable[[~.ListVehiclesRequest], - ~.ListVehiclesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicles' not in self._stubs: - self._stubs['list_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/ListVehicles', - request_serializer=vehicle_api.ListVehiclesRequest.serialize, - response_deserializer=vehicle_api.ListVehiclesResponse.deserialize, - ) - return self._stubs['list_vehicles'] - - @property - def search_vehicles(self) -> Callable[ - [vehicle_api.SearchVehiclesRequest], - vehicle_api.SearchVehiclesResponse]: - r"""Return a callable for the search vehicles method over gRPC. - - Returns a list of vehicles that match the request - options. - - Returns: - Callable[[~.SearchVehiclesRequest], - ~.SearchVehiclesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicles' not in self._stubs: - self._stubs['search_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/SearchVehicles', - request_serializer=vehicle_api.SearchVehiclesRequest.serialize, - response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, - ) - return self._stubs['search_vehicles'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'VehicleServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py deleted file mode 100644 index 952dd0c816f8..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,546 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from .base import VehicleServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import VehicleServiceGrpcTransport - - -class VehicleServiceGrpcAsyncIOTransport(VehicleServiceTransport): - """gRPC AsyncIO backend transport for VehicleService. - - Vehicle management service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'fleetengine.googleapis.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 = 'fleetengine.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: 'fleetengine.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_vehicle(self) -> Callable[ - [vehicle_api.CreateVehicleRequest], - Awaitable[vehicles.Vehicle]]: - r"""Return a callable for the create vehicle method over gRPC. - - Instantiates a new vehicle associated with an on-demand - rideshare or deliveries provider. Each ``Vehicle`` must have a - unique vehicle ID. - - The following ``Vehicle`` fields are required when creating a - ``Vehicle``: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - The following ``Vehicle`` fields are ignored when creating a - ``Vehicle``: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - - Returns: - Callable[[~.CreateVehicleRequest], - Awaitable[~.Vehicle]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicle' not in self._stubs: - self._stubs['create_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/CreateVehicle', - request_serializer=vehicle_api.CreateVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['create_vehicle'] - - @property - def get_vehicle(self) -> Callable[ - [vehicle_api.GetVehicleRequest], - Awaitable[vehicles.Vehicle]]: - r"""Return a callable for the get vehicle method over gRPC. - - Returns a vehicle from the Fleet Engine. - - Returns: - Callable[[~.GetVehicleRequest], - Awaitable[~.Vehicle]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicle' not in self._stubs: - self._stubs['get_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/GetVehicle', - request_serializer=vehicle_api.GetVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['get_vehicle'] - - @property - def update_vehicle(self) -> Callable[ - [vehicle_api.UpdateVehicleRequest], - Awaitable[vehicles.Vehicle]]: - r"""Return a callable for the update vehicle method over gRPC. - - Writes updated vehicle data to the Fleet Engine. - - When updating a ``Vehicle``, the following fields cannot be - updated since they are managed by the server: - - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment_version`` - - ``waypoints_version`` - - The vehicle ``name`` also cannot be updated. - - If the ``attributes`` field is updated, **all** the vehicle's - attributes are replaced with the attributes provided in the - request. If you want to update only some attributes, see the - ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` - field can be updated, but must contain all the waypoints - currently on the vehicle, and no other waypoints. - - Returns: - Callable[[~.UpdateVehicleRequest], - Awaitable[~.Vehicle]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicle' not in self._stubs: - self._stubs['update_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/UpdateVehicle', - request_serializer=vehicle_api.UpdateVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['update_vehicle'] - - @property - def update_vehicle_attributes(self) -> Callable[ - [vehicle_api.UpdateVehicleAttributesRequest], - Awaitable[vehicle_api.UpdateVehicleAttributesResponse]]: - r"""Return a callable for the update vehicle attributes method over gRPC. - - Partially updates a vehicle's attributes. Only the attributes - mentioned in the request will be updated, other attributes will - NOT be altered. Note: this is different in ``UpdateVehicle``, - where the whole ``attributes`` field will be replaced by the one - in ``UpdateVehicleRequest``, attributes not in the request would - be removed. - - Returns: - Callable[[~.UpdateVehicleAttributesRequest], - Awaitable[~.UpdateVehicleAttributesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicle_attributes' not in self._stubs: - self._stubs['update_vehicle_attributes'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/UpdateVehicleAttributes', - request_serializer=vehicle_api.UpdateVehicleAttributesRequest.serialize, - response_deserializer=vehicle_api.UpdateVehicleAttributesResponse.deserialize, - ) - return self._stubs['update_vehicle_attributes'] - - @property - def list_vehicles(self) -> Callable[ - [vehicle_api.ListVehiclesRequest], - Awaitable[vehicle_api.ListVehiclesResponse]]: - r"""Return a callable for the list vehicles method over gRPC. - - Returns a paginated list of vehicles associated with - a provider that match the request options. - - Returns: - Callable[[~.ListVehiclesRequest], - Awaitable[~.ListVehiclesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicles' not in self._stubs: - self._stubs['list_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/ListVehicles', - request_serializer=vehicle_api.ListVehiclesRequest.serialize, - response_deserializer=vehicle_api.ListVehiclesResponse.deserialize, - ) - return self._stubs['list_vehicles'] - - @property - def search_vehicles(self) -> Callable[ - [vehicle_api.SearchVehiclesRequest], - Awaitable[vehicle_api.SearchVehiclesResponse]]: - r"""Return a callable for the search vehicles method over gRPC. - - Returns a list of vehicles that match the request - options. - - Returns: - Callable[[~.SearchVehiclesRequest], - Awaitable[~.SearchVehiclesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vehicles' not in self._stubs: - self._stubs['search_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/SearchVehicles', - request_serializer=vehicle_api.SearchVehiclesRequest.serialize, - response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, - ) - return self._stubs['search_vehicles'] - - 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_vehicle: self._wrap_method( - self.create_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.get_vehicle: self._wrap_method( - self.get_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_vehicle: self._wrap_method( - self.update_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_vehicle_attributes: self._wrap_method( - self.update_vehicle_attributes, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.list_vehicles: self._wrap_method( - self.list_vehicles, - default_timeout=None, - client_info=client_info, - ), - self.search_vehicles: self._wrap_method( - self.search_vehicles, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'VehicleServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py deleted file mode 100644 index cba18024bd88..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py +++ /dev/null @@ -1,124 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .fleetengine import ( - TerminalLocation, - TerminalPointId, - TripWaypoint, - VehicleAttribute, - VehicleLocation, - LocationSensor, - NavigationStatus, - PolylineFormatType, - TripType, - WaypointType, -) -from .header import ( - RequestHeader, -) -from .traffic import ( - ConsumableTrafficPolyline, - SpeedReadingInterval, -) -from .trip_api import ( - CreateTripRequest, - GetTripRequest, - ReportBillableTripRequest, - SearchTripsRequest, - SearchTripsResponse, - UpdateTripRequest, -) -from .trips import ( - StopLocation, - Trip, - BillingPlatformIdentifier, - TripStatus, - TripView, -) -from .vehicle_api import ( - CreateVehicleRequest, - GetVehicleRequest, - ListVehiclesRequest, - ListVehiclesResponse, - SearchVehiclesRequest, - SearchVehiclesResponse, - UpdateVehicleAttributesRequest, - UpdateVehicleAttributesResponse, - UpdateVehicleRequest, - VehicleAttributeList, - VehicleMatch, - Waypoint, -) -from .vehicles import ( - BatteryInfo, - DeviceSettings, - LicensePlate, - TrafficPolylineData, - Vehicle, - VisualTrafficReportPolylineRendering, - BatteryStatus, - LocationPowerSaveMode, - PowerSource, - VehicleState, -) - -__all__ = ( - 'TerminalLocation', - 'TerminalPointId', - 'TripWaypoint', - 'VehicleAttribute', - 'VehicleLocation', - 'LocationSensor', - 'NavigationStatus', - 'PolylineFormatType', - 'TripType', - 'WaypointType', - 'RequestHeader', - 'ConsumableTrafficPolyline', - 'SpeedReadingInterval', - 'CreateTripRequest', - 'GetTripRequest', - 'ReportBillableTripRequest', - 'SearchTripsRequest', - 'SearchTripsResponse', - 'UpdateTripRequest', - 'StopLocation', - 'Trip', - 'BillingPlatformIdentifier', - 'TripStatus', - 'TripView', - 'CreateVehicleRequest', - 'GetVehicleRequest', - 'ListVehiclesRequest', - 'ListVehiclesResponse', - 'SearchVehiclesRequest', - 'SearchVehiclesResponse', - 'UpdateVehicleAttributesRequest', - 'UpdateVehicleAttributesResponse', - 'UpdateVehicleRequest', - 'VehicleAttributeList', - 'VehicleMatch', - 'Waypoint', - 'BatteryInfo', - 'DeviceSettings', - 'LicensePlate', - 'TrafficPolylineData', - 'Vehicle', - 'VisualTrafficReportPolylineRendering', - 'BatteryStatus', - 'LocationPowerSaveMode', - 'PowerSource', - 'VehicleState', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py deleted file mode 100644 index 95fe3f592984..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py +++ /dev/null @@ -1,628 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.fleetengine_v1.types import traffic -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.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'TripType', - 'WaypointType', - 'PolylineFormatType', - 'NavigationStatus', - 'LocationSensor', - 'TerminalPointId', - 'TerminalLocation', - 'TripWaypoint', - 'VehicleAttribute', - 'VehicleLocation', - }, -) - - -class TripType(proto.Enum): - r"""The type of a trip. - - Values: - UNKNOWN_TRIP_TYPE (0): - Default, used for unspecified or unrecognized - trip types. - SHARED (1): - The trip may share a vehicle with other - trips. - EXCLUSIVE (2): - The trip is exclusive to a vehicle. - """ - UNKNOWN_TRIP_TYPE = 0 - SHARED = 1 - EXCLUSIVE = 2 - - -class WaypointType(proto.Enum): - r"""The type of waypoint. - - Values: - UNKNOWN_WAYPOINT_TYPE (0): - Unknown or unspecified waypoint type. - PICKUP_WAYPOINT_TYPE (1): - Waypoints for picking up riders or items. - DROP_OFF_WAYPOINT_TYPE (2): - Waypoints for dropping off riders or items. - INTERMEDIATE_DESTINATION_WAYPOINT_TYPE (3): - Waypoints for intermediate destinations in a - multi-destination trip. - """ - UNKNOWN_WAYPOINT_TYPE = 0 - PICKUP_WAYPOINT_TYPE = 1 - DROP_OFF_WAYPOINT_TYPE = 2 - INTERMEDIATE_DESTINATION_WAYPOINT_TYPE = 3 - - -class PolylineFormatType(proto.Enum): - r"""The type of polyline format. - - Values: - UNKNOWN_FORMAT_TYPE (0): - The format is unspecified or unknown. - LAT_LNG_LIST_TYPE (1): - A list of ``google.type.LatLng``. - ENCODED_POLYLINE_TYPE (2): - A polyline encoded with a polyline - compression algorithm. Decoding is not yet - supported. - """ - UNKNOWN_FORMAT_TYPE = 0 - LAT_LNG_LIST_TYPE = 1 - ENCODED_POLYLINE_TYPE = 2 - - -class NavigationStatus(proto.Enum): - r"""The vehicle's navigation status. - - Values: - UNKNOWN_NAVIGATION_STATUS (0): - Unspecified navigation status. - NO_GUIDANCE (1): - The Driver app's navigation is in ``FREE_NAV`` mode. - ENROUTE_TO_DESTINATION (2): - Turn-by-turn navigation is available and the Driver app - navigation has entered ``GUIDED_NAV`` mode. - OFF_ROUTE (3): - The vehicle has gone off the suggested route. - ARRIVED_AT_DESTINATION (4): - The vehicle is within approximately 50m of - the destination. - """ - UNKNOWN_NAVIGATION_STATUS = 0 - NO_GUIDANCE = 1 - ENROUTE_TO_DESTINATION = 2 - OFF_ROUTE = 3 - ARRIVED_AT_DESTINATION = 4 - - -class LocationSensor(proto.Enum): - r"""The sensor or methodology used to determine the location. - - Values: - UNKNOWN_SENSOR (0): - The sensor is unspecified or unknown. - GPS (1): - GPS or Assisted GPS. - NETWORK (2): - Assisted GPS, cell tower ID, or WiFi access - point. - PASSIVE (3): - Cell tower ID or WiFi access point. - ROAD_SNAPPED_LOCATION_PROVIDER (4): - A location determined by the mobile device to - be the most likely road position. - CUSTOMER_SUPPLIED_LOCATION (5): - A customer-supplied location from an independent source. - Typically, this value is used for a location provided from - sources other than the mobile device running Driver SDK. If - the original source is described by one of the other enum - values, use that value. Locations marked - CUSTOMER_SUPPLIED_LOCATION are typically provided via a - Vehicle's ``last_location.supplemental_location_sensor``. - FLEET_ENGINE_LOCATION (6): - A location calculated by Fleet Engine based - on the signals available to it. Output only. - This value will be rejected if it is received in - a request. - FUSED_LOCATION_PROVIDER (100): - Android's Fused Location Provider. - CORE_LOCATION (200): - The location provider on Apple operating - systems. - """ - UNKNOWN_SENSOR = 0 - GPS = 1 - NETWORK = 2 - PASSIVE = 3 - ROAD_SNAPPED_LOCATION_PROVIDER = 4 - CUSTOMER_SUPPLIED_LOCATION = 5 - FLEET_ENGINE_LOCATION = 6 - FUSED_LOCATION_PROVIDER = 100 - CORE_LOCATION = 200 - - -class TerminalPointId(proto.Message): - r"""Deprecated: TerminalPoints are no longer supported in Fleet Engine. - Use ``TerminalLocation.point`` instead. - - 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_id (str): - Deprecated. - - This field is a member of `oneof`_ ``Id``. - generated_id (str): - Deprecated. - - This field is a member of `oneof`_ ``Id``. - value (str): - Deprecated. - """ - - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='Id', - ) - generated_id: str = proto.Field( - proto.STRING, - number=3, - oneof='Id', - ) - value: str = proto.Field( - proto.STRING, - number=4, - ) - - -class TerminalLocation(proto.Message): - r"""Describes the location of a waypoint. - - Attributes: - point (google.type.latlng_pb2.LatLng): - Required. Denotes the location of a trip - waypoint. - terminal_point_id (google.maps.fleetengine_v1.types.TerminalPointId): - Deprecated: Specify the ``point`` field instead. - access_point_id (str): - Deprecated: Specify the ``point`` field instead. - trip_id (str): - Deprecated. - terminal_location_type (google.maps.fleetengine_v1.types.WaypointType): - Deprecated: ``Vehicle.waypoint`` will have this data. - """ - - point: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - terminal_point_id: 'TerminalPointId' = proto.Field( - proto.MESSAGE, - number=2, - message='TerminalPointId', - ) - access_point_id: str = proto.Field( - proto.STRING, - number=3, - ) - trip_id: str = proto.Field( - proto.STRING, - number=4, - ) - terminal_location_type: 'WaypointType' = proto.Field( - proto.ENUM, - number=5, - enum='WaypointType', - ) - - -class TripWaypoint(proto.Message): - r"""Describes a stopping point on a vehicle's route or an ending - point on a vehicle's trip. - - Attributes: - location (google.maps.fleetengine_v1.types.TerminalLocation): - The location of this waypoint. - trip_id (str): - The trip associated with this waypoint. - waypoint_type (google.maps.fleetengine_v1.types.WaypointType): - The role this waypoint plays in this trip, - such as pickup or dropoff. - path_to_waypoint (MutableSequence[google.type.latlng_pb2.LatLng]): - The path from the previous waypoint to the - current waypoint. Undefined for the first - waypoint in a list. This field is only populated - when requested. - encoded_path_to_waypoint (str): - The encoded path from the previous waypoint - to the current waypoint. -

Note: This field is intended only for use by - the Driver SDK and Consumer SDK. Decoding is not - yet supported. - traffic_to_waypoint (google.maps.fleetengine_v1.types.ConsumableTrafficPolyline): - The traffic conditions along the path to this - waypoint. Note that traffic is only available - for Google Map Platform Rides and Deliveries - Solution customers. - distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The path distance from the previous waypoint - to the current waypoint. Undefined for the first - waypoint in a list. - eta (google.protobuf.timestamp_pb2.Timestamp): - The estimated time of arrival at this - waypoint. Undefined for the first waypoint in a - list. - duration (google.protobuf.duration_pb2.Duration): - The travel time from previous waypoint to - this point. Undefined for the first waypoint in - a list. - """ - - location: 'TerminalLocation' = proto.Field( - proto.MESSAGE, - number=1, - message='TerminalLocation', - ) - trip_id: str = proto.Field( - proto.STRING, - number=2, - ) - waypoint_type: 'WaypointType' = proto.Field( - proto.ENUM, - number=3, - enum='WaypointType', - ) - path_to_waypoint: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=latlng_pb2.LatLng, - ) - encoded_path_to_waypoint: str = proto.Field( - proto.STRING, - number=5, - ) - traffic_to_waypoint: traffic.ConsumableTrafficPolyline = proto.Field( - proto.MESSAGE, - number=10, - message=traffic.ConsumableTrafficPolyline, - ) - distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int32Value, - ) - eta: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -class VehicleAttribute(proto.Message): - r"""Describes a vehicle attribute as a key-value pair. The - "key:value" string length cannot exceed 256 characters. - - 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: - key (str): - The attribute's key. Keys may not contain the - colon character (:). - value (str): - The attribute's value. - string_value (str): - String typed attribute value. - - Note: This is identical to the ``value`` field which will - eventually be deprecated. For create or update methods, - either field can be used, but it's strongly recommended to - use ``string_value``. If both ``string_value`` and ``value`` - are set, they must be identical or an error will be thrown. - Both fields are populated in responses. - - This field is a member of `oneof`_ ``vehicle_attribute_value``. - bool_value (bool): - Boolean typed attribute value. - - This field is a member of `oneof`_ ``vehicle_attribute_value``. - number_value (float): - Double typed attribute value. - - This field is a member of `oneof`_ ``vehicle_attribute_value``. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - string_value: str = proto.Field( - proto.STRING, - number=3, - oneof='vehicle_attribute_value', - ) - bool_value: bool = proto.Field( - proto.BOOL, - number=4, - oneof='vehicle_attribute_value', - ) - number_value: float = proto.Field( - proto.DOUBLE, - number=5, - oneof='vehicle_attribute_value', - ) - - -class VehicleLocation(proto.Message): - r"""The location, speed, and heading of a vehicle at a point in - time. - - Attributes: - location (google.type.latlng_pb2.LatLng): - The location of the vehicle. When it is sent to Fleet - Engine, the vehicle's location is a GPS location. When you - receive it in a response, the vehicle's location can be - either a GPS location, a supplemental location, or some - other estimated location. The source is specified in - ``location_sensor``. - horizontal_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Deprecated: Use ``latlng_accuracy`` instead. - latlng_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``location`` in meters as a radius. - heading (google.protobuf.wrappers_pb2.Int32Value): - Direction the vehicle is moving in degrees. 0 represents - North. The valid range is [0,360). - bearing_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Deprecated: Use ``heading_accuracy`` instead. - heading_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``heading`` in degrees. - altitude (google.protobuf.wrappers_pb2.DoubleValue): - Altitude in meters above WGS84. - vertical_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Deprecated: Use ``altitude_accuracy`` instead. - altitude_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``altitude`` in meters. - speed_kmph (google.protobuf.wrappers_pb2.Int32Value): - Speed of the vehicle in kilometers per hour. Deprecated: Use - ``speed`` instead. - speed (google.protobuf.wrappers_pb2.DoubleValue): - Speed of the vehicle in meters/second - speed_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``speed`` in meters/second. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when ``location`` was reported by the sensor - according to the sensor's clock. - server_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the server - received the location information. - location_sensor (google.maps.fleetengine_v1.types.LocationSensor): - Provider of location data (for example, ``GPS``). - is_road_snapped (google.protobuf.wrappers_pb2.BoolValue): - Whether ``location`` is snapped to a road. - is_gps_sensor_enabled (google.protobuf.wrappers_pb2.BoolValue): - Input only. Indicates whether the GPS sensor - is enabled on the mobile device. - time_since_update (google.protobuf.wrappers_pb2.Int32Value): - Input only. Time (in seconds) since this - location was first sent to the server. This will - be zero for the first update. If the time is - unknown (for example, when the app restarts), - this value resets to zero. - num_stale_updates (google.protobuf.wrappers_pb2.Int32Value): - Input only. Deprecated: Other signals are now - used to determine if a location is stale. - raw_location (google.type.latlng_pb2.LatLng): - Raw vehicle location (unprocessed by - road-snapper). - raw_location_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp associated with the raw location. - raw_location_sensor (google.maps.fleetengine_v1.types.LocationSensor): - Source of the raw location. Defaults to ``GPS``. - raw_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``raw_location`` as a radius, in meters. - supplemental_location (google.type.latlng_pb2.LatLng): - Supplemental location provided by the - integrating app. - supplemental_location_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp associated with the supplemental - location. - supplemental_location_sensor (google.maps.fleetengine_v1.types.LocationSensor): - Source of the supplemental location. Defaults to - ``CUSTOMER_SUPPLIED_LOCATION``. - supplemental_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``supplemental_location`` as a radius, in - meters. - road_snapped (bool): - Deprecated: Use ``is_road_snapped`` instead. - """ - - location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - horizontal_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=8, - message=wrappers_pb2.DoubleValue, - ) - latlng_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=22, - message=wrappers_pb2.DoubleValue, - ) - heading: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - bearing_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=10, - message=wrappers_pb2.DoubleValue, - ) - heading_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=23, - message=wrappers_pb2.DoubleValue, - ) - altitude: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.DoubleValue, - ) - vertical_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=9, - message=wrappers_pb2.DoubleValue, - ) - altitude_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=24, - message=wrappers_pb2.DoubleValue, - ) - speed_kmph: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int32Value, - ) - speed: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.DoubleValue, - ) - speed_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=7, - message=wrappers_pb2.DoubleValue, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - server_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=13, - message=timestamp_pb2.Timestamp, - ) - location_sensor: 'LocationSensor' = proto.Field( - proto.ENUM, - number=11, - enum='LocationSensor', - ) - is_road_snapped: wrappers_pb2.BoolValue = proto.Field( - proto.MESSAGE, - number=27, - message=wrappers_pb2.BoolValue, - ) - is_gps_sensor_enabled: wrappers_pb2.BoolValue = proto.Field( - proto.MESSAGE, - number=12, - message=wrappers_pb2.BoolValue, - ) - time_since_update: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=14, - message=wrappers_pb2.Int32Value, - ) - num_stale_updates: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=15, - message=wrappers_pb2.Int32Value, - ) - raw_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=16, - message=latlng_pb2.LatLng, - ) - raw_location_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=17, - message=timestamp_pb2.Timestamp, - ) - raw_location_sensor: 'LocationSensor' = proto.Field( - proto.ENUM, - number=28, - enum='LocationSensor', - ) - raw_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=25, - message=wrappers_pb2.DoubleValue, - ) - supplemental_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=18, - message=latlng_pb2.LatLng, - ) - supplemental_location_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - supplemental_location_sensor: 'LocationSensor' = proto.Field( - proto.ENUM, - number=20, - enum='LocationSensor', - ) - supplemental_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=21, - message=wrappers_pb2.DoubleValue, - ) - road_snapped: bool = proto.Field( - proto.BOOL, - number=26, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py deleted file mode 100644 index 6cc60e782c23..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'RequestHeader', - }, -) - - -class RequestHeader(proto.Message): - r"""A RequestHeader contains fields common to all Fleet Engine - RPC requests. - - Attributes: - language_code (str): - The BCP-47 language code, such as en-US or sr-Latn. For more - information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - If none is specified, the response may be in any language, - with a preference for English if such a name exists. Field - value example: ``en-US``. - region_code (str): - Required. CLDR region code of the region where the request - originates. Field value example: ``US``. - sdk_version (str): - Version of the calling SDK, if applicable. The version - format is "major.minor.patch", example: ``1.1.2``. - os_version (str): - Version of the operating system on which the calling SDK is - running. Field value examples: ``4.4.1``, ``12.1``. - device_model (str): - Model of the device on which the calling SDK is running. - Field value examples: ``iPhone12,1``, ``SM-G920F``. - sdk_type (google.maps.fleetengine_v1.types.RequestHeader.SdkType): - The type of SDK sending the request. - maps_sdk_version (str): - Version of the MapSDK which the calling SDK depends on, if - applicable. The version format is "major.minor.patch", - example: ``5.2.1``. - nav_sdk_version (str): - Version of the NavSDK which the calling SDK depends on, if - applicable. The version format is "major.minor.patch", - example: ``2.1.0``. - platform (google.maps.fleetengine_v1.types.RequestHeader.Platform): - Platform of the calling SDK. - manufacturer (str): - Manufacturer of the Android device from the calling SDK, - only applicable for the Android SDKs. Field value example: - ``Samsung``. - android_api_level (int): - Android API level of the calling SDK, only applicable for - the Android SDKs. Field value example: ``23``. - trace_id (str): - Optional ID that can be provided for logging - purposes in order to identify the request. - """ - class SdkType(proto.Enum): - r"""Possible types of SDK. - - Values: - SDK_TYPE_UNSPECIFIED (0): - The default value. This value is used if the ``sdk_type`` is - omitted. - CONSUMER (1): - The calling SDK is Consumer. - DRIVER (2): - The calling SDK is Driver. - JAVASCRIPT (3): - The calling SDK is JavaScript. - """ - SDK_TYPE_UNSPECIFIED = 0 - CONSUMER = 1 - DRIVER = 2 - JAVASCRIPT = 3 - - class Platform(proto.Enum): - r"""The platform of the calling SDK. - - Values: - PLATFORM_UNSPECIFIED (0): - The default value. This value is used if the - platform is omitted. - ANDROID (1): - The request is coming from Android. - IOS (2): - The request is coming from iOS. - WEB (3): - The request is coming from the web. - """ - PLATFORM_UNSPECIFIED = 0 - ANDROID = 1 - IOS = 2 - WEB = 3 - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=2, - ) - sdk_version: str = proto.Field( - proto.STRING, - number=3, - ) - os_version: str = proto.Field( - proto.STRING, - number=4, - ) - device_model: str = proto.Field( - proto.STRING, - number=5, - ) - sdk_type: SdkType = proto.Field( - proto.ENUM, - number=6, - enum=SdkType, - ) - maps_sdk_version: str = proto.Field( - proto.STRING, - number=7, - ) - nav_sdk_version: str = proto.Field( - proto.STRING, - number=8, - ) - platform: Platform = proto.Field( - proto.ENUM, - number=9, - enum=Platform, - ) - manufacturer: str = proto.Field( - proto.STRING, - number=10, - ) - android_api_level: int = proto.Field( - proto.INT32, - number=11, - ) - trace_id: str = proto.Field( - proto.STRING, - number=12, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py deleted file mode 100644 index c67d29281d61..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'SpeedReadingInterval', - 'ConsumableTrafficPolyline', - }, -) - - -class SpeedReadingInterval(proto.Message): - r"""Traffic density indicator on a contiguous segment of a 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. - - Attributes: - start_polyline_point_index (int): - The starting index of this interval in the - path. In JSON, when the index is 0, the field - will appear to be unpopulated. - end_polyline_point_index (int): - The ending index of this interval in the - path. In JSON, when the index is 0, the field - will appear to be unpopulated. - speed (google.maps.fleetengine_v1.types.SpeedReadingInterval.Speed): - Traffic speed in this interval. - """ - 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, - ) - end_polyline_point_index: int = proto.Field( - proto.INT32, - number=2, - ) - speed: Speed = proto.Field( - proto.ENUM, - number=3, - enum=Speed, - ) - - -class ConsumableTrafficPolyline(proto.Message): - r"""Traffic density along a Vehicle's path. - - Attributes: - speed_reading_interval (MutableSequence[google.maps.fleetengine_v1.types.SpeedReadingInterval]): - Traffic speed along the path from the - previous waypoint to the current waypoint. - encoded_path_to_waypoint (str): - The path the driver is taking from the previous waypoint to - the current waypoint. This path has landmarks in it so - clients can show traffic markers along the path (see - ``speed_reading_interval``). Decoding is not yet supported. - """ - - speed_reading_interval: MutableSequence['SpeedReadingInterval'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SpeedReadingInterval', - ) - encoded_path_to_waypoint: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py deleted file mode 100644 index 911a0a2053c2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import header as mf_header -from google.maps.fleetengine_v1.types import trips as mf_trips -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'CreateTripRequest', - 'GetTripRequest', - 'ReportBillableTripRequest', - 'UpdateTripRequest', - 'SearchTripsRequest', - 'SearchTripsResponse', - }, -) - - -class CreateTripRequest(proto.Message): - r"""CreateTrip request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - trip_id (str): - Required. Unique Trip ID. Subject to the following - restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - trip (google.maps.fleetengine_v1.types.Trip): - Required. Trip entity to create. - - When creating a Trip, the following fields are required: - - - ``trip_type`` - - ``pickup_point`` - - The following fields are used if you provide them: - - - ``number_of_passengers`` - - ``vehicle_id`` - - ``dropoff_point`` - - ``intermediate_destinations`` - - ``vehicle_waypoints`` - - All other Trip fields are ignored. For example, all trips - start with a ``trip_status`` of ``NEW`` even if you pass in - a ``trip_status`` of ``CANCELED`` in the creation request. - - Only ``EXCLUSIVE`` trips support - ``intermediate_destinations``. - - When ``vehicle_id`` is set for a shared trip, you must - supply the list of ``Trip.vehicle_waypoints`` to specify the - order of the remaining waypoints for the vehicle, otherwise - the waypoint order will be undetermined. - - When you specify ``Trip.vehicle_waypoints``, the list must - contain all the remaining waypoints of the vehicle's trips, - with no extra waypoints. You must order these waypoints such - that for a given trip, the pickup point is before - intermediate destinations, and all intermediate destinations - come before the drop-off point. An ``EXCLUSIVE`` trip's - waypoints must not interleave with any other trips. - - The ``trip_id``, ``waypoint_type`` and ``location`` fields - are used, and all other TripWaypoint fields in - ``vehicle_waypoints`` are ignored. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - trip_id: str = proto.Field( - proto.STRING, - number=5, - ) - trip: mf_trips.Trip = proto.Field( - proto.MESSAGE, - number=4, - message=mf_trips.Trip, - ) - - -class GetTripRequest(proto.Message): - r"""GetTrip request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/trips/{trip}``. The provider must be - the Project ID (for example, ``sample-cloud-project``) of - the Google Cloud Project of which the service account making - this call is a member. - view (google.maps.fleetengine_v1.types.TripView): - The subset of Trip fields that should be - returned and their interpretation. - current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Trip.route`` or ``Trip.current_route_segment`` data are - retrieved. If route data are unchanged since this timestamp, - the route field is not set in the response. If a minimum is - unspecified, the route data are always retrieved. - remaining_waypoints_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Trip.remaining_waypoints`` are retrieved. If they are - unchanged since this timestamp, the ``remaining_waypoints`` - are not set in the response. If this field is unspecified, - ``remaining_waypoints`` is always retrieved. - route_format_type (google.maps.fleetengine_v1.types.PolylineFormatType): - The returned current route format, ``LAT_LNG_LIST_TYPE`` (in - ``Trip.route``), or ``ENCODED_POLYLINE_TYPE`` (in - ``Trip.current_route_segment``). The default is - ``LAT_LNG_LIST_TYPE``. - current_route_segment_traffic_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Trip.current_route_segment_traffic`` is retrieved. If - traffic data are unchanged since this timestamp, the - ``current_route_segment_traffic`` field is not set in the - response. If a minimum is unspecified, the traffic data are - always retrieved. Note that traffic is only available for - On-Demand Rides and Deliveries Solution customers. - remaining_waypoints_route_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Trip.remaining_waypoints.traffic_to_waypoint`` and - ``Trip.remaining_waypoints.path_to_waypoint`` data are - retrieved. If data are unchanged since this timestamp, the - fields above are not set in the response. If - ``remaining_waypoints_route_version`` is unspecified, - traffic and path are always retrieved. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - view: mf_trips.TripView = proto.Field( - proto.ENUM, - number=11, - enum=mf_trips.TripView, - ) - current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - remaining_waypoints_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - route_format_type: fleetengine.PolylineFormatType = proto.Field( - proto.ENUM, - number=8, - enum=fleetengine.PolylineFormatType, - ) - current_route_segment_traffic_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - remaining_waypoints_route_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -class ReportBillableTripRequest(proto.Message): - r"""ReportBillableTrip request message. - - Attributes: - name (str): - Required. Must be in the format - ``providers/{provider}/billableTrips/{billable_trip}``. The - provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - country_code (str): - Required. Two letter country code of the - country where the trip takes place. Price is - defined according to country code. - platform (google.maps.fleetengine_v1.types.BillingPlatformIdentifier): - The platform upon which the request was - issued. - related_ids (MutableSequence[str]): - The identifiers that are directly related to the trip being - reported. These are usually IDs (for example, session IDs) - of pre-booking operations done before the trip ID is - available. The number of ``related_ids`` is limited to 50. - solution_type (google.maps.fleetengine_v1.types.ReportBillableTripRequest.SolutionType): - The type of GMP product solution (for example, - ``ON_DEMAND_RIDESHARING_AND_DELIVERIES``) used for the - reported trip. - """ - class SolutionType(proto.Enum): - r"""Selector for different solution types of a reported trip. - - Values: - SOLUTION_TYPE_UNSPECIFIED (0): - The default value. For backwards-compatibility, the API will - use ``ON_DEMAND_RIDESHARING_AND_DELIVERIES`` by default - which is the first supported solution type. - ON_DEMAND_RIDESHARING_AND_DELIVERIES (1): - The solution is an on-demand ridesharing and - deliveries trip. - """ - SOLUTION_TYPE_UNSPECIFIED = 0 - ON_DEMAND_RIDESHARING_AND_DELIVERIES = 1 - - name: str = proto.Field( - proto.STRING, - number=2, - ) - country_code: str = proto.Field( - proto.STRING, - number=3, - ) - platform: mf_trips.BillingPlatformIdentifier = proto.Field( - proto.ENUM, - number=5, - enum=mf_trips.BillingPlatformIdentifier, - ) - related_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - solution_type: SolutionType = proto.Field( - proto.ENUM, - number=7, - enum=SolutionType, - ) - - -class UpdateTripRequest(proto.Message): - r"""UpdateTrip request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/trips/{trip}``. The provider must be - the Project ID (for example, ``sample-consumer-project``) of - the Google Cloud Project of which the service account making - this call is a member. - trip (google.maps.fleetengine_v1.types.Trip): - Required. The Trip associated with the update. - - The following fields are maintained by the Fleet Engine. Do - not update them using Trip.update. - - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_traffic`` - - ``current_route_segment_traffic_version`` - - ``current_route_segment_version`` - - ``dropoff_time`` - - ``eta_to_next_waypoint`` - - ``intermediate_destinations_version`` - - ``last_location`` - - ``name`` - - ``number_of_passengers`` - - ``pickup_time`` - - ``remaining_distance_meters`` - - ``remaining_time_to_first_waypoint`` - - ``remaining_waypoints`` - - ``remaining_waypoints_version`` - - ``route`` - - When you update the ``Trip.vehicle_id`` for a shared trip, - you must supply the list of ``Trip.vehicle_waypoints`` to - specify the order of the remaining waypoints, otherwise the - order will be undetermined. - - When you specify ``Trip.vehicle_waypoints``, the list must - contain all the remaining waypoints of the vehicle's trips, - with no extra waypoints. You must order these waypoints such - that for a given trip, the pickup point is before - intermediate destinations, and all intermediate destinations - come before the drop-off point. An ``EXCLUSIVE`` trip's - waypoints must not interleave with any other trips. The - ``trip_id``, ``waypoint_type`` and ``location`` fields are - used, and all other TripWaypoint fields in - ``vehicle_waypoints`` are ignored. - - To avoid a race condition for trips with multiple - destinations, you should provide - ``Trip.intermediate_destinations_version`` when updating the - trip status to ``ENROUTE_TO_INTERMEDIATE_DESTINATION``. The - ``Trip.intermediate_destinations_version`` passed must be - consistent with Fleet Engine's version. If it isn't, the - request fails. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The field mask indicating which fields in Trip to - update. The ``update_mask`` must contain at least one field. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - trip: mf_trips.Trip = proto.Field( - proto.MESSAGE, - number=4, - message=mf_trips.Trip, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class SearchTripsRequest(proto.Message): - r"""SearchTrips request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - vehicle_id (str): - The vehicle associated with the trips in the request. If - unspecified, the returned trips do not contain: - - - ``current_route_segment`` - - ``remaining_waypoints`` - - ``remaining_distance_meters`` - - ``eta_to_first_waypoint`` - active_trips_only (bool): - If set to true, the response includes Trips - that influence a driver's route. - page_size (int): - If not set, the server decides the number of - results to return. - page_token (str): - Set this to a value previously returned in the - ``SearchTripsResponse`` to continue from previous results. - minimum_staleness (google.protobuf.duration_pb2.Duration): - If specified, returns the trips that have not been updated - after the time ``(current - minimum_staleness)``. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - vehicle_id: str = proto.Field( - proto.STRING, - number=4, - ) - active_trips_only: bool = proto.Field( - proto.BOOL, - number=5, - ) - page_size: int = proto.Field( - proto.INT32, - number=6, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - minimum_staleness: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -class SearchTripsResponse(proto.Message): - r"""SearchTrips response message. - - Attributes: - trips (MutableSequence[google.maps.fleetengine_v1.types.Trip]): - The list of trips for the requested vehicle. - next_page_token (str): - Pass this token in the SearchTripsRequest to - page through list results. The API returns a - trip list on each call, and when no more results - remain the trip list is empty. - """ - - @property - def raw_page(self): - return self - - trips: MutableSequence[mf_trips.Trip] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mf_trips.Trip, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py deleted file mode 100644 index 7fd145d8cd69..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py +++ /dev/null @@ -1,490 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import traffic -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.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'TripStatus', - 'BillingPlatformIdentifier', - 'TripView', - 'Trip', - 'StopLocation', - }, -) - - -class TripStatus(proto.Enum): - r"""The status of a trip indicating its progression. - - Values: - UNKNOWN_TRIP_STATUS (0): - Default, used for unspecified or unrecognized - trip status. - NEW (1): - Newly created trip. - ENROUTE_TO_PICKUP (2): - The driver is on their way to the pickup - point. - ARRIVED_AT_PICKUP (3): - The driver has arrived at the pickup point. - ARRIVED_AT_INTERMEDIATE_DESTINATION (7): - The driver has arrived at an intermediate - destination and is waiting for the rider. - ENROUTE_TO_INTERMEDIATE_DESTINATION (8): - The driver is on their way to an intermediate - destination (not the dropoff point). - ENROUTE_TO_DROPOFF (4): - The driver has picked up the rider and is on - their way to the next destination. - COMPLETE (5): - The rider has been dropped off and the trip - is complete. - CANCELED (6): - The trip was canceled prior to pickup by the - driver, rider, or rideshare provider. - """ - UNKNOWN_TRIP_STATUS = 0 - NEW = 1 - ENROUTE_TO_PICKUP = 2 - ARRIVED_AT_PICKUP = 3 - ARRIVED_AT_INTERMEDIATE_DESTINATION = 7 - ENROUTE_TO_INTERMEDIATE_DESTINATION = 8 - ENROUTE_TO_DROPOFF = 4 - COMPLETE = 5 - CANCELED = 6 - - -class BillingPlatformIdentifier(proto.Enum): - r"""A set of values that indicate upon which platform the request - was issued. - - Values: - BILLING_PLATFORM_IDENTIFIER_UNSPECIFIED (0): - Default. Used for unspecified platforms. - SERVER (1): - The platform is a client server. - WEB (2): - The platform is a web browser. - ANDROID (3): - The platform is an Android mobile device. - IOS (4): - The platform is an IOS mobile device. - OTHERS (5): - Other platforms that are not listed in this - enumeration. - """ - BILLING_PLATFORM_IDENTIFIER_UNSPECIFIED = 0 - SERVER = 1 - WEB = 2 - ANDROID = 3 - IOS = 4 - OTHERS = 5 - - -class TripView(proto.Enum): - r"""Selector for different sets of Trip fields in a ``GetTrip`` - response. See `AIP-157 `__ for context. - Additional views are likely to be added. - - Values: - TRIP_VIEW_UNSPECIFIED (0): - The default value. For backwards-compatibility, the API will - default to an SDK view. To ensure stability and support, - customers are advised to select a ``TripView`` other than - ``SDK``. - SDK (1): - Includes fields that may not be interpretable - or supportable using publicly available - libraries. - JOURNEY_SHARING_V1S (2): - Trip fields are populated for the Journey - Sharing use case. This view is intended for - server-to-server communications. - """ - TRIP_VIEW_UNSPECIFIED = 0 - SDK = 1 - JOURNEY_SHARING_V1S = 2 - - -class Trip(proto.Message): - r"""Trip metadata. - - Attributes: - name (str): - Output only. In the format - "providers/{provider}/trips/{trip}". - vehicle_id (str): - ID of the vehicle making this trip. - trip_status (google.maps.fleetengine_v1.types.TripStatus): - Current status of the trip. - trip_type (google.maps.fleetengine_v1.types.TripType): - The type of the trip. - pickup_point (google.maps.fleetengine_v1.types.TerminalLocation): - Location where customer indicates they will - be picked up. - actual_pickup_point (google.maps.fleetengine_v1.types.StopLocation): - Input only. The actual location when and - where customer was picked up. This field is for - provider to provide feedback on actual pickup - information. - actual_pickup_arrival_point (google.maps.fleetengine_v1.types.StopLocation): - Input only. The actual time and location of - the driver arrival at the pickup point. - This field is for provider to provide feedback - on actual arrival information at the pickup - point. - pickup_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Either the estimated future time - when the rider(s) will be picked up, or the - actual time when they were picked up. - intermediate_destinations (MutableSequence[google.maps.fleetengine_v1.types.TerminalLocation]): - Intermediate stops in order that the trip - requests (in addition to pickup and dropoff). - Initially this will not be supported for shared - trips. - intermediate_destinations_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the last time the ``intermediate_destinations`` - was modified. Your server should cache this value and pass - it in ``UpdateTripRequest`` when update - ``intermediate_destination_index`` to ensure the - ``intermediate_destinations`` is not changed. - intermediate_destination_index (int): - When ``TripStatus`` is - ``ENROUTE_TO_INTERMEDIATE_DESTINATION``, a number between - [0..N-1] indicating which intermediate destination the - vehicle will cross next. When ``TripStatus`` is - ``ARRIVED_AT_INTERMEDIATE_DESTINATION``, a number between - [0..N-1] indicating which intermediate destination the - vehicle is at. The provider sets this value. If there are no - ``intermediate_destinations``, this field is ignored. - actual_intermediate_destination_arrival_points (MutableSequence[google.maps.fleetengine_v1.types.StopLocation]): - Input only. The actual time and location of - the driver's arrival at an intermediate - destination. This field is for provider to - provide feedback on actual arrival information - at intermediate destinations. - actual_intermediate_destinations (MutableSequence[google.maps.fleetengine_v1.types.StopLocation]): - Input only. The actual time and location when - and where the customer was picked up from an - intermediate destination. This field is for - provider to provide feedback on actual pickup - information at intermediate destinations. - dropoff_point (google.maps.fleetengine_v1.types.TerminalLocation): - Location where customer indicates they will - be dropped off. - actual_dropoff_point (google.maps.fleetengine_v1.types.StopLocation): - Input only. The actual time and location when - and where customer was dropped off. This field - is for provider to provide feedback on actual - dropoff information. - dropoff_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Either the estimated future time - when the rider(s) will be dropped off at the - final destination, or the actual time when they - were dropped off. - remaining_waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): - Output only. The full path from the current - location to the dropoff point, inclusive. This - path could include waypoints from other trips. - vehicle_waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): - This field supports manual ordering of the waypoints for the - trip. It contains all of the remaining waypoints for the - assigned vehicle, as well as the pickup and drop-off - waypoints for this trip. If the trip hasn't been assigned to - a vehicle, then Fleet Engine ignores this field. For privacy - reasons, this field is only populated by the server on - ``UpdateTrip`` and ``CreateTrip`` calls, NOT on ``GetTrip`` - calls. - route (MutableSequence[google.type.latlng_pb2.LatLng]): - Output only. Anticipated route for this trip to the first - entry in remaining_waypoints. Note that the first waypoint - may belong to a different trip. - current_route_segment (str): - Output only. An encoded path to the next - waypoint. - Note: This field is intended only for use by the - Driver SDK and Consumer SDK. Decoding is not yet - supported. - current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Indicates the last time the - route was modified. - Note: This field is intended only for use by the - Driver SDK and Consumer SDK. - current_route_segment_traffic (google.maps.fleetengine_v1.types.ConsumableTrafficPolyline): - Output only. Indicates the traffic conditions along the - ``current_route_segment`` when they're available. - - Note: This field is intended only for use by the Driver SDK - and Consumer SDK. - current_route_segment_traffic_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Indicates the last time the - ``current_route_segment_traffic`` was modified. - - Note: This field is intended only for use by the Driver SDK - and Consumer SDK. - current_route_segment_end_point (google.maps.fleetengine_v1.types.TripWaypoint): - Output only. The waypoint where ``current_route_segment`` - ends. - remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - Output only. The remaining driving distance in the - ``current_route_segment`` field. The value is unspecified if - the trip is not assigned to a vehicle, or the trip is - completed or cancelled. - eta_to_first_waypoint (google.protobuf.timestamp_pb2.Timestamp): - Output only. The ETA to the next waypoint (the first entry - in the ``remaining_waypoints`` field). The value is - unspecified if the trip is not assigned to a vehicle, or the - trip is inactive (completed or cancelled). - remaining_time_to_first_waypoint (google.protobuf.duration_pb2.Duration): - Output only. The duration from when the Trip data is - returned to the time in ``Trip.eta_to_first_waypoint``. The - value is unspecified if the trip is not assigned to a - vehicle, or the trip is inactive (completed or cancelled). - remaining_waypoints_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Indicates the last time that - ``remaining_waypoints`` was changed (a waypoint was added, - removed, or changed). - remaining_waypoints_route_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Indicates the last time the - ``remaining_waypoints.path_to_waypoint`` and - ``remaining_waypoints.traffic_to_waypoint`` were modified. - Your client app should cache this value and pass it in - ``GetTripRequest`` to ensure the paths and traffic for - ``remaining_waypoints`` are only returned if updated. - number_of_passengers (int): - Immutable. Indicates the number of passengers on this trip - and does not include the driver. A vehicle must have - available capacity to be returned in a ``SearchVehicles`` - response. - last_location (google.maps.fleetengine_v1.types.VehicleLocation): - Output only. Indicates the last reported - location of the vehicle along the route. - last_location_snappable (bool): - Output only. Indicates whether the vehicle's - ``last_location`` can be snapped to the - current_route_segment. False if ``last_location`` or - ``current_route_segment`` doesn't exist. It is computed by - Fleet Engine. Any update from clients will be ignored. - view (google.maps.fleetengine_v1.types.TripView): - The subset of Trip fields that are populated - and how they should be interpreted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - vehicle_id: str = proto.Field( - proto.STRING, - number=2, - ) - trip_status: 'TripStatus' = proto.Field( - proto.ENUM, - number=3, - enum='TripStatus', - ) - trip_type: fleetengine.TripType = proto.Field( - proto.ENUM, - number=4, - enum=fleetengine.TripType, - ) - pickup_point: fleetengine.TerminalLocation = proto.Field( - proto.MESSAGE, - number=5, - message=fleetengine.TerminalLocation, - ) - actual_pickup_point: 'StopLocation' = proto.Field( - proto.MESSAGE, - number=22, - message='StopLocation', - ) - actual_pickup_arrival_point: 'StopLocation' = proto.Field( - proto.MESSAGE, - number=32, - message='StopLocation', - ) - pickup_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - intermediate_destinations: MutableSequence[fleetengine.TerminalLocation] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=fleetengine.TerminalLocation, - ) - intermediate_destinations_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=25, - message=timestamp_pb2.Timestamp, - ) - intermediate_destination_index: int = proto.Field( - proto.INT32, - number=15, - ) - actual_intermediate_destination_arrival_points: MutableSequence['StopLocation'] = proto.RepeatedField( - proto.MESSAGE, - number=33, - message='StopLocation', - ) - actual_intermediate_destinations: MutableSequence['StopLocation'] = proto.RepeatedField( - proto.MESSAGE, - number=34, - message='StopLocation', - ) - dropoff_point: fleetengine.TerminalLocation = proto.Field( - proto.MESSAGE, - number=7, - message=fleetengine.TerminalLocation, - ) - actual_dropoff_point: 'StopLocation' = proto.Field( - proto.MESSAGE, - number=23, - message='StopLocation', - ) - dropoff_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - remaining_waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( - proto.MESSAGE, - number=16, - message=fleetengine.TripWaypoint, - ) - vehicle_waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( - proto.MESSAGE, - number=20, - message=fleetengine.TripWaypoint, - ) - route: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=latlng_pb2.LatLng, - ) - current_route_segment: str = proto.Field( - proto.STRING, - number=21, - ) - current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=17, - message=timestamp_pb2.Timestamp, - ) - current_route_segment_traffic: traffic.ConsumableTrafficPolyline = proto.Field( - proto.MESSAGE, - number=28, - message=traffic.ConsumableTrafficPolyline, - ) - current_route_segment_traffic_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=30, - message=timestamp_pb2.Timestamp, - ) - current_route_segment_end_point: fleetengine.TripWaypoint = proto.Field( - proto.MESSAGE, - number=24, - message=fleetengine.TripWaypoint, - ) - remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=12, - message=wrappers_pb2.Int32Value, - ) - eta_to_first_waypoint: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=13, - message=timestamp_pb2.Timestamp, - ) - remaining_time_to_first_waypoint: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=27, - message=duration_pb2.Duration, - ) - remaining_waypoints_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - remaining_waypoints_route_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=29, - message=timestamp_pb2.Timestamp, - ) - number_of_passengers: int = proto.Field( - proto.INT32, - number=10, - ) - last_location: fleetengine.VehicleLocation = proto.Field( - proto.MESSAGE, - number=11, - message=fleetengine.VehicleLocation, - ) - last_location_snappable: bool = proto.Field( - proto.BOOL, - number=26, - ) - view: 'TripView' = proto.Field( - proto.ENUM, - number=31, - enum='TripView', - ) - - -class StopLocation(proto.Message): - r"""The actual location where a stop (pickup/dropoff) happened. - - Attributes: - point (google.type.latlng_pb2.LatLng): - Required. Denotes the actual location. - timestamp (google.protobuf.timestamp_pb2.Timestamp): - Indicates when the stop happened. - stop_time (google.protobuf.timestamp_pb2.Timestamp): - Input only. Deprecated. Use the timestamp - field. - """ - - point: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - stop_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py deleted file mode 100644 index a3097884c456..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py +++ /dev/null @@ -1,1050 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import header as mf_header -from google.maps.fleetengine_v1.types import vehicles as mf_vehicles -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'CreateVehicleRequest', - 'GetVehicleRequest', - 'UpdateVehicleRequest', - 'UpdateVehicleAttributesRequest', - 'UpdateVehicleAttributesResponse', - 'SearchVehiclesRequest', - 'SearchVehiclesResponse', - 'ListVehiclesRequest', - 'ListVehiclesResponse', - 'Waypoint', - 'VehicleMatch', - 'VehicleAttributeList', - }, -) - - -class CreateVehicleRequest(proto.Message): - r"""``CreateVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - vehicle_id (str): - Required. Unique Vehicle ID. Subject to the following - restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - vehicle (google.maps.fleetengine_v1.types.Vehicle): - Required. The Vehicle entity to create. When creating a - Vehicle, the following fields are required: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - When creating a Vehicle, the following fields are ignored: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - vehicle_id: str = proto.Field( - proto.STRING, - number=4, - ) - vehicle: mf_vehicles.Vehicle = proto.Field( - proto.MESSAGE, - number=5, - message=mf_vehicles.Vehicle, - ) - - -class GetVehicleRequest(proto.Message): - r"""``GetVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/vehicles/{vehicle}``. The provider - must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Vehicle.current_route_segment`` is retrieved. If the route - is unchanged since this timestamp, the - ``current_route_segment`` field is not set in the response. - If a minimum is unspecified, the ``current_route_segment`` - is always retrieved. - waypoints_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Vehicle.waypoints`` data is retrieved. If the waypoints - are unchanged since this timestamp, the - ``vehicle.waypoints`` data is not set in the response. If - this field is unspecified, ``vehicle.waypoints`` is always - retrieved. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - waypoints_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -class UpdateVehicleRequest(proto.Message): - r"""\`UpdateVehicle request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/vehicles/{vehicle}``. The {provider} - must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - vehicle (google.maps.fleetengine_v1.types.Vehicle): - Required. The ``Vehicle`` entity values to apply. When - updating a ``Vehicle``, the following fields may not be - updated as they are managed by the server. - - - ``available_capacity`` - - ``current_route_segment_version`` - - ``current_trips`` - - ``name`` - - ``waypoints_version`` - - If the ``attributes`` field is updated, **all** the - vehicle's attributes are replaced with the attributes - provided in the request. If you want to update only some - attributes, see the ``UpdateVehicleAttributes`` method. - - Likewise, the ``waypoints`` field can be updated, but must - contain all the waypoints currently on the vehicle, and no - other waypoints. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A field mask indicating which fields of the - ``Vehicle`` to update. At least one field name must be - provided. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - vehicle: mf_vehicles.Vehicle = proto.Field( - proto.MESSAGE, - number=4, - message=mf_vehicles.Vehicle, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateVehicleAttributesRequest(proto.Message): - r"""``UpdateVehicleAttributes`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/vehicles/{vehicle}``. The provider - must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - Required. The vehicle attributes to update. - Unmentioned attributes are not altered or - removed. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=fleetengine.VehicleAttribute, - ) - - -class UpdateVehicleAttributesResponse(proto.Message): - r"""``UpdateVehicleAttributes`` response message. - - Attributes: - attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - Required. The updated full list of vehicle - attributes, including new, altered, and - untouched attributes. - """ - - attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=fleetengine.VehicleAttribute, - ) - - -class SearchVehiclesRequest(proto.Message): - r"""``SearchVehicles`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - pickup_point (google.maps.fleetengine_v1.types.TerminalLocation): - Required. The pickup point to search near. - dropoff_point (google.maps.fleetengine_v1.types.TerminalLocation): - The customer's intended dropoff location. The field is - required if ``trip_types`` contains ``TripType.SHARED``. - pickup_radius_meters (int): - Required. Defines the vehicle search radius - around the pickup point. Only vehicles within - the search radius will be returned. Value must - be between 400 and 10000 meters (inclusive). - count (int): - Required. Specifies the maximum number of - vehicles to return. The value must be between 1 - and 50 (inclusive). - minimum_capacity (int): - Required. Specifies the number of passengers - being considered for a trip. The value must be - greater than or equal to one. The driver is not - considered in the capacity value. - trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): - Required. Represents the type of proposed trip. Must include - exactly one type. ``UNKNOWN_TRIP_TYPE`` is not allowed. - Restricts the search to only those vehicles that can support - that trip type. - maximum_staleness (google.protobuf.duration_pb2.Duration): - Restricts the search to only those vehicles - that have sent location updates to Fleet Engine - within the specified duration. Stationary - vehicles still transmitting their locations are - not considered stale. If this field is not set, - the server uses five minutes as the default - value. - vehicle_types (MutableSequence[google.maps.fleetengine_v1.types.Vehicle.VehicleType]): - Required. Restricts the search to vehicles with one of the - specified types. At least one vehicle type must be - specified. VehicleTypes with a category of ``UNKNOWN`` are - not allowed. - required_attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - Callers can form complex logical operations using any - combination of the ``required_attributes``, - ``required_one_of_attributes``, and - ``required_one_of_attribute_sets`` fields. - - ``required_attributes`` is a list; - ``required_one_of_attributes`` uses a message which allows a - list of lists. In combination, the two fields allow the - composition of this expression: - - :: - - (required_attributes[0] AND required_attributes[1] AND ...) - AND - (required_one_of_attributes[0][0] OR required_one_of_attributes[0][1] OR - ...) - AND - (required_one_of_attributes[1][0] OR required_one_of_attributes[1][1] OR - ...) - - Restricts the search to only those vehicles with the - specified attributes. This field is a conjunction/AND - operation. A max of 50 required_attributes is allowed. This - matches the maximum number of attributes allowed on a - vehicle. - required_one_of_attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttributeList]): - Restricts the search to only those vehicles with at least - one of the specified attributes in each - ``VehicleAttributeList``. Within each list, a vehicle must - match at least one of the attributes. This field is an - inclusive disjunction/OR operation in each - ``VehicleAttributeList`` and a conjunction/AND operation - across the collection of ``VehicleAttributeList``. - required_one_of_attribute_sets (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttributeList]): - ``required_one_of_attribute_sets`` provides additional - functionality. - - Similar to ``required_one_of_attributes``, - ``required_one_of_attribute_sets`` uses a message which - allows a list of lists, allowing expressions such as this - one: - - :: - - (required_attributes[0] AND required_attributes[1] AND ...) - AND - ( - (required_one_of_attribute_sets[0][0] AND - required_one_of_attribute_sets[0][1] AND - ...) - OR - (required_one_of_attribute_sets[1][0] AND - required_one_of_attribute_sets[1][1] AND - ...) - ) - - Restricts the search to only those vehicles with all the - attributes in a ``VehicleAttributeList``. Within each list, - a vehicle must match all of the attributes. This field is a - conjunction/AND operation in each ``VehicleAttributeList`` - and inclusive disjunction/OR operation across the collection - of ``VehicleAttributeList``. - order_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): - Required. Specifies the desired ordering - criterion for results. - include_back_to_back (bool): - This indicates if vehicles with a single active trip are - eligible for this search. This field is only used when - ``current_trips_present`` is unspecified. When - ``current_trips_present`` is unspecified and this field is - ``false``, vehicles with assigned trips are excluded from - the search results. When ``current_trips_present`` is - unspecified and this field is ``true``, search results can - include vehicles with one active trip that has a status of - ``ENROUTE_TO_DROPOFF``. When ``current_trips_present`` is - specified, this field cannot be set to true. - - The default value is ``false``. - trip_id (str): - Indicates the trip associated with this - ``SearchVehicleRequest``. - current_trips_present (google.maps.fleetengine_v1.types.SearchVehiclesRequest.CurrentTripsPresent): - This indicates if vehicles with active trips are eligible - for this search. This must be set to something other than - ``CURRENT_TRIPS_PRESENT_UNSPECIFIED`` if ``trip_type`` - includes ``SHARED``. - filter (str): - Optional. A filter query to apply when searching vehicles. - See http://aip.dev/160 for examples of the filter syntax. - - This field is designed to replace the - ``required_attributes``, ``required_one_of_attributes``, and - ``required_one_of_attributes_sets`` fields. If a non-empty - value is specified here, the following fields must be empty: - ``required_attributes``, ``required_one_of_attributes``, and - ``required_one_of_attributes_sets``. - - This filter functions as an AND clause with other - constraints, such as ``minimum_capacity`` or - ``vehicle_types``. - - Note that the only queries supported are on vehicle - attributes (for example, ``attributes. = `` or - ``attributes. = AND attributes. = ``). - The maximum number of restrictions allowed in a filter query - is 50. - - Also, all attributes are stored as strings, so the only - supported comparisons against attributes are string - comparisons. In order to compare against number or boolean - values, the values must be explicitly quoted to be treated - as strings (for example, ``attributes. = "10"`` or - ``attributes. = "true"``). - """ - class VehicleMatchOrder(proto.Enum): - r"""Specifies the order of the vehicle matches in the response. - - Values: - UNKNOWN_VEHICLE_MATCH_ORDER (0): - Default, used for unspecified or unrecognized - vehicle matches order. - PICKUP_POINT_ETA (1): - Ascending order by vehicle driving time to - the pickup point. - PICKUP_POINT_DISTANCE (2): - Ascending order by vehicle driving distance - to the pickup point. - DROPOFF_POINT_ETA (3): - Ascending order by vehicle driving time to - the dropoff point. This order can only be used - if the dropoff point is specified in the - request. - PICKUP_POINT_STRAIGHT_DISTANCE (4): - Ascending order by straight-line distance - from the vehicle's last reported location to the - pickup point. - COST (5): - Ascending order by the configured match cost. - Match cost is defined as a weighted calculation - between straight-line distance and ETA. Weights - are set with default values and can be modified - per customer. Please contact Google support if - these weights need to be modified for your - project. - """ - UNKNOWN_VEHICLE_MATCH_ORDER = 0 - PICKUP_POINT_ETA = 1 - PICKUP_POINT_DISTANCE = 2 - DROPOFF_POINT_ETA = 3 - PICKUP_POINT_STRAIGHT_DISTANCE = 4 - COST = 5 - - class CurrentTripsPresent(proto.Enum): - r"""Specifies the types of restrictions on a vehicle's current - trips. - - Values: - CURRENT_TRIPS_PRESENT_UNSPECIFIED (0): - The availability of vehicles with trips present is governed - by the ``include_back_to_back`` field. - NONE (1): - Vehicles without trips can appear in search results. When - this value is used, ``include_back_to_back`` cannot be - ``true``. - ANY (2): - Vehicles with at most 5 current trips and 10 waypoints are - included in the search results. When this value is used, - ``include_back_to_back`` cannot be ``true``. - """ - CURRENT_TRIPS_PRESENT_UNSPECIFIED = 0 - NONE = 1 - ANY = 2 - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - pickup_point: fleetengine.TerminalLocation = proto.Field( - proto.MESSAGE, - number=4, - message=fleetengine.TerminalLocation, - ) - dropoff_point: fleetengine.TerminalLocation = proto.Field( - proto.MESSAGE, - number=5, - message=fleetengine.TerminalLocation, - ) - pickup_radius_meters: int = proto.Field( - proto.INT32, - number=6, - ) - count: int = proto.Field( - proto.INT32, - number=7, - ) - minimum_capacity: int = proto.Field( - proto.INT32, - number=8, - ) - trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( - proto.ENUM, - number=9, - enum=fleetengine.TripType, - ) - maximum_staleness: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=10, - message=duration_pb2.Duration, - ) - vehicle_types: MutableSequence[mf_vehicles.Vehicle.VehicleType] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=mf_vehicles.Vehicle.VehicleType, - ) - required_attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=fleetengine.VehicleAttribute, - ) - required_one_of_attributes: MutableSequence['VehicleAttributeList'] = proto.RepeatedField( - proto.MESSAGE, - number=15, - message='VehicleAttributeList', - ) - required_one_of_attribute_sets: MutableSequence['VehicleAttributeList'] = proto.RepeatedField( - proto.MESSAGE, - number=20, - message='VehicleAttributeList', - ) - order_by: VehicleMatchOrder = proto.Field( - proto.ENUM, - number=13, - enum=VehicleMatchOrder, - ) - include_back_to_back: bool = proto.Field( - proto.BOOL, - number=18, - ) - trip_id: str = proto.Field( - proto.STRING, - number=19, - ) - current_trips_present: CurrentTripsPresent = proto.Field( - proto.ENUM, - number=21, - enum=CurrentTripsPresent, - ) - filter: str = proto.Field( - proto.STRING, - number=22, - ) - - -class SearchVehiclesResponse(proto.Message): - r"""``SearchVehicles`` response message. - - Attributes: - matches (MutableSequence[google.maps.fleetengine_v1.types.VehicleMatch]): - List of vehicles that match the ``SearchVehiclesRequest`` - criteria, ordered according to - ``SearchVehiclesRequest.order_by`` field. - """ - - matches: MutableSequence['VehicleMatch'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VehicleMatch', - ) - - -class ListVehiclesRequest(proto.Message): - r"""``ListVehicles`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - page_size (int): - The maximum number of vehicles to return. - Default value: 100. - page_token (str): - The value of the ``next_page_token`` provided by a previous - call to ``ListVehicles`` so that you can paginate through - groups of vehicles. The value is undefined if the filter - criteria of the request is not the same as the filter - criteria for the previous call to ``ListVehicles``. - minimum_capacity (google.protobuf.wrappers_pb2.Int32Value): - Specifies the required minimum capacity of the vehicle. All - vehicles returned will have a ``maximum_capacity`` greater - than or equal to this value. If set, must be greater or - equal to 0. - trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): - Restricts the response to vehicles that - support at least one of the specified trip - types. - maximum_staleness (google.protobuf.duration_pb2.Duration): - Restricts the response to vehicles that have - sent location updates to Fleet Engine within the - specified duration. Stationary vehicles still - transmitting their locations are not considered - stale. If present, must be a valid positive - duration. - vehicle_type_categories (MutableSequence[google.maps.fleetengine_v1.types.Vehicle.VehicleType.Category]): - Required. Restricts the response to vehicles with one of the - specified type categories. ``UNKNOWN`` is not allowed. - required_attributes (MutableSequence[str]): - Callers can form complex logical operations using any - combination of the ``required_attributes``, - ``required_one_of_attributes``, and - ``required_one_of_attribute_sets`` fields. - - ``required_attributes`` is a list; - ``required_one_of_attributes`` uses a message which allows a - list of lists. In combination, the two fields allow the - composition of this expression: - - :: - - (required_attributes[0] AND required_attributes[1] AND ...) - AND - (required_one_of_attributes[0][0] OR required_one_of_attributes[0][1] OR - ...) - AND - (required_one_of_attributes[1][0] OR required_one_of_attributes[1][1] OR - ...) - - Restricts the response to vehicles with the specified - attributes. This field is a conjunction/AND operation. A max - of 50 required_attributes is allowed. This matches the - maximum number of attributes allowed on a vehicle. Each - repeated string should be of the format "key:value". - required_one_of_attributes (MutableSequence[str]): - Restricts the response to vehicles with at least one of the - specified attributes in each ``VehicleAttributeList``. - Within each list, a vehicle must match at least one of the - attributes. This field is an inclusive disjunction/OR - operation in each ``VehicleAttributeList`` and a - conjunction/AND operation across the collection of - ``VehicleAttributeList``. Each repeated string should be of - the format "key1:value1|key2:value2|key3:value3". - required_one_of_attribute_sets (MutableSequence[str]): - ``required_one_of_attribute_sets`` provides additional - functionality. - - Similar to ``required_one_of_attributes``, - ``required_one_of_attribute_sets`` uses a message which - allows a list of lists, allowing expressions such as this - one: - - :: - - (required_attributes[0] AND required_attributes[1] AND ...) - AND - ( - (required_one_of_attribute_sets[0][0] AND - required_one_of_attribute_sets[0][1] AND - ...) - OR - (required_one_of_attribute_sets[1][0] AND - required_one_of_attribute_sets[1][1] AND - ...) - ) - - Restricts the response to vehicles that match all the - attributes in a ``VehicleAttributeList``. Within each list, - a vehicle must match all of the attributes. This field is a - conjunction/AND operation in each ``VehicleAttributeList`` - and inclusive disjunction/OR operation across the collection - of ``VehicleAttributeList``. Each repeated string should be - of the format "key1:value1|key2:value2|key3:value3". - vehicle_state (google.maps.fleetengine_v1.types.VehicleState): - Restricts the response to vehicles that have - this vehicle state. - on_trip_only (bool): - Only return the vehicles with current - trip(s). - filter (str): - Optional. A filter query to apply when listing vehicles. See - http://aip.dev/160 for examples of the filter syntax. - - This field is designed to replace the - ``required_attributes``, ``required_one_of_attributes``, and - ``required_one_of_attributes_sets`` fields. If a non-empty - value is specified here, the following fields must be empty: - ``required_attributes``, ``required_one_of_attributes``, and - ``required_one_of_attributes_sets``. - - This filter functions as an AND clause with other - constraints, such as ``vehicle_state`` or ``on_trip_only``. - - Note that the only queries supported are on vehicle - attributes (for example, ``attributes. = `` or - ``attributes. = AND attributes. = ``). - The maximum number of restrictions allowed in a filter query - is 50. - - Also, all attributes are stored as strings, so the only - supported comparisons against attributes are string - comparisons. In order to compare against number or boolean - values, the values must be explicitly quoted to be treated - as strings (for example, ``attributes. = "10"`` or - ``attributes. = "true"``). - viewport (google.geo.type.types.Viewport): - Optional. A filter that limits the vehicles - returned to those whose last known location was - in the rectangular area defined by the viewport. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=12, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - minimum_capacity: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int32Value, - ) - trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( - proto.ENUM, - number=7, - enum=fleetengine.TripType, - ) - maximum_staleness: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - vehicle_type_categories: MutableSequence[mf_vehicles.Vehicle.VehicleType.Category] = proto.RepeatedField( - proto.ENUM, - number=9, - enum=mf_vehicles.Vehicle.VehicleType.Category, - ) - required_attributes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - required_one_of_attributes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=13, - ) - required_one_of_attribute_sets: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=15, - ) - vehicle_state: mf_vehicles.VehicleState = proto.Field( - proto.ENUM, - number=11, - enum=mf_vehicles.VehicleState, - ) - on_trip_only: bool = proto.Field( - proto.BOOL, - number=14, - ) - filter: str = proto.Field( - proto.STRING, - number=16, - ) - viewport: ggt_viewport.Viewport = proto.Field( - proto.MESSAGE, - number=17, - message=ggt_viewport.Viewport, - ) - - -class ListVehiclesResponse(proto.Message): - r"""``ListVehicles`` response message. - - Attributes: - vehicles (MutableSequence[google.maps.fleetengine_v1.types.Vehicle]): - Vehicles matching the criteria in the request. The maximum - number of vehicles returned is determined by the - ``page_size`` field in the request. - next_page_token (str): - Token to retrieve the next page of vehicles, - or empty if there are no more vehicles that meet - the request criteria. - total_size (int): - Required. Total number of vehicles matching - the request criteria across all pages. - """ - - @property - def raw_page(self): - return self - - vehicles: MutableSequence[mf_vehicles.Vehicle] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mf_vehicles.Vehicle, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT64, - number=3, - ) - - -class Waypoint(proto.Message): - r"""Describes intermediate points along a route for a ``VehicleMatch`` - in a ``SearchVehiclesResponse``. This concept is represented as a - ``TripWaypoint`` in all other endpoints. - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The location of this waypoint. - eta (google.protobuf.timestamp_pb2.Timestamp): - The estimated time that the vehicle will - arrive at this waypoint. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - eta: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class VehicleMatch(proto.Message): - r"""Contains the vehicle and related estimates for a vehicle that match - the points of active trips for the vehicle - ``SearchVehiclesRequest``. - - Attributes: - vehicle (google.maps.fleetengine_v1.types.Vehicle): - Required. A vehicle that matches the request. - vehicle_pickup_eta (google.protobuf.timestamp_pb2.Timestamp): - The vehicle's driving ETA to the pickup point specified in - the request. An empty value indicates a failure in - calculating ETA for the vehicle. If - ``SearchVehiclesRequest.include_back_to_back`` was ``true`` - and this vehicle has an active trip, ``vehicle_pickup_eta`` - includes the time required to complete the current active - trip. - vehicle_pickup_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The distance from the Vehicle's current - location to the pickup point specified in the - request, including any intermediate pickup or - dropoff points for existing trips. This distance - comprises the calculated driving (route) - distance, plus the straight line distance - between the navigation end point and the - requested pickup point. (The distance between - the navigation end point and the requested - pickup point is typically small.) An empty value - indicates an error in calculating the distance. - vehicle_pickup_straight_line_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - Required. The straight-line distance between - the vehicle and the pickup point specified in - the request. - vehicle_dropoff_eta (google.protobuf.timestamp_pb2.Timestamp): - The complete vehicle's driving ETA to the drop off point - specified in the request. The ETA includes stopping at any - waypoints before the ``dropoff_point`` specified in the - request. The value will only be populated when a drop off - point is specified in the request. An empty value indicates - an error calculating the ETA. - vehicle_pickup_to_dropoff_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The vehicle's driving distance (in meters) from the pickup - point to the drop off point specified in the request. The - distance is only between the two points and does not include - the vehicle location or any other points that must be - visited before the vehicle visits either the pickup point or - dropoff point. The value will only be populated when a - ``dropoff_point`` is specified in the request. An empty - value indicates a failure in calculating the distance from - the pickup to drop off point specified in the request. - trip_type (google.maps.fleetengine_v1.types.TripType): - Required. The trip type of the request that - was used to calculate the ETA to the pickup - point. - vehicle_trips_waypoints (MutableSequence[google.maps.fleetengine_v1.types.Waypoint]): - The ordered list of waypoints used to - calculate the ETA. The list includes vehicle - location, the pickup points of active trips for - the vehicle, and the pickup points provided in - the request. An empty list indicates a failure - in calculating ETA for the vehicle. - vehicle_match_type (google.maps.fleetengine_v1.types.VehicleMatch.VehicleMatchType): - Type of the vehicle match. - requested_ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): - The order requested for sorting vehicle - matches. - ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): - The actual order that was used for this vehicle. Normally - this will match the 'order_by' field from the request; - however, in certain circumstances such as an internal server - error, a different method may be used (such as - ``PICKUP_POINT_STRAIGHT_DISTANCE``). - """ - class VehicleMatchType(proto.Enum): - r"""Type of vehicle match. - - Values: - UNKNOWN (0): - Unknown vehicle match type - EXCLUSIVE (1): - The vehicle currently has no trip assigned to - it and can proceed to the pickup point. - BACK_TO_BACK (2): - The vehicle is currently assigned to a trip, - but can proceed to the pickup point after - completing the in-progress trip. ETA and - distance calculations take the existing trip - into account. - CARPOOL (3): - The vehicle has sufficient capacity for a - shared ride. - CARPOOL_BACK_TO_BACK (4): - The vehicle will finish its current, active - trip before proceeding to the pickup point. ETA - and distance calculations take the existing trip - into account. - """ - UNKNOWN = 0 - EXCLUSIVE = 1 - BACK_TO_BACK = 2 - CARPOOL = 3 - CARPOOL_BACK_TO_BACK = 4 - - vehicle: mf_vehicles.Vehicle = proto.Field( - proto.MESSAGE, - number=1, - message=mf_vehicles.Vehicle, - ) - vehicle_pickup_eta: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - vehicle_pickup_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int32Value, - ) - vehicle_pickup_straight_line_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=11, - message=wrappers_pb2.Int32Value, - ) - vehicle_dropoff_eta: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - vehicle_pickup_to_dropoff_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int32Value, - ) - trip_type: fleetengine.TripType = proto.Field( - proto.ENUM, - number=6, - enum=fleetengine.TripType, - ) - vehicle_trips_waypoints: MutableSequence['Waypoint'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='Waypoint', - ) - vehicle_match_type: VehicleMatchType = proto.Field( - proto.ENUM, - number=8, - enum=VehicleMatchType, - ) - requested_ordered_by: 'SearchVehiclesRequest.VehicleMatchOrder' = proto.Field( - proto.ENUM, - number=9, - enum='SearchVehiclesRequest.VehicleMatchOrder', - ) - ordered_by: 'SearchVehiclesRequest.VehicleMatchOrder' = proto.Field( - proto.ENUM, - number=10, - enum='SearchVehiclesRequest.VehicleMatchOrder', - ) - - -class VehicleAttributeList(proto.Message): - r"""A list-of-lists datatype for vehicle attributes. - - Attributes: - attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - A list of attributes in this collection. - """ - - attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=fleetengine.VehicleAttribute, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py deleted file mode 100644 index c4662d189513..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py +++ /dev/null @@ -1,580 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.fleetengine_v1.types import fleetengine -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'VehicleState', - 'LocationPowerSaveMode', - 'BatteryStatus', - 'PowerSource', - 'Vehicle', - 'BatteryInfo', - 'DeviceSettings', - 'LicensePlate', - 'VisualTrafficReportPolylineRendering', - 'TrafficPolylineData', - }, -) - - -class VehicleState(proto.Enum): - r"""The state of a ``Vehicle``. - - Values: - UNKNOWN_VEHICLE_STATE (0): - Default, used for unspecified or unrecognized - vehicle states. - OFFLINE (1): - The vehicle is not accepting new trips. Note: - the vehicle may continue to operate in this - state while completing a trip assigned to it. - ONLINE (2): - The vehicle is accepting new trips. - """ - UNKNOWN_VEHICLE_STATE = 0 - OFFLINE = 1 - ONLINE = 2 - - -class LocationPowerSaveMode(proto.Enum): - r"""How location features are configured to behave on the mobile - device when the devices "battery saver" feature is on. - (https://developer.android.com/reference/android/os/PowerManager#getLocationPowerSaveMode()) - - Values: - UNKNOWN_LOCATION_POWER_SAVE_MODE (0): - Undefined LocationPowerSaveMode - LOCATION_MODE_NO_CHANGE (1): - Either the location providers shouldn't be - affected by battery saver, or battery saver is - off. - LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF (2): - The GPS based location provider should be - disabled when battery saver is on and the device - is non-interactive. - LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF (3): - All location providers should be disabled - when battery saver is on and the device is - non-interactive. - LOCATION_MODE_FOREGROUND_ONLY (4): - All the location providers will be kept - available, but location fixes should only be - provided to foreground apps. - LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF (5): - Location will not be turned off, but - LocationManager will throttle all requests to - providers when the device is non-interactive. - """ - UNKNOWN_LOCATION_POWER_SAVE_MODE = 0 - LOCATION_MODE_NO_CHANGE = 1 - LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF = 2 - LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF = 3 - LOCATION_MODE_FOREGROUND_ONLY = 4 - LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF = 5 - - -class BatteryStatus(proto.Enum): - r"""Status of the battery, whether full or charging etc. - - Values: - UNKNOWN_BATTERY_STATUS (0): - Battery status unknown. - BATTERY_STATUS_CHARGING (1): - Battery is being charged. - BATTERY_STATUS_DISCHARGING (2): - Battery is discharging. - BATTERY_STATUS_FULL (3): - Battery is full. - BATTERY_STATUS_NOT_CHARGING (4): - Battery is not charging. - BATTERY_STATUS_POWER_LOW (5): - Battery is low on power. - """ - UNKNOWN_BATTERY_STATUS = 0 - BATTERY_STATUS_CHARGING = 1 - BATTERY_STATUS_DISCHARGING = 2 - BATTERY_STATUS_FULL = 3 - BATTERY_STATUS_NOT_CHARGING = 4 - BATTERY_STATUS_POWER_LOW = 5 - - -class PowerSource(proto.Enum): - r"""Type of the charger being used to charge the battery. - - Values: - UNKNOWN_POWER_SOURCE (0): - Power source unknown. - POWER_SOURCE_AC (1): - Power source is an AC charger. - POWER_SOURCE_USB (2): - Power source is a USB port. - POWER_SOURCE_WIRELESS (3): - Power source is wireless. - POWER_SOURCE_UNPLUGGED (4): - Battery is unplugged. - """ - UNKNOWN_POWER_SOURCE = 0 - POWER_SOURCE_AC = 1 - POWER_SOURCE_USB = 2 - POWER_SOURCE_WIRELESS = 3 - POWER_SOURCE_UNPLUGGED = 4 - - -class Vehicle(proto.Message): - r"""Vehicle metadata. - - Attributes: - name (str): - Output only. The unique name for this vehicle. The format is - ``providers/{provider}/vehicles/{vehicle}``. - vehicle_state (google.maps.fleetengine_v1.types.VehicleState): - The vehicle state. - supported_trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): - Trip types supported by this vehicle. - current_trips (MutableSequence[str]): - Output only. List of ``trip_id``'s for trips currently - assigned to this vehicle. - last_location (google.maps.fleetengine_v1.types.VehicleLocation): - Last reported location of the vehicle. - maximum_capacity (int): - The total numbers of riders this vehicle can - carry. The driver is not considered in this - value. This value must be greater than or equal - to one. - attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - List of vehicle attributes. A vehicle can - have at most 100 attributes, and each attribute - must have a unique key. - vehicle_type (google.maps.fleetengine_v1.types.Vehicle.VehicleType): - Required. The type of this vehicle. Can be used to filter - vehicles in ``SearchVehicles`` results. Also influences ETA - and route calculations. - license_plate (google.maps.fleetengine_v1.types.LicensePlate): - License plate information for the vehicle. - route (MutableSequence[google.maps.fleetengine_v1.types.TerminalLocation]): - Deprecated: Use ``Vehicle.waypoints`` instead. - current_route_segment (str): - The polyline specifying the route the driver app intends to - take to the next waypoint. This list is also returned in - ``Trip.current_route_segment`` for all active trips assigned - to the vehicle. - - Note: This field is intended only for use by the Driver SDK. - Decoding is not yet supported. - current_route_segment_traffic (google.maps.fleetengine_v1.types.TrafficPolylineData): - Input only. Fleet Engine uses this - information to improve journey sharing. Note: - This field is intended only for use by the - Driver SDK. - current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when ``current_route_segment`` was set. It - can be stored by the client and passed in future - ``GetVehicle`` requests to prevent returning routes that - haven't changed. - current_route_segment_end_point (google.maps.fleetengine_v1.types.TripWaypoint): - The waypoint where ``current_route_segment`` ends. This can - be supplied by drivers on ``UpdateVehicle`` calls either as - a full trip waypoint, a waypoint ``LatLng``, or as the last - ``LatLng`` of the ``current_route_segment``. Fleet Engine - will then do its best to interpolate to an actual waypoint - if it is not fully specified. This field is ignored in - ``UpdateVehicle`` calls unless ``current_route_segment`` is - also specified. - remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The remaining driving distance for the - ``current_route_segment``. This value is also returned in - ``Trip.remaining_distance_meters`` for all active trips - assigned to the vehicle. The value is unspecified if the - ``current_route_segment`` field is empty. - eta_to_first_waypoint (google.protobuf.timestamp_pb2.Timestamp): - The ETA to the first entry in the ``waypoints`` field. The - value is unspecified if the ``waypoints`` field is empty or - the ``Vehicle.current_route_segment`` field is empty. - - When updating a vehicle, ``remaining_time_seconds`` takes - precedence over ``eta_to_first_waypoint`` in the same - request. - remaining_time_seconds (google.protobuf.wrappers_pb2.Int32Value): - Input only. The remaining driving time for the - ``current_route_segment``. The value is unspecified if the - ``waypoints`` field is empty or the - ``Vehicle.current_route_segment`` field is empty. This value - should match ``eta_to_first_waypoint`` - ``current_time`` if - all parties are using the same clock. - - When updating a vehicle, ``remaining_time_seconds`` takes - precedence over ``eta_to_first_waypoint`` in the same - request. - waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): - The remaining waypoints assigned to this - Vehicle. - waypoints_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last time the ``waypoints`` field was updated. - Clients should cache this value and pass it in - ``GetVehicleRequest`` to ensure the ``waypoints`` field is - only returned if it is updated. - back_to_back_enabled (bool): - Indicates if the driver accepts back-to-back trips. If - ``true``, ``SearchVehicles`` may include the vehicle even if - it is currently assigned to a trip. The default value is - ``false``. - navigation_status (google.maps.fleetengine_v1.types.NavigationStatus): - The vehicle's navigation status. - device_settings (google.maps.fleetengine_v1.types.DeviceSettings): - Input only. Information about settings in the - mobile device being used by the driver. - """ - - class VehicleType(proto.Message): - r"""The type of vehicle. - - Attributes: - category (google.maps.fleetengine_v1.types.Vehicle.VehicleType.Category): - Vehicle type category - """ - class Category(proto.Enum): - r"""Vehicle type categories - - Values: - UNKNOWN (0): - Default, used for unspecified or unrecognized - vehicle categories. - AUTO (1): - An automobile. - TAXI (2): - Any vehicle that acts as a taxi (typically - licensed or regulated). - TRUCK (3): - Generally, a vehicle with a large storage - capacity. - TWO_WHEELER (4): - A motorcycle, moped, or other two-wheeled - vehicle - BICYCLE (5): - Human-powered transport. - PEDESTRIAN (6): - A human transporter, typically walking or - running, traveling along pedestrian pathways. - """ - UNKNOWN = 0 - AUTO = 1 - TAXI = 2 - TRUCK = 3 - TWO_WHEELER = 4 - BICYCLE = 5 - PEDESTRIAN = 6 - - category: 'Vehicle.VehicleType.Category' = proto.Field( - proto.ENUM, - number=1, - enum='Vehicle.VehicleType.Category', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - vehicle_state: 'VehicleState' = proto.Field( - proto.ENUM, - number=2, - enum='VehicleState', - ) - supported_trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( - proto.ENUM, - number=3, - enum=fleetengine.TripType, - ) - current_trips: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - last_location: fleetengine.VehicleLocation = proto.Field( - proto.MESSAGE, - number=5, - message=fleetengine.VehicleLocation, - ) - maximum_capacity: int = proto.Field( - proto.INT32, - number=6, - ) - attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=fleetengine.VehicleAttribute, - ) - vehicle_type: VehicleType = proto.Field( - proto.MESSAGE, - number=9, - message=VehicleType, - ) - license_plate: 'LicensePlate' = proto.Field( - proto.MESSAGE, - number=10, - message='LicensePlate', - ) - route: MutableSequence[fleetengine.TerminalLocation] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=fleetengine.TerminalLocation, - ) - current_route_segment: str = proto.Field( - proto.STRING, - number=20, - ) - current_route_segment_traffic: 'TrafficPolylineData' = proto.Field( - proto.MESSAGE, - number=28, - message='TrafficPolylineData', - ) - current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=15, - message=timestamp_pb2.Timestamp, - ) - current_route_segment_end_point: fleetengine.TripWaypoint = proto.Field( - proto.MESSAGE, - number=24, - message=fleetengine.TripWaypoint, - ) - remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=18, - message=wrappers_pb2.Int32Value, - ) - eta_to_first_waypoint: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - remaining_time_seconds: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=25, - message=wrappers_pb2.Int32Value, - ) - waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( - proto.MESSAGE, - number=22, - message=fleetengine.TripWaypoint, - ) - waypoints_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=16, - message=timestamp_pb2.Timestamp, - ) - back_to_back_enabled: bool = proto.Field( - proto.BOOL, - number=23, - ) - navigation_status: fleetengine.NavigationStatus = proto.Field( - proto.ENUM, - number=26, - enum=fleetengine.NavigationStatus, - ) - device_settings: 'DeviceSettings' = proto.Field( - proto.MESSAGE, - number=27, - message='DeviceSettings', - ) - - -class BatteryInfo(proto.Message): - r"""Information about the device's battery. - - Attributes: - battery_status (google.maps.fleetengine_v1.types.BatteryStatus): - Status of the battery, whether full or - charging etc. - power_source (google.maps.fleetengine_v1.types.PowerSource): - Status of battery power source. - battery_percentage (float): - Current battery percentage [0-100]. - """ - - battery_status: 'BatteryStatus' = proto.Field( - proto.ENUM, - number=1, - enum='BatteryStatus', - ) - power_source: 'PowerSource' = proto.Field( - proto.ENUM, - number=2, - enum='PowerSource', - ) - battery_percentage: float = proto.Field( - proto.FLOAT, - number=3, - ) - - -class DeviceSettings(proto.Message): - r"""Information about various settings on the mobile device. - - Attributes: - location_power_save_mode (google.maps.fleetengine_v1.types.LocationPowerSaveMode): - How location features are set to behave on - the device when battery saver is on. - is_power_save_mode (bool): - Whether the device is currently in power save - mode. - is_interactive (bool): - Whether the device is in an interactive - state. - battery_info (google.maps.fleetengine_v1.types.BatteryInfo): - Information about the battery state. - """ - - location_power_save_mode: 'LocationPowerSaveMode' = proto.Field( - proto.ENUM, - number=1, - enum='LocationPowerSaveMode', - ) - is_power_save_mode: bool = proto.Field( - proto.BOOL, - number=2, - ) - is_interactive: bool = proto.Field( - proto.BOOL, - number=3, - ) - battery_info: 'BatteryInfo' = proto.Field( - proto.MESSAGE, - number=4, - message='BatteryInfo', - ) - - -class LicensePlate(proto.Message): - r"""The license plate information of the Vehicle. To avoid - storing personally-identifiable information, only the minimum - information about the license plate is stored as part of the - entity. - - Attributes: - country_code (str): - Required. CLDR Country/Region Code. For example, ``US`` for - United States, or ``IN`` for India. - last_character (str): - The last digit of the license plate or "-1" to denote no - numeric value is present in the license plate. - - - "ABC 1234" -> "4" - - "AB 123 CD" -> "3" - - "ABCDEF" -> "-1". - """ - - country_code: str = proto.Field( - proto.STRING, - number=1, - ) - last_character: str = proto.Field( - proto.STRING, - number=2, - ) - - -class VisualTrafficReportPolylineRendering(proto.Message): - r"""Describes how clients should color one portion of the - polyline along the route. - - Attributes: - road_stretch (MutableSequence[google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering.RoadStretch]): - Optional. Road stretches that should be - rendered along the polyline. Stretches are - guaranteed to not overlap, and do not - necessarily span the full route. - - In the absence of a road stretch to style, the - client should apply the default for the route. - """ - - class RoadStretch(proto.Message): - r"""One road stretch that should be rendered. - - Attributes: - style (google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering.RoadStretch.Style): - Required. The style to apply. - offset_meters (int): - Required. The style should be applied between - ``[offset_meters, offset_meters + length_meters)``. - length_meters (int): - Required. The length of the path where to - apply the style. - """ - class Style(proto.Enum): - r"""The traffic style, indicating traffic speed. - - Values: - STYLE_UNSPECIFIED (0): - No style selected. - SLOWER_TRAFFIC (1): - Traffic is slowing down. - TRAFFIC_JAM (2): - There is a traffic jam. - """ - STYLE_UNSPECIFIED = 0 - SLOWER_TRAFFIC = 1 - TRAFFIC_JAM = 2 - - style: 'VisualTrafficReportPolylineRendering.RoadStretch.Style' = proto.Field( - proto.ENUM, - number=1, - enum='VisualTrafficReportPolylineRendering.RoadStretch.Style', - ) - offset_meters: int = proto.Field( - proto.INT32, - number=2, - ) - length_meters: int = proto.Field( - proto.INT32, - number=3, - ) - - road_stretch: MutableSequence[RoadStretch] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=RoadStretch, - ) - - -class TrafficPolylineData(proto.Message): - r"""Traffic conditions along the expected vehicle route. - - Attributes: - traffic_rendering (google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering): - A polyline rendering of how fast traffic is - for all regions along one stretch of a customer - ride. - """ - - traffic_rendering: 'VisualTrafficReportPolylineRendering' = proto.Field( - proto.MESSAGE, - number=1, - message='VisualTrafficReportPolylineRendering', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini b/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/noxfile.py b/owl-bot-staging/google-maps-fleetengine/v1/noxfile.py deleted file mode 100644 index 4bc01f860119..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine' - -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/fleetengine_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/fleetengine_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-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py deleted file mode 100644 index ab45c932839a..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_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 CreateTrip -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_CreateTrip_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_create_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateTripRequest( - parent="parent_value", - trip_id="trip_id_value", - ) - - # Make the request - response = await client.create_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_CreateTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py deleted file mode 100644 index c4644b1862d3..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_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 CreateTrip -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_CreateTrip_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_create_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateTripRequest( - parent="parent_value", - trip_id="trip_id_value", - ) - - # Make the request - response = client.create_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_CreateTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py deleted file mode 100644 index 0c2d7cd52ca9..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_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 GetTrip -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_GetTrip_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_get_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetTripRequest( - name="name_value", - ) - - # Make the request - response = await client.get_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_GetTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py deleted file mode 100644 index d3bfcfe709c0..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_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 GetTrip -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_GetTrip_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_get_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetTripRequest( - name="name_value", - ) - - # Make the request - response = client.get_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_GetTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py deleted file mode 100644 index 8e32e9b6f3a9..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_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 ReportBillableTrip -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_ReportBillableTrip_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_report_billable_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.ReportBillableTripRequest( - name="name_value", - country_code="country_code_value", - ) - - # Make the request - await client.report_billable_trip(request=request) - - -# [END fleetengine_v1_generated_TripService_ReportBillableTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py deleted file mode 100644 index 0ea03be8d902..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_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 ReportBillableTrip -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_ReportBillableTrip_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_report_billable_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.ReportBillableTripRequest( - name="name_value", - country_code="country_code_value", - ) - - # Make the request - client.report_billable_trip(request=request) - - -# [END fleetengine_v1_generated_TripService_ReportBillableTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py deleted file mode 100644 index 5cd30f613daa..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_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 SearchTrips -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_SearchTrips_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_search_trips(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchTripsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_trips(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END fleetengine_v1_generated_TripService_SearchTrips_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py deleted file mode 100644 index dfbbfe500c95..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_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 SearchTrips -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_SearchTrips_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_search_trips(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchTripsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_trips(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END fleetengine_v1_generated_TripService_SearchTrips_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py deleted file mode 100644 index f67869a7143d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_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 UpdateTrip -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_UpdateTrip_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_update_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateTripRequest( - name="name_value", - ) - - # Make the request - response = await client.update_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_UpdateTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py deleted file mode 100644 index fc41bd61a318..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_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 UpdateTrip -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_UpdateTrip_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_update_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateTripRequest( - name="name_value", - ) - - # Make the request - response = client.update_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_UpdateTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py deleted file mode 100644 index 851946fd95a3..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_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 CreateVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_CreateVehicle_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_create_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateVehicleRequest( - parent="parent_value", - vehicle_id="vehicle_id_value", - ) - - # Make the request - response = await client.create_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_CreateVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py deleted file mode 100644 index 24820678e5df..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_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 CreateVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_CreateVehicle_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_create_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateVehicleRequest( - parent="parent_value", - vehicle_id="vehicle_id_value", - ) - - # Make the request - response = client.create_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_CreateVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py deleted file mode 100644 index 39c32d3272f7..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_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 GetVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_GetVehicle_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_get_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_GetVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py deleted file mode 100644 index 3b852145ad23..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_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 GetVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_GetVehicle_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_get_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.get_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_GetVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py deleted file mode 100644 index 969785d1f002..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_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 ListVehicles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_ListVehicles_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_list_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.ListVehiclesRequest( - parent="parent_value", - vehicle_type_categories=['PEDESTRIAN'], - ) - - # Make the request - page_result = client.list_vehicles(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END fleetengine_v1_generated_VehicleService_ListVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py deleted file mode 100644 index 32329e16b91d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_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 ListVehicles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_ListVehicles_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_list_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.ListVehiclesRequest( - parent="parent_value", - vehicle_type_categories=['PEDESTRIAN'], - ) - - # Make the request - page_result = client.list_vehicles(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END fleetengine_v1_generated_VehicleService_ListVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py deleted file mode 100644 index 72dbea4e2525..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_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 SearchVehicles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_SearchVehicles_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_search_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = await client.search_vehicles(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_SearchVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py deleted file mode 100644 index 9d2ea3d1cd7f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_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 SearchVehicles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_SearchVehicles_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_search_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = client.search_vehicles(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_SearchVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py deleted file mode 100644 index 83ef89e4566b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_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 UpdateVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicle_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_update_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.update_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py deleted file mode 100644 index 9b5d10d7db81..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_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 UpdateVehicleAttributes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -async def sample_update_vehicle_attributes(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - attributes = fleetengine_v1.VehicleAttribute() - attributes.string_value = "string_value_value" - - request = fleetengine_v1.UpdateVehicleAttributesRequest( - name="name_value", - attributes=attributes, - ) - - # Make the request - response = await client.update_vehicle_attributes(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py deleted file mode 100644 index ae0d5f325998..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_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 UpdateVehicleAttributes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_update_vehicle_attributes(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - attributes = fleetengine_v1.VehicleAttribute() - attributes.string_value = "string_value_value" - - request = fleetengine_v1.UpdateVehicleAttributesRequest( - name="name_value", - attributes=attributes, - ) - - # Make the request - response = client.update_vehicle_attributes(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py deleted file mode 100644 index f1ae021b0f99..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_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 UpdateVehicle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicle_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 fleetengine_v1 - - -def sample_update_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.update_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json deleted file mode 100644 index b0139d358773..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json +++ /dev/null @@ -1,1692 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "maps.fleetengine.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-fleetengine", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.create_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.CreateTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "CreateTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.CreateTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "create_trip" - }, - "description": "Sample for CreateTrip", - "file": "fleetengine_v1_generated_trip_service_create_trip_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_CreateTrip_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": "fleetengine_v1_generated_trip_service_create_trip_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.create_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.CreateTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "CreateTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.CreateTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "create_trip" - }, - "description": "Sample for CreateTrip", - "file": "fleetengine_v1_generated_trip_service_create_trip_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_CreateTrip_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": "fleetengine_v1_generated_trip_service_create_trip_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.get_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.GetTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "GetTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.GetTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "get_trip" - }, - "description": "Sample for GetTrip", - "file": "fleetengine_v1_generated_trip_service_get_trip_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_GetTrip_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": "fleetengine_v1_generated_trip_service_get_trip_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.get_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.GetTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "GetTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.GetTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "get_trip" - }, - "description": "Sample for GetTrip", - "file": "fleetengine_v1_generated_trip_service_get_trip_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_GetTrip_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": "fleetengine_v1_generated_trip_service_get_trip_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.report_billable_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.ReportBillableTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "ReportBillableTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.ReportBillableTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "report_billable_trip" - }, - "description": "Sample for ReportBillableTrip", - "file": "fleetengine_v1_generated_trip_service_report_billable_trip_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_ReportBillableTrip_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_report_billable_trip_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.report_billable_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.ReportBillableTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "ReportBillableTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.ReportBillableTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "report_billable_trip" - }, - "description": "Sample for ReportBillableTrip", - "file": "fleetengine_v1_generated_trip_service_report_billable_trip_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_ReportBillableTrip_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_report_billable_trip_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.search_trips", - "method": { - "fullName": "maps.fleetengine.v1.TripService.SearchTrips", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "SearchTrips" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchTripsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsAsyncPager", - "shortName": "search_trips" - }, - "description": "Sample for SearchTrips", - "file": "fleetengine_v1_generated_trip_service_search_trips_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_SearchTrips_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": "fleetengine_v1_generated_trip_service_search_trips_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.search_trips", - "method": { - "fullName": "maps.fleetengine.v1.TripService.SearchTrips", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "SearchTrips" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchTripsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsPager", - "shortName": "search_trips" - }, - "description": "Sample for SearchTrips", - "file": "fleetengine_v1_generated_trip_service_search_trips_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_SearchTrips_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": "fleetengine_v1_generated_trip_service_search_trips_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.update_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.UpdateTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "UpdateTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "update_trip" - }, - "description": "Sample for UpdateTrip", - "file": "fleetengine_v1_generated_trip_service_update_trip_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_UpdateTrip_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": "fleetengine_v1_generated_trip_service_update_trip_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.update_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.UpdateTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "UpdateTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "update_trip" - }, - "description": "Sample for UpdateTrip", - "file": "fleetengine_v1_generated_trip_service_update_trip_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_UpdateTrip_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": "fleetengine_v1_generated_trip_service_update_trip_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.create_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.CreateVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "CreateVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.CreateVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "create_vehicle" - }, - "description": "Sample for CreateVehicle", - "file": "fleetengine_v1_generated_vehicle_service_create_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_CreateVehicle_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": "fleetengine_v1_generated_vehicle_service_create_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.create_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.CreateVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "CreateVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.CreateVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "create_vehicle" - }, - "description": "Sample for CreateVehicle", - "file": "fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_CreateVehicle_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": "fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.get_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.GetVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "GetVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.GetVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "get_vehicle" - }, - "description": "Sample for GetVehicle", - "file": "fleetengine_v1_generated_vehicle_service_get_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_GetVehicle_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": "fleetengine_v1_generated_vehicle_service_get_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.get_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.GetVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "GetVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.GetVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "get_vehicle" - }, - "description": "Sample for GetVehicle", - "file": "fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_GetVehicle_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": "fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.list_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.ListVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "ListVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.ListVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesAsyncPager", - "shortName": "list_vehicles" - }, - "description": "Sample for ListVehicles", - "file": "fleetengine_v1_generated_vehicle_service_list_vehicles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_ListVehicles_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": "fleetengine_v1_generated_vehicle_service_list_vehicles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.list_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.ListVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "ListVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.ListVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesPager", - "shortName": "list_vehicles" - }, - "description": "Sample for ListVehicles", - "file": "fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_ListVehicles_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": "fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.search_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.SearchVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "SearchVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", - "shortName": "search_vehicles" - }, - "description": "Sample for SearchVehicles", - "file": "fleetengine_v1_generated_vehicle_service_search_vehicles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_SearchVehicles_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": "fleetengine_v1_generated_vehicle_service_search_vehicles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.search_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.SearchVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "SearchVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", - "shortName": "search_vehicles" - }, - "description": "Sample for SearchVehicles", - "file": "fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_SearchVehicles_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": "fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.update_vehicle_attributes", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleAttributes", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicleAttributes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse", - "shortName": "update_vehicle_attributes" - }, - "description": "Sample for UpdateVehicleAttributes", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_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": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.update_vehicle_attributes", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleAttributes", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicleAttributes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse", - "shortName": "update_vehicle_attributes" - }, - "description": "Sample for UpdateVehicleAttributes", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_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": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.update_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "update_vehicle" - }, - "description": "Sample for UpdateVehicle", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicle_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": "fleetengine_v1_generated_vehicle_service_update_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.update_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "update_vehicle" - }, - "description": "Sample for UpdateVehicle", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicle_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": "fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py b/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py deleted file mode 100644 index 1a4c9837d26c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py +++ /dev/null @@ -1,186 +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 fleetengineCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_trip': ('parent', 'trip_id', 'trip', 'header', ), - 'create_vehicle': ('parent', 'vehicle_id', 'vehicle', 'header', ), - 'get_trip': ('name', 'header', 'view', 'current_route_segment_version', 'remaining_waypoints_version', 'route_format_type', 'current_route_segment_traffic_version', 'remaining_waypoints_route_version', ), - 'get_vehicle': ('name', 'header', 'current_route_segment_version', 'waypoints_version', ), - 'list_vehicles': ('parent', 'vehicle_type_categories', 'header', 'page_size', 'page_token', 'minimum_capacity', 'trip_types', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'vehicle_state', 'on_trip_only', 'filter', 'viewport', ), - 'report_billable_trip': ('name', 'country_code', 'platform', 'related_ids', 'solution_type', ), - 'search_trips': ('parent', 'header', 'vehicle_id', 'active_trips_only', 'page_size', 'page_token', 'minimum_staleness', ), - 'search_vehicles': ('parent', 'pickup_point', 'pickup_radius_meters', 'count', 'minimum_capacity', 'trip_types', 'vehicle_types', 'order_by', 'header', 'dropoff_point', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'include_back_to_back', 'trip_id', 'current_trips_present', 'filter', ), - 'update_trip': ('name', 'trip', 'update_mask', 'header', ), - 'update_vehicle': ('name', 'vehicle', 'update_mask', 'header', ), - 'update_vehicle_attributes': ('name', 'attributes', 'header', ), - } - - 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=fleetengineCallTransformer(), -): - """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 fleetengine 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-fleetengine/v1/setup.py b/owl-bot-staging/google-maps-fleetengine/v1/setup.py deleted file mode 100644 index b805ff698554..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine' - - -description = "Google Maps Fleetengine API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/fleetengine/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-fleetengine" - -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-fleetengine/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.7.txt deleted file mode 100644 index 277853c664a0..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/tests/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py deleted file mode 100644 index ce5c3361748e..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py +++ /dev/null @@ -1,3085 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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.fleetengine_v1.services.trip_service import TripServiceAsyncClient -from google.maps.fleetengine_v1.services.trip_service import TripServiceClient -from google.maps.fleetengine_v1.services.trip_service import pagers -from google.maps.fleetengine_v1.services.trip_service import transports -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import header -from google.maps.fleetengine_v1.types import traffic -from google.maps.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_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 TripServiceClient._get_default_mtls_endpoint(None) is None - assert TripServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TripServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TripServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TripServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TripServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert TripServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert TripServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert TripServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - TripServiceClient._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 TripServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert TripServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert TripServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - TripServiceClient._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 TripServiceClient._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 TripServiceClient._get_client_cert_source(None, False) is None - assert TripServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert TripServiceClient._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 TripServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert TripServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = TripServiceClient._DEFAULT_UNIVERSE - default_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert TripServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert TripServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TripServiceClient.DEFAULT_MTLS_ENDPOINT - assert TripServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert TripServiceClient._get_api_endpoint(None, None, default_universe, "always") == TripServiceClient.DEFAULT_MTLS_ENDPOINT - assert TripServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TripServiceClient.DEFAULT_MTLS_ENDPOINT - assert TripServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert TripServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - TripServiceClient._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 TripServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert TripServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert TripServiceClient._get_universe_domain(None, None) == TripServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - TripServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (TripServiceClient, "grpc"), - (TripServiceAsyncClient, "grpc_asyncio"), -]) -def test_trip_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 == ( - 'fleetengine.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.TripServiceGrpcTransport, "grpc"), - (transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_trip_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", [ - (TripServiceClient, "grpc"), - (TripServiceAsyncClient, "grpc_asyncio"), -]) -def test_trip_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 == ( - 'fleetengine.googleapis.com:443' - ) - - -def test_trip_service_client_get_transport_class(): - transport = TripServiceClient.get_transport_class() - available_transports = [ - transports.TripServiceGrpcTransport, - ] - assert transport in available_transports - - transport = TripServiceClient.get_transport_class("grpc") - assert transport == transports.TripServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) -def test_trip_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(TripServiceClient, '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(TripServiceClient, '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", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", "true"), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", "false"), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_trip_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", [ - TripServiceClient, TripServiceAsyncClient -]) -@mock.patch.object(TripServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TripServiceAsyncClient)) -def test_trip_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", [ - TripServiceClient, TripServiceAsyncClient -]) -@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) -def test_trip_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = TripServiceClient._DEFAULT_UNIVERSE - default_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = TripServiceClient._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", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_trip_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", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", grpc_helpers), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_trip_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_trip_service_client_client_options_from_dict(): - with mock.patch('google.maps.fleetengine_v1.services.trip_service.transports.TripServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TripServiceClient( - 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", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", grpc_helpers), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_trip_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( - "fleetengine.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="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - trip_api.CreateTripRequest, - dict, -]) -def test_create_trip(request_type, transport: str = 'grpc'): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - ) - response = client.create_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.CreateTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -def test_create_trip_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = trip_api.CreateTripRequest( - parent='parent_value', - trip_id='trip_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_trip(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.CreateTripRequest( - parent='parent_value', - trip_id='trip_id_value', - ) - -def test_create_trip_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_trip in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_trip] = mock_rpc - request = {} - client.create_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_trip(request) - - # Establish that a new wrapper 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_trip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_trip in client._client._transport._wrapped_methods - - # 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_trip] = mock_rpc - - request = {} - await client.create_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_trip(request) - - # Establish that a new wrapper 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_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.CreateTripRequest): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - response = await client.create_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.CreateTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -@pytest.mark.asyncio -async def test_create_trip_async_from_dict(): - await test_create_trip_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - trip_api.GetTripRequest, - dict, -]) -def test_get_trip(request_type, transport: str = 'grpc'): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - ) - response = client.get_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.GetTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -def test_get_trip_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = trip_api.GetTripRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_trip(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.GetTripRequest( - name='name_value', - ) - -def test_get_trip_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_trip in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_trip] = mock_rpc - request = {} - client.get_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_trip(request) - - # Establish that a new wrapper 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_trip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_trip in client._client._transport._wrapped_methods - - # 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_trip] = mock_rpc - - request = {} - await client.get_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_trip(request) - - # Establish that a new wrapper 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_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.GetTripRequest): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - response = await client.get_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.GetTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -@pytest.mark.asyncio -async def test_get_trip_async_from_dict(): - await test_get_trip_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - trip_api.ReportBillableTripRequest, - dict, -]) -def test_report_billable_trip(request_type, transport: str = 'grpc'): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.report_billable_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.ReportBillableTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_report_billable_trip_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = trip_api.ReportBillableTripRequest( - name='name_value', - country_code='country_code_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.report_billable_trip(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.ReportBillableTripRequest( - name='name_value', - country_code='country_code_value', - ) - -def test_report_billable_trip_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.report_billable_trip in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.report_billable_trip] = mock_rpc - request = {} - client.report_billable_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.report_billable_trip(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_report_billable_trip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.report_billable_trip in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.report_billable_trip] = mock_rpc - - request = {} - await client.report_billable_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.report_billable_trip(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_report_billable_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.ReportBillableTripRequest): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.report_billable_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.ReportBillableTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_report_billable_trip_async_from_dict(): - await test_report_billable_trip_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - trip_api.SearchTripsRequest, - dict, -]) -def test_search_trips(request_type, transport: str = 'grpc'): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_trips), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trip_api.SearchTripsResponse( - next_page_token='next_page_token_value', - ) - response = client.search_trips(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.SearchTripsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchTripsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_trips_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = trip_api.SearchTripsRequest( - parent='parent_value', - vehicle_id='vehicle_id_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_trips), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search_trips(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.SearchTripsRequest( - parent='parent_value', - vehicle_id='vehicle_id_value', - page_token='page_token_value', - ) - -def test_search_trips_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_trips in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_trips] = mock_rpc - request = {} - client.search_trips(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_trips(request) - - # Establish that a new wrapper 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_trips_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_trips in client._client._transport._wrapped_methods - - # 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_trips] = mock_rpc - - request = {} - await client.search_trips(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.search_trips(request) - - # Establish that a new wrapper 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_trips_async(transport: str = 'grpc_asyncio', request_type=trip_api.SearchTripsRequest): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_trips), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_trips(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.SearchTripsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchTripsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_trips_async_from_dict(): - await test_search_trips_async(request_type=dict) - - -def test_search_trips_pager(transport_name: str = "grpc"): - client = TripServiceClient( - 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_trips), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - trips.Trip(), - ], - next_page_token='abc', - ), - trip_api.SearchTripsResponse( - trips=[], - next_page_token='def', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - ], - next_page_token='ghi', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.search_trips(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, trips.Trip) - for i in results) -def test_search_trips_pages(transport_name: str = "grpc"): - client = TripServiceClient( - 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_trips), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - trips.Trip(), - ], - next_page_token='abc', - ), - trip_api.SearchTripsResponse( - trips=[], - next_page_token='def', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - ], - next_page_token='ghi', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - ], - ), - RuntimeError, - ) - pages = list(client.search_trips(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_trips_async_pager(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - trips.Trip(), - ], - next_page_token='abc', - ), - trip_api.SearchTripsResponse( - trips=[], - next_page_token='def', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - ], - next_page_token='ghi', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_trips(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, trips.Trip) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_trips_async_pages(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - trips.Trip(), - ], - next_page_token='abc', - ), - trip_api.SearchTripsResponse( - trips=[], - next_page_token='def', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - ], - next_page_token='ghi', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - ], - ), - 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_trips(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", [ - trip_api.UpdateTripRequest, - dict, -]) -def test_update_trip(request_type, transport: str = 'grpc'): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - ) - response = client.update_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.UpdateTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -def test_update_trip_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = trip_api.UpdateTripRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_trip(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.UpdateTripRequest( - name='name_value', - ) - -def test_update_trip_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_trip in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_trip] = mock_rpc - request = {} - client.update_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_trip(request) - - # Establish that a new wrapper 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_trip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_trip in client._client._transport._wrapped_methods - - # 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_trip] = mock_rpc - - request = {} - await client.update_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_trip(request) - - # Establish that a new wrapper 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_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.UpdateTripRequest): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - response = await client.update_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.UpdateTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -@pytest.mark.asyncio -async def test_update_trip_async_from_dict(): - await test_update_trip_async(request_type=dict) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TripServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TripServiceClient( - 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 = TripServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TripServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TripServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TripServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TripServiceGrpcTransport, - transports.TripServiceGrpcAsyncIOTransport, -]) -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 = TripServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = TripServiceClient( - 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_trip_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.create_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.CreateTripRequest() - - assert args[0] == request_msg - - -# This 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_trip_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.get_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.GetTripRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_report_billable_trip_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - call.return_value = None - client.report_billable_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.ReportBillableTripRequest() - - assert args[0] == request_msg - - -# This 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_trips_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - call.return_value = trip_api.SearchTripsResponse() - client.search_trips(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.SearchTripsRequest() - - assert args[0] == request_msg - - -# This 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_trip_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.update_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.UpdateTripRequest() - - assert args[0] == request_msg - - -def test_create_trip_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.create_trip(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.CreateTripRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_trip_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.get_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.GetTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_report_billable_trip_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - call.return_value = None - client.report_billable_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.ReportBillableTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_search_trips_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - call.return_value = trip_api.SearchTripsResponse() - client.search_trips(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.SearchTripsRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_trip_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.update_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.UpdateTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_kind_grpc_asyncio(): - transport = TripServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = TripServiceAsyncClient( - 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_trip_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.create_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.CreateTripRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_trip_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.get_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.GetTripRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_report_billable_trip_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.report_billable_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.ReportBillableTripRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_trips_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( - next_page_token='next_page_token_value', - )) - await client.search_trips(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.SearchTripsRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_trip_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.update_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.UpdateTripRequest() - - assert args[0] == request_msg - - -@pytest.mark.asyncio -async def test_create_trip_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.create_trip(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.CreateTripRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_get_trip_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.get_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.GetTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_report_billable_trip_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.report_billable_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.ReportBillableTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_search_trips_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( - next_page_token='next_page_token_value', - )) - await client.search_trips(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.SearchTripsRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_update_trip_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.update_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.UpdateTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TripServiceGrpcTransport, - ) - -def test_trip_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TripServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_trip_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.fleetengine_v1.services.trip_service.transports.TripServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TripServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_trip', - 'get_trip', - 'report_billable_trip', - 'search_trips', - 'update_trip', - ) - 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_trip_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.maps.fleetengine_v1.services.trip_service.transports.TripServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TripServiceTransport( - 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_trip_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.maps.fleetengine_v1.services.trip_service.transports.TripServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TripServiceTransport() - adc.assert_called_once() - - -def test_trip_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) - TripServiceClient() - 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.TripServiceGrpcTransport, - transports.TripServiceGrpcAsyncIOTransport, - ], -) -def test_trip_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/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TripServiceGrpcTransport, - transports.TripServiceGrpcAsyncIOTransport, - ], -) -def test_trip_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.TripServiceGrpcTransport, grpc_helpers), - (transports.TripServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_trip_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( - "fleetengine.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="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) -def test_trip_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_trip_service_host_no_port(transport_name): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_trip_service_host_with_port(transport_name): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:8000' - ) - -def test_trip_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TripServiceGrpcTransport( - 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_trip_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TripServiceGrpcAsyncIOTransport( - 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.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) -def test_trip_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.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) -def test_trip_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_trip_path(): - provider = "squid" - trip = "clam" - expected = "providers/{provider}/trips/{trip}".format(provider=provider, trip=trip, ) - actual = TripServiceClient.trip_path(provider, trip) - assert expected == actual - - -def test_parse_trip_path(): - expected = { - "provider": "whelk", - "trip": "octopus", - } - path = TripServiceClient.trip_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.parse_trip_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TripServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = TripServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = TripServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = TripServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TripServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = TripServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = TripServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = TripServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.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 = TripServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = TripServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.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.TripServiceTransport, '_prep_wrapped_messages') as prep: - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TripServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = TripServiceClient.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 = TripServiceClient( - 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 = TripServiceAsyncClient( - 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_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = TripServiceClient( - 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", [ - (TripServiceClient, transports.TripServiceGrpcTransport), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport), -]) -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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py deleted file mode 100644 index 39ac26e13afb..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py +++ /dev/null @@ -1,3340 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 - -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.fleetengine_v1.services.vehicle_service import VehicleServiceAsyncClient -from google.maps.fleetengine_v1.services.vehicle_service import VehicleServiceClient -from google.maps.fleetengine_v1.services.vehicle_service import pagers -from google.maps.fleetengine_v1.services.vehicle_service import transports -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import header -from google.maps.fleetengine_v1.types import traffic -from google.maps.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_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 VehicleServiceClient._get_default_mtls_endpoint(None) is None - assert VehicleServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert VehicleServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert VehicleServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert VehicleServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert VehicleServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert VehicleServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - VehicleServiceClient._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 VehicleServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert VehicleServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - VehicleServiceClient._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 VehicleServiceClient._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 VehicleServiceClient._get_client_cert_source(None, False) is None - assert VehicleServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert VehicleServiceClient._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 VehicleServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert VehicleServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = VehicleServiceClient._DEFAULT_UNIVERSE - default_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert VehicleServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert VehicleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "always") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - assert VehicleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - assert VehicleServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - VehicleServiceClient._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 VehicleServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert VehicleServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert VehicleServiceClient._get_universe_domain(None, None) == VehicleServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - VehicleServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (VehicleServiceClient, "grpc"), - (VehicleServiceAsyncClient, "grpc_asyncio"), -]) -def test_vehicle_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 == ( - 'fleetengine.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VehicleServiceGrpcTransport, "grpc"), - (transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_vehicle_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", [ - (VehicleServiceClient, "grpc"), - (VehicleServiceAsyncClient, "grpc_asyncio"), -]) -def test_vehicle_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 == ( - 'fleetengine.googleapis.com:443' - ) - - -def test_vehicle_service_client_get_transport_class(): - transport = VehicleServiceClient.get_transport_class() - available_transports = [ - transports.VehicleServiceGrpcTransport, - ] - assert transport in available_transports - - transport = VehicleServiceClient.get_transport_class("grpc") - assert transport == transports.VehicleServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) -def test_vehicle_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(VehicleServiceClient, '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(VehicleServiceClient, '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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", "true"), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", "false"), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_vehicle_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", [ - VehicleServiceClient, VehicleServiceAsyncClient -]) -@mock.patch.object(VehicleServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VehicleServiceAsyncClient)) -def test_vehicle_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", [ - VehicleServiceClient, VehicleServiceAsyncClient -]) -@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) -def test_vehicle_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = VehicleServiceClient._DEFAULT_UNIVERSE - default_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = VehicleServiceClient._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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_vehicle_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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", grpc_helpers), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_vehicle_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_vehicle_service_client_client_options_from_dict(): - with mock.patch('google.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = VehicleServiceClient( - 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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", grpc_helpers), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_vehicle_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( - "fleetengine.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="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.CreateVehicleRequest, - dict, -]) -def test_create_vehicle(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - ) - response = client.create_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.CreateVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -def test_create_vehicle_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = vehicle_api.CreateVehicleRequest( - parent='parent_value', - vehicle_id='vehicle_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.CreateVehicleRequest( - parent='parent_value', - vehicle_id='vehicle_id_value', - ) - -def test_create_vehicle_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_vehicle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vehicle] = mock_rpc - request = {} - client.create_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_vehicle(request) - - # Establish that a new wrapper 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_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_vehicle in client._client._transport._wrapped_methods - - # 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_vehicle] = mock_rpc - - request = {} - await client.create_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_vehicle(request) - - # Establish that a new wrapper 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_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.CreateVehicleRequest): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - response = await client.create_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.CreateVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -@pytest.mark.asyncio -async def test_create_vehicle_async_from_dict(): - await test_create_vehicle_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.GetVehicleRequest, - dict, -]) -def test_get_vehicle(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - ) - response = client.get_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.GetVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -def test_get_vehicle_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = vehicle_api.GetVehicleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.GetVehicleRequest( - name='name_value', - ) - -def test_get_vehicle_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_vehicle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_vehicle] = mock_rpc - request = {} - client.get_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_vehicle(request) - - # Establish that a new wrapper 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_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_vehicle in client._client._transport._wrapped_methods - - # 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_vehicle] = mock_rpc - - request = {} - await client.get_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_vehicle(request) - - # Establish that a new wrapper 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_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.GetVehicleRequest): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - response = await client.get_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.GetVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -@pytest.mark.asyncio -async def test_get_vehicle_async_from_dict(): - await test_get_vehicle_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.UpdateVehicleRequest, - dict, -]) -def test_update_vehicle(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - ) - response = client.update_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -def test_update_vehicle_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = vehicle_api.UpdateVehicleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.UpdateVehicleRequest( - name='name_value', - ) - -def test_update_vehicle_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_vehicle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vehicle] = mock_rpc - request = {} - client.update_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_vehicle(request) - - # Establish that a new wrapper 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_vehicle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_vehicle in client._client._transport._wrapped_methods - - # 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_vehicle] = mock_rpc - - request = {} - await client.update_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_vehicle(request) - - # Establish that a new wrapper 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_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.UpdateVehicleRequest): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - response = await client.update_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -@pytest.mark.asyncio -async def test_update_vehicle_async_from_dict(): - await test_update_vehicle_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.UpdateVehicleAttributesRequest, - dict, -]) -def test_update_vehicle_attributes(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicle_attributes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicle_api.UpdateVehicleAttributesResponse( - ) - response = client.update_vehicle_attributes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleAttributesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.UpdateVehicleAttributesResponse) - - -def test_update_vehicle_attributes_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = vehicle_api.UpdateVehicleAttributesRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_vehicle_attributes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.UpdateVehicleAttributesRequest( - name='name_value', - ) - -def test_update_vehicle_attributes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_vehicle_attributes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vehicle_attributes] = mock_rpc - request = {} - client.update_vehicle_attributes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_vehicle_attributes(request) - - # Establish that a new wrapper 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_vehicle_attributes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_vehicle_attributes in client._client._transport._wrapped_methods - - # 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_vehicle_attributes] = mock_rpc - - request = {} - await client.update_vehicle_attributes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_vehicle_attributes(request) - - # Establish that a new wrapper 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_vehicle_attributes_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.UpdateVehicleAttributesRequest): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicle_attributes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( - )) - response = await client.update_vehicle_attributes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleAttributesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.UpdateVehicleAttributesResponse) - - -@pytest.mark.asyncio -async def test_update_vehicle_attributes_async_from_dict(): - await test_update_vehicle_attributes_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.ListVehiclesRequest, - dict, -]) -def test_list_vehicles(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicle_api.ListVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.ListVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVehiclesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_vehicles_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = vehicle_api.ListVehiclesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_vehicles(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.ListVehiclesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_vehicles_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_vehicles in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vehicles] = mock_rpc - request = {} - client.list_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_vehicles(request) - - # Establish that a new wrapper 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_vehicles_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_vehicles in client._client._transport._wrapped_methods - - # 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_vehicles] = mock_rpc - - request = {} - await client.list_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_vehicles(request) - - # Establish that a new wrapper 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_vehicles_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.ListVehiclesRequest): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.ListVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVehiclesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_vehicles_async_from_dict(): - await test_list_vehicles_async(request_type=dict) - - -def test_list_vehicles_pager(transport_name: str = "grpc"): - client = VehicleServiceClient( - 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_vehicles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - next_page_token='abc', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[], - next_page_token='def', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - ], - next_page_token='ghi', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_vehicles(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, vehicles.Vehicle) - for i in results) -def test_list_vehicles_pages(transport_name: str = "grpc"): - client = VehicleServiceClient( - 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_vehicles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - next_page_token='abc', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[], - next_page_token='def', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - ], - next_page_token='ghi', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - ), - RuntimeError, - ) - pages = list(client.list_vehicles(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_vehicles_async_pager(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - next_page_token='abc', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[], - next_page_token='def', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - ], - next_page_token='ghi', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_vehicles(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, vehicles.Vehicle) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_vehicles_async_pages(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - next_page_token='abc', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[], - next_page_token='def', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - ], - next_page_token='ghi', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - ), - 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_vehicles(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", [ - vehicle_api.SearchVehiclesRequest, - dict, -]) -def test_search_vehicles(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicle_api.SearchVehiclesResponse( - ) - response = client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.SearchVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.SearchVehiclesResponse) - - -def test_search_vehicles_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = vehicle_api.SearchVehiclesRequest( - parent='parent_value', - trip_id='trip_id_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search_vehicles(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.SearchVehiclesRequest( - parent='parent_value', - trip_id='trip_id_value', - filter='filter_value', - ) - -def test_search_vehicles_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_vehicles in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vehicles] = mock_rpc - request = {} - client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_vehicles(request) - - # Establish that a new wrapper 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_vehicles_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_vehicles in client._client._transport._wrapped_methods - - # 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_vehicles] = mock_rpc - - request = {} - await client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.search_vehicles(request) - - # Establish that a new wrapper 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_vehicles_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.SearchVehiclesRequest): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( - )) - response = await client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.SearchVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.SearchVehiclesResponse) - - -@pytest.mark.asyncio -async def test_search_vehicles_async_from_dict(): - await test_search_vehicles_async(request_type=dict) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VehicleServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = VehicleServiceClient( - 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 = VehicleServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VehicleServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = VehicleServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.VehicleServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.VehicleServiceGrpcTransport, - transports.VehicleServiceGrpcAsyncIOTransport, -]) -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 = VehicleServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = VehicleServiceClient( - 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_vehicle_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.create_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.CreateVehicleRequest() - - assert args[0] == request_msg - - -# This 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_vehicle_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.get_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.GetVehicleRequest() - - assert args[0] == request_msg - - -# This 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_vehicle_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.update_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleRequest() - - assert args[0] == request_msg - - -# This 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_vehicle_attributes_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - call.return_value = vehicle_api.UpdateVehicleAttributesResponse() - client.update_vehicle_attributes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleAttributesRequest() - - assert args[0] == request_msg - - -# This 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_vehicles_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - call.return_value = vehicle_api.ListVehiclesResponse() - client.list_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.ListVehiclesRequest() - - assert args[0] == request_msg - - -# This 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_vehicles_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - call.return_value = vehicle_api.SearchVehiclesResponse() - client.search_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.SearchVehiclesRequest() - - assert args[0] == request_msg - - -def test_create_vehicle_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.create_vehicle(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.CreateVehicleRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_vehicle_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.get_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.GetVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_vehicle_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.update_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_vehicle_attributes_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - call.return_value = vehicle_api.UpdateVehicleAttributesResponse() - client.update_vehicle_attributes(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleAttributesRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_list_vehicles_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - call.return_value = vehicle_api.ListVehiclesResponse() - client.list_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.ListVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_search_vehicles_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - call.return_value = vehicle_api.SearchVehiclesResponse() - client.search_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_kind_grpc_asyncio(): - transport = VehicleServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = VehicleServiceAsyncClient( - 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_vehicle_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.create_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.CreateVehicleRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_vehicle_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.get_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.GetVehicleRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_vehicle_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.update_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_vehicle_attributes_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( - )) - await client.update_vehicle_attributes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleAttributesRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_vehicles_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.ListVehiclesRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_vehicles_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( - )) - await client.search_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.SearchVehiclesRequest() - - assert args[0] == request_msg - - -@pytest.mark.asyncio -async def test_create_vehicle_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.create_vehicle(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.CreateVehicleRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_get_vehicle_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.get_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.GetVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_update_vehicle_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.update_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_update_vehicle_attributes_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( - )) - await client.update_vehicle_attributes(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleAttributesRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_list_vehicles_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.ListVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_search_vehicles_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( - )) - await client.search_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VehicleServiceGrpcTransport, - ) - -def test_vehicle_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.VehicleServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_vehicle_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.VehicleServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_vehicle', - 'get_vehicle', - 'update_vehicle', - 'update_vehicle_attributes', - 'list_vehicles', - 'search_vehicles', - ) - 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_vehicle_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.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VehicleServiceTransport( - 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_vehicle_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.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VehicleServiceTransport() - adc.assert_called_once() - - -def test_vehicle_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) - VehicleServiceClient() - 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.VehicleServiceGrpcTransport, - transports.VehicleServiceGrpcAsyncIOTransport, - ], -) -def test_vehicle_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/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VehicleServiceGrpcTransport, - transports.VehicleServiceGrpcAsyncIOTransport, - ], -) -def test_vehicle_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.VehicleServiceGrpcTransport, grpc_helpers), - (transports.VehicleServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_vehicle_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( - "fleetengine.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="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) -def test_vehicle_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_vehicle_service_host_no_port(transport_name): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_vehicle_service_host_with_port(transport_name): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:8000' - ) - -def test_vehicle_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VehicleServiceGrpcTransport( - 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_vehicle_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VehicleServiceGrpcAsyncIOTransport( - 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.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) -def test_vehicle_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.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) -def test_vehicle_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_vehicle_path(): - provider = "squid" - vehicle = "clam" - expected = "providers/{provider}/vehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) - actual = VehicleServiceClient.vehicle_path(provider, vehicle) - assert expected == actual - - -def test_parse_vehicle_path(): - expected = { - "provider": "whelk", - "vehicle": "octopus", - } - path = VehicleServiceClient.vehicle_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.parse_vehicle_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = VehicleServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = VehicleServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = VehicleServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = VehicleServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VehicleServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = VehicleServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = VehicleServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = VehicleServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.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 = VehicleServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = VehicleServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.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.VehicleServiceTransport, '_prep_wrapped_messages') as prep: - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.VehicleServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = VehicleServiceClient.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 = VehicleServiceClient( - 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 = VehicleServiceAsyncClient( - 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_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = VehicleServiceClient( - 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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport), -]) -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-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 1b704ccdc187..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/async_client.py +++ /dev/null @@ -1,907 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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 4839d35b574d..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/client.py +++ /dev/null @@ -1,1258 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = MapsPlatformDatasetsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - MapsPlatformDatasetsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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 9bb35d1acfb2..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/pagers.py +++ /dev/null @@ -1,299 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 4a399925dcf4..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc.py +++ /dev/null @@ -1,403 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 96bc3c4511b3..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/grpc_asyncio.py +++ /dev/null @@ -1,476 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 7b4183f36a90..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/google/maps/mapsplatformdatasets_v1/services/maps_platform_datasets/transports/rest.py +++ /dev/null @@ -1,787 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[maps_platform_datasets.CreateDatasetRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[maps_platform_datasets.DeleteDatasetRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[maps_platform_datasets.FetchDatasetErrorsRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[maps_platform_datasets.GetDatasetRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[maps_platform_datasets.ListDatasetsRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[maps_platform_datasets.UpdateDatasetMetadataRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 ef06d5878d41..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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.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 85e0ad71af9f..000000000000 --- a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/tests/unit/gapic/mapsplatformdatasets_v1/test_maps_platform_datasets.py +++ /dev/null @@ -1,6146 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsGrpcTransport, "grpc"), - (MapsPlatformDatasetsClient, transports.MapsPlatformDatasetsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 da49a941ee60..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places/__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.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.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', - '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 3c5e4f5b980e..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_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.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.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', -'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 87bbcc56beb4..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py +++ /dev/null @@ -1,691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 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 - - -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, - - ) - - 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]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 d0cc9cedf8e3..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py +++ /dev/null @@ -1,1073 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PlacesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - PlacesClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 c860eeb19cfa..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 56c4c2a197aa..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py +++ /dev/null @@ -1,421 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 de4d01a7ca8f..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[places_service.AutocompletePlacesRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[places_service.GetPhotoMediaRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[places_service.GetPlaceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[places_service.SearchNearbyRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[places_service.SearchTextRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 013126637ac4..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py +++ /dev/null @@ -1,104 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 .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', - '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 36525aff107f..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py +++ /dev/null @@ -1,1208 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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 reference -from google.maps.places_v1.types import review -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. - 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): - The business status for the place. - 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. - """ - 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. - """ - 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', - ) - - 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, - ) - - 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, - ) - - -__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 6abdcd07f4c2..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py +++ /dev/null @@ -1,1316 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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. - """ - 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, - ) - - -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. - """ - - 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, - ) - - -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/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 121b25b6cd0b..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.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 __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. - """ - - 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, - ) - - -__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 74eb224b30a6..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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 886ede01a438..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', ), - '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', ), - } - - 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.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 ffcaa117ba26..000000000000 --- a/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py +++ /dev/null @@ -1,4498 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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_class,transport_name", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc"), - (PlacesClient, transports.PlacesRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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, - ) - 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 - - -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, - )) - 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 - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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, - )) - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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, - ) - - # Wrap 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 - 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 - - -@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 - 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 - 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 - 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 - 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 d21fc35ea40a..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/async_client.py +++ /dev/null @@ -1,548 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 437dbebd654f..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/client.py +++ /dev/null @@ -1,898 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - RouteOptimizationClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 166140484608..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py +++ /dev/null @@ -1,394 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 1152e68b64ba..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 cc0cee239709..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[route_optimization_service.BatchOptimizeToursRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[route_optimization_service.OptimizeToursRequest, Sequence[Tuple[str, str]]]: - """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, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 c329d83ca2a2..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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.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 b292a592bc35..000000000000 --- a/owl-bot-staging/google-maps-routeoptimization/v1/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py +++ /dev/null @@ -1,2749 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc"), - (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 6435ad0166ed..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.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 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.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', - '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 cdae66b5d7f6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py +++ /dev/null @@ -1,114 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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', -'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 3315c0768267..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.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. -# -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 - - -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, - - ) - - 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]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 9276016535fb..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py +++ /dev/null @@ -1,808 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RoutesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - RoutesClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 223360b6ba76..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.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 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 - -import grpc # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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 e4752aeff4c2..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py +++ /dev/null @@ -1,395 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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 e62eb44c3f16..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 56fa2a5f9cbb..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.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 .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 .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', - '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/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py deleted file mode 100644 index e2353aaa6c46..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py +++ /dev/null @@ -1,787 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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 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): - A web-safe, base64-encoded route token that can be passed to - the Navigation SDK, that allows the Navigation SDK to - reconstruct the route during navigation, and, in the event - of rerouting, honor the original intention when you created - the route by calling ComputeRoutes. Customers should treat - this token as an opaque blob. It is not meant for reading or - mutating. 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. - """ - - 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 taking traffic conditions into consideration, - represented in text form. Note: If you did not request - traffic information, this value will be 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, - ) - - -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 taking traffic conditions into consideration - represented in text form. Note: If you did not request - traffic information, this value will be 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 will return 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 afa49bc25ec3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.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 - - -__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. - """ - ROUTE_LABEL_UNSPECIFIED = 0 - DEFAULT_ROUTE = 1 - DEFAULT_ROUTE_ALTERNATE = 2 - FUEL_EFFICIENT = 3 - - -__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 622d38e9f513..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py +++ /dev/null @@ -1,713 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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. - 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. Routes labeled with - this value are determined to be optimized for - parameters such as fuel consumption. - """ - REFERENCE_ROUTE_UNSPECIFIED = 0 - FUEL_EFFICIENT = 1 - - 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. - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - FUEL_CONSUMPTION = 2 - TRAFFIC_ON_POLYLINE = 3 - HTML_FORMATTED_NAVIGATION_INSTRUCTIONS = 4 - - 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 b5ed5aca319c..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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.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 313833af9740..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py +++ /dev/null @@ -1,2389 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 f554e566179b..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/async_client.py +++ /dev/null @@ -1,521 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 0b3a35d70db6..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/client.py +++ /dev/null @@ -1,869 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SolarClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - SolarClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 86aa6371b33d..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc.py +++ /dev/null @@ -1,327 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 e0313519f457..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/grpc_asyncio.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 inspect -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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 d1a651b34c9f..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/google/maps/solar_v1/services/solar/transports/rest.py +++ /dev/null @@ -1,548 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[solar_service.FindClosestBuildingInsightsRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[solar_service.GetDataLayersRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[solar_service.GetGeoTiffRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 ef51a4e54a98..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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 d2237d436239..000000000000 --- a/owl-bot-staging/google-maps-solar/v1/tests/unit/gapic/solar_v1/test_solar.py +++ /dev/null @@ -1,2921 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (SolarClient, transports.SolarGrpcTransport, "grpc"), - (SolarClient, transports.SolarRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 9899f408e93a..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,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. -# -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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 2d2824f1c687..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py +++ /dev/null @@ -1,722 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - AccountIssueServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 122c88fcdd42..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 be25edbe0083..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,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. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_accounts_v1beta.types import accountissue -from .base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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 5b7a4183cac6..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,292 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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 640f0e42e6c4..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,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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[accountissue.ListAccountIssuesRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 898b44e47160..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,588 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 01464cb91e35..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py +++ /dev/null @@ -1,942 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AccountTaxServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - AccountTaxServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 4560040913d8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 d7dc1b538d8f..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,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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 f4eb0d3545b4..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,362 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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 cc25b5101013..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,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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[account_tax.GetAccountTaxRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[account_tax.ListAccountTaxRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[gsma_account_tax.UpdateAccountTaxRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 faf90a89aa38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py +++ /dev/null @@ -1,852 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 98314e11111e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py +++ /dev/null @@ -1,1223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AccountsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - AccountsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 6037fc9d2088..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.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. -# -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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 edf844a7f9cb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py +++ /dev/null @@ -1,425 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 2bca1715b1bd..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,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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 a061c830710c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py +++ /dev/null @@ -1,776 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[accounts.CreateAndConfigureAccountRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[accounts.DeleteAccountRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[accounts.GetAccountRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[accounts.ListAccountsRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[accounts.ListSubAccountsRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[accounts.UpdateAccountRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 dfaf606e984d..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,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. -# -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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 68ef500d876e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - AutofeedSettingsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 50ad69088c3d..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,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 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 - -import grpc # type: ignore - -from google.shopping.merchant_accounts_v1beta.types import autofeedsettings -from .base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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 05630ed2ec4c..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,324 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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 fdab84a4ef27..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,388 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[autofeedsettings.GetAutofeedSettingsRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[autofeedsettings.UpdateAutofeedSettingsRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 8b90bcaca5a0..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,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. -# -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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 417dd9888206..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py +++ /dev/null @@ -1,811 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - BusinessIdentityServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 ebb5eb52c5cb..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,299 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_accounts_v1beta.types import businessidentity -from .base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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 8d25c39f5f65..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,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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 adbecd00c412..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,386 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[businessidentity.GetBusinessIdentityRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[businessidentity.UpdateBusinessIdentityRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 c00c2f39652f..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,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. -# -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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 43a447b9ae4c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py +++ /dev/null @@ -1,811 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - BusinessInfoServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 a349e040aae9..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,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 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 - -import grpc # type: ignore - -from google.shopping.merchant_accounts_v1beta.types import businessinfo -from .base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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 8d9e9033679a..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,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. -# -import inspect -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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 004e8f128d83..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,383 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[businessinfo.GetBusinessInfoRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[businessinfo.UpdateBusinessInfoRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 aa73583a2cc2..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,479 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 b523557c5e94..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py +++ /dev/null @@ -1,834 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - EmailPreferencesServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 3f350752550c..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,314 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_accounts_v1beta.types import emailpreferences -from .base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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 01fd96f5467f..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,340 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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 2c5de44d62aa..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,394 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[emailpreferences.GetEmailPreferencesRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[emailpreferences.UpdateEmailPreferencesRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 ec74d511cd5c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py +++ /dev/null @@ -1,622 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 df7e12407870..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py +++ /dev/null @@ -1,977 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = HomepageServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - HomepageServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 a73262d323dc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py +++ /dev/null @@ -1,363 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 08628e7ebbda..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,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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 970a5bde38cd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[homepage.ClaimHomepageRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[homepage.GetHomepageRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[homepage.UnclaimHomepageRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[gsma_homepage.UpdateHomepageRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 6da68a5145f7..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,469 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 2bd3afa96ef8..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,824 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - OnlineReturnPolicyServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 9fd3c13bd2b7..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,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 e432f27210a4..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,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_accounts_v1beta.types import online_return_policy -from .base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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 8c14071044b6..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,329 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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 0aee419bb6a2..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,392 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[online_return_policy.GetOnlineReturnPolicyRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 5db2fa88d13b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py +++ /dev/null @@ -1,702 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 5fd5f217add7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py +++ /dev/null @@ -1,1055 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - ProgramsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 d57324925688..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 b01a291b0617..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py +++ /dev/null @@ -1,361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_accounts_v1beta.types import programs -from .base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 2b16365bfc5e..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,397 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 20bac24f2675..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py +++ /dev/null @@ -1,633 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[programs.DisableProgramRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[programs.EnableProgramRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[programs.GetProgramRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[programs.ListProgramsRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 7a02c6bb9453..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py +++ /dev/null @@ -1,806 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 45a0c3fac17c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - RegionsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 e83bfb7f2a9c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 8e3af8236efa..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py +++ /dev/null @@ -1,383 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 e896ab29d57f..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,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. -# -import inspect -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 055992213f8a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py +++ /dev/null @@ -1,698 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[regions.CreateRegionRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[regions.DeleteRegionRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[regions.GetRegionRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[regions.ListRegionsRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[regions.UpdateRegionRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 df4b61a377b1..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,430 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 3a236fd28324..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.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. -# -from collections import OrderedDict -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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - ShippingSettingsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 7a42cd6d2a9a..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,299 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_accounts_v1beta.types import shippingsettings -from .base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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 f63a8f4ad5ff..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,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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 8355e989f928..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,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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[shippingsettings.GetShippingSettingsRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[shippingsettings.InsertShippingSettingsRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 0eb347e1fbce..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,504 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 bc097f3ec698..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,877 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - TermsOfServiceAgreementStateServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 7e36e15daf7c..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,299 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate -from .base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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 c41fe7f7d06c..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,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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 21a9829cb18b..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,437 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 0edaaacf519d..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,509 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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 b3e6c55dc6ae..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,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. -# -from collections import OrderedDict -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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - TermsOfServiceServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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 798751c8879e..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,327 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 048b268abe9f..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,358 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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 8a73fd10954a..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,458 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[termsofservice.AcceptTermsOfServiceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[termsofservice.GetTermsOfServiceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[termsofservice.RetrieveLatestTermsOfServiceRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 abf841495e46..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.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. -# -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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 55400105b84d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py +++ /dev/null @@ -1,1147 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = UserServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - UserServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 ff8061acfe15..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 acc8704ccb00..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py +++ /dev/null @@ -1,379 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 55fb5c24da67..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,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 inspect -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 52497a33dd97..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py +++ /dev/null @@ -1,677 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[gsma_user.CreateUserRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[user.DeleteUserRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[user.GetUserRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[user.ListUsersRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[gsma_user.UpdateUserRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 91ea23ca0671..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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.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 62d7440027f7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py +++ /dev/null @@ -1,2424 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - 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 - 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 - 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 4b63cb73aaae..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py +++ /dev/null @@ -1,3791 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc"), - (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 c7f575e3064c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py +++ /dev/null @@ -1,5618 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 0b2b65162f0c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py +++ /dev/null @@ -1,2887 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 fd5f7208330c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py +++ /dev/null @@ -1,2873 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 8caa1fea3b3f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py +++ /dev/null @@ -1,2891 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 8855b0d1ad64..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py +++ /dev/null @@ -1,2875 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 cb355d0eaf36..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py +++ /dev/null @@ -1,3946 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 ac7ceb319b95..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,3115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 b88075f1c618..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py +++ /dev/null @@ -1,4414 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 9a0f4979db05..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py +++ /dev/null @@ -1,5190 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 - 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 - 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 - 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 d3c971085582..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py +++ /dev/null @@ -1,2731 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 364169d96d19..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,2851 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 8c4f6c788231..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,3324 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 dcdec3d7043f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py +++ /dev/null @@ -1,5200 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), - (UserServiceClient, transports.UserServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 e3cac5caebac..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,894 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 c83087341250..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/client.py +++ /dev/null @@ -1,1246 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ConversionSourcesServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - ConversionSourcesServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 586714c04254..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/google/shopping/merchant_conversions_v1beta/services/conversion_sources_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 1a70db2a347d..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,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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 657b13c2b0b0..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,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 inspect -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 ba02c61eedbc..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,803 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[conversionsources.CreateConversionSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[conversionsources.DeleteConversionSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[conversionsources.GetConversionSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[conversionsources.ListConversionSourcesRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[conversionsources.UndeleteConversionSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[conversionsources.UpdateConversionSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 03a202362a18..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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 2ffccf9a5fc6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-conversions/v1beta/tests/unit/gapic/merchant_conversions_v1beta/test_conversion_sources_service.py +++ /dev/null @@ -1,5696 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceGrpcTransport, "grpc"), - (ConversionSourcesServiceClient, transports.ConversionSourcesServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 99c6fb1959b1..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,879 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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 b37d1dd8e063..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/client.py +++ /dev/null @@ -1,1231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataSourcesServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - DataSourcesServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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 38b65bd1a3ed..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/data_sources_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 13a4d717e4e3..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,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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 b5265cde6875..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,462 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 578acbd1ce7d..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,772 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[datasources.CreateDataSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[datasources.DeleteDataSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[datasources.FetchDataSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[datasources.GetDataSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[datasources.ListDataSourcesRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[datasources.UpdateDataSourceRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 3eb1b5b07a2e..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,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. -# -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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 8afe6378fdba..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/google/shopping/merchant_datasources_v1beta/services/file_uploads_service/client.py +++ /dev/null @@ -1,704 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = FileUploadsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - FileUploadsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 071773dc0ca5..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,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. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_datasources_v1beta.types import fileuploads -from .base import FileUploadsServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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 ef6996006854..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,292 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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 cd6597b70bf8..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,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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[fileuploads.GetFileUploadRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 8af0e5a52d60..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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 0c476161e247..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_data_sources_service.py +++ /dev/null @@ -1,5682 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (DataSourcesServiceClient, transports.DataSourcesServiceGrpcTransport, "grpc"), - (DataSourcesServiceClient, transports.DataSourcesServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 - 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 - 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 - - 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 f55255e283c0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-datasources/v1beta/tests/unit/gapic/merchant_datasources_v1beta/test_file_uploads_service.py +++ /dev/null @@ -1,2177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (FileUploadsServiceClient, transports.FileUploadsServiceGrpcTransport, "grpc"), - (FileUploadsServiceClient, transports.FileUploadsServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - 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 - 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 - 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 a57143cfa523..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,557 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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 cdb582406777..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py +++ /dev/null @@ -1,912 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - LocalInventoryServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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 5871c583a09f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 0be6d5b83b71..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,342 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 003e3774e885..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,373 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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 27455f0a84ad..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,468 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[localinventory.DeleteLocalInventoryRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[localinventory.InsertLocalInventoryRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[localinventory.ListLocalInventoriesRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 4febadd1c18e..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,563 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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 fd6006001569..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py +++ /dev/null @@ -1,918 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - RegionalInventoryServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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 ee92c7526c93..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 8653391dd348..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,343 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 831fffcc6cb1..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,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 inspect -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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 624af3d0a99e..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,472 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[regionalinventory.DeleteRegionalInventoryRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[regionalinventory.InsertRegionalInventoryRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[regionalinventory.ListRegionalInventoriesRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 69c4a31abe8f..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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.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 dc04243af8ed..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py +++ /dev/null @@ -1,3659 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 2a170ce08be0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py +++ /dev/null @@ -1,3631 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 2884af750669..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,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. -# -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 - - -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, - - ) - - 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]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 e3a4a2405b8d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_inventory_service/client.py +++ /dev/null @@ -1,690 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = LfpInventoryServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - LfpInventoryServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 917f427714c7..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,274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_lfp_v1beta.types import lfpinventory -from .base import LfpInventoryServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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 cf456e7875b7..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,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. -# -import inspect -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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 ddb8c5ec385d..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,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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[lfpinventory.InsertLfpInventoryRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 ca50465ec57f..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,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. -# -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 - - -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, - - ) - - 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]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 a9430efaa34a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_sale_service/client.py +++ /dev/null @@ -1,690 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = LfpSaleServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - LfpSaleServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 0d05b5dd995d..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,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. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_lfp_v1beta.types import lfpsale -from .base import LfpSaleServiceTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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 b7e6fa1eb3ad..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,293 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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 83b7ce536cc5..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,278 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[lfpsale.InsertLfpSaleRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 cfeddc832339..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,684 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 a9752c675163..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/client.py +++ /dev/null @@ -1,1037 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = LfpStoreServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - LfpStoreServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 03dd7df91e4f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/google/shopping/merchant_lfp_v1beta/services/lfp_store_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 6fd63b713cf4..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,354 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 fdcfb49a78b7..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,390 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 64366bfd71e8..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,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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[lfpstore.DeleteLfpStoreRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[lfpstore.GetLfpStoreRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[lfpstore.InsertLfpStoreRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[lfpstore.ListLfpStoresRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 e3327910013f..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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.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 e53a578cb2b0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_inventory_service.py +++ /dev/null @@ -1,2152 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (LfpInventoryServiceClient, transports.LfpInventoryServiceGrpcTransport, "grpc"), - (LfpInventoryServiceClient, transports.LfpInventoryServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - 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 - 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 - 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 87e6c59d93b8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_sale_service.py +++ /dev/null @@ -1,2134 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (LfpSaleServiceClient, transports.LfpSaleServiceGrpcTransport, "grpc"), - (LfpSaleServiceClient, transports.LfpSaleServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - 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 - 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 - 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 7dafcb7fadae..000000000000 --- a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/tests/unit/gapic/merchant_lfp_v1beta/test_lfp_store_service.py +++ /dev/null @@ -1,4555 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (LfpStoreServiceClient, transports.LfpStoreServiceGrpcTransport, "grpc"), - (LfpStoreServiceClient, transports.LfpStoreServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 - 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 - 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 - 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 c52ff70d9d59..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,804 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - - -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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 00e3eb53aa9b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/client.py +++ /dev/null @@ -1,1156 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NotificationsApiServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - NotificationsApiServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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 - - 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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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 4579e713049f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/google/shopping/merchant_notifications_v1beta/services/notifications_api_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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, str]] = ()): - """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, str]]): Strings which should be - sent along with the request as metadata. - """ - 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 d1082b9c738f..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,398 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 daaec0eb0334..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,439 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # 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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 3704394b619b..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,691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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 - - -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, str]]) -> Tuple[notificationsapi.CreateNotificationSubscriptionRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[notificationsapi.DeleteNotificationSubscriptionRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[notificationsapi.GetNotificationSubscriptionRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[notificationsapi.ListNotificationSubscriptionsRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[notificationsapi.UpdateNotificationSubscriptionRequest, Sequence[Tuple[str, str]]]: - """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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - 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) - - # 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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) - - # 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) - 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 834227f32181..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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.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 4aa3628ee715..000000000000 --- a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/tests/unit/gapic/merchant_notifications_v1beta/test_notifications_api_service.py +++ /dev/null @@ -1,5172 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_class,transport_name", [ - (NotificationsApiServiceClient, transports.NotificationsApiServiceGrpcTransport, "grpc"), - (NotificationsApiServiceClient, transports.NotificationsApiServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - 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 - - 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 - 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 - 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 - 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-products/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-products/v1beta/.coveragerc deleted file mode 100644 index 0d94c2da5109..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_products/__init__.py - google/shopping/merchant_products/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-products/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-products/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-products/v1beta/MANIFEST.in deleted file mode 100644 index eeb53abab351..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/shopping/merchant_products *.py -recursive-include google/shopping/merchant_products_v1beta *.py diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/README.rst deleted file mode 100644 index 77b249a95743..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Shopping Merchant Products 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 Products 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-products/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/conf.py deleted file mode 100644 index 7ba9f03c5b3f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products 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-products" -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-products-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-products.tex", - u"google-shopping-merchant-products 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-products", - u"Google Shopping Merchant Products 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-products", - u"google-shopping-merchant-products Documentation", - author, - "google-shopping-merchant-products", - "GAPIC library for Google Shopping Merchant Products 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-products/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/index.rst deleted file mode 100644 index b94cbc45f50d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_products_v1beta/services_ - merchant_products_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/product_inputs_service.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/product_inputs_service.rst deleted file mode 100644 index 99e2c59bfb43..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/product_inputs_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -ProductInputsService --------------------------------------- - -.. automodule:: google.shopping.merchant_products_v1beta.services.product_inputs_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/products_service.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/products_service.rst deleted file mode 100644 index f20ce0b9e362..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/products_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProductsService ---------------------------------- - -.. automodule:: google.shopping.merchant_products_v1beta.services.products_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_products_v1beta.services.products_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/services_.rst deleted file mode 100644 index ce641539544e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Shopping Merchant Products v1beta API -========================================================= -.. toctree:: - :maxdepth: 2 - - product_inputs_service - products_service diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/types_.rst deleted file mode 100644 index af3a6c59c20f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/docs/merchant_products_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Products v1beta API -====================================================== - -.. automodule:: google.shopping.merchant_products_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/__init__.py deleted file mode 100644 index 794f9625d9da..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/__init__.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_products import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_products_v1beta.services.product_inputs_service.client import ProductInputsServiceClient -from google.shopping.merchant_products_v1beta.services.product_inputs_service.async_client import ProductInputsServiceAsyncClient -from google.shopping.merchant_products_v1beta.services.products_service.client import ProductsServiceClient -from google.shopping.merchant_products_v1beta.services.products_service.async_client import ProductsServiceAsyncClient - -from google.shopping.merchant_products_v1beta.types.productinputs import DeleteProductInputRequest -from google.shopping.merchant_products_v1beta.types.productinputs import InsertProductInputRequest -from google.shopping.merchant_products_v1beta.types.productinputs import ProductInput -from google.shopping.merchant_products_v1beta.types.products import GetProductRequest -from google.shopping.merchant_products_v1beta.types.products import ListProductsRequest -from google.shopping.merchant_products_v1beta.types.products import ListProductsResponse -from google.shopping.merchant_products_v1beta.types.products import Product -from google.shopping.merchant_products_v1beta.types.products_common import Attributes -from google.shopping.merchant_products_v1beta.types.products_common import Certification -from google.shopping.merchant_products_v1beta.types.products_common import CloudExportAdditionalProperties -from google.shopping.merchant_products_v1beta.types.products_common import FreeShippingThreshold -from google.shopping.merchant_products_v1beta.types.products_common import Installment -from google.shopping.merchant_products_v1beta.types.products_common import LoyaltyPoints -from google.shopping.merchant_products_v1beta.types.products_common import LoyaltyProgram -from google.shopping.merchant_products_v1beta.types.products_common import ProductDetail -from google.shopping.merchant_products_v1beta.types.products_common import ProductDimension -from google.shopping.merchant_products_v1beta.types.products_common import ProductStatus -from google.shopping.merchant_products_v1beta.types.products_common import ProductStructuredDescription -from google.shopping.merchant_products_v1beta.types.products_common import ProductStructuredTitle -from google.shopping.merchant_products_v1beta.types.products_common import ProductWeight -from google.shopping.merchant_products_v1beta.types.products_common import Shipping -from google.shopping.merchant_products_v1beta.types.products_common import ShippingDimension -from google.shopping.merchant_products_v1beta.types.products_common import ShippingWeight -from google.shopping.merchant_products_v1beta.types.products_common import SubscriptionCost -from google.shopping.merchant_products_v1beta.types.products_common import Tax -from google.shopping.merchant_products_v1beta.types.products_common import UnitPricingBaseMeasure -from google.shopping.merchant_products_v1beta.types.products_common import UnitPricingMeasure -from google.shopping.merchant_products_v1beta.types.products_common import SubscriptionPeriod - -__all__ = ('ProductInputsServiceClient', - 'ProductInputsServiceAsyncClient', - 'ProductsServiceClient', - 'ProductsServiceAsyncClient', - 'DeleteProductInputRequest', - 'InsertProductInputRequest', - 'ProductInput', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'Product', - 'Attributes', - 'Certification', - 'CloudExportAdditionalProperties', - 'FreeShippingThreshold', - 'Installment', - 'LoyaltyPoints', - 'LoyaltyProgram', - 'ProductDetail', - 'ProductDimension', - 'ProductStatus', - 'ProductStructuredDescription', - 'ProductStructuredTitle', - 'ProductWeight', - 'Shipping', - 'ShippingDimension', - 'ShippingWeight', - 'SubscriptionCost', - 'Tax', - 'UnitPricingBaseMeasure', - 'UnitPricingMeasure', - 'SubscriptionPeriod', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/gapic_version.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/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-products/v1beta/google/shopping/merchant_products/py.typed b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/py.typed deleted file mode 100644 index 962817aecdcd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-products package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/__init__.py deleted file mode 100644 index 949f22e1af16..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/__init__.py +++ /dev/null @@ -1,88 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_products_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.product_inputs_service import ProductInputsServiceClient -from .services.product_inputs_service import ProductInputsServiceAsyncClient -from .services.products_service import ProductsServiceClient -from .services.products_service import ProductsServiceAsyncClient - -from .types.productinputs import DeleteProductInputRequest -from .types.productinputs import InsertProductInputRequest -from .types.productinputs import ProductInput -from .types.products import GetProductRequest -from .types.products import ListProductsRequest -from .types.products import ListProductsResponse -from .types.products import Product -from .types.products_common import Attributes -from .types.products_common import Certification -from .types.products_common import CloudExportAdditionalProperties -from .types.products_common import FreeShippingThreshold -from .types.products_common import Installment -from .types.products_common import LoyaltyPoints -from .types.products_common import LoyaltyProgram -from .types.products_common import ProductDetail -from .types.products_common import ProductDimension -from .types.products_common import ProductStatus -from .types.products_common import ProductStructuredDescription -from .types.products_common import ProductStructuredTitle -from .types.products_common import ProductWeight -from .types.products_common import Shipping -from .types.products_common import ShippingDimension -from .types.products_common import ShippingWeight -from .types.products_common import SubscriptionCost -from .types.products_common import Tax -from .types.products_common import UnitPricingBaseMeasure -from .types.products_common import UnitPricingMeasure -from .types.products_common import SubscriptionPeriod - -__all__ = ( - 'ProductInputsServiceAsyncClient', - 'ProductsServiceAsyncClient', -'Attributes', -'Certification', -'CloudExportAdditionalProperties', -'DeleteProductInputRequest', -'FreeShippingThreshold', -'GetProductRequest', -'InsertProductInputRequest', -'Installment', -'ListProductsRequest', -'ListProductsResponse', -'LoyaltyPoints', -'LoyaltyProgram', -'Product', -'ProductDetail', -'ProductDimension', -'ProductInput', -'ProductInputsServiceClient', -'ProductStatus', -'ProductStructuredDescription', -'ProductStructuredTitle', -'ProductWeight', -'ProductsServiceClient', -'Shipping', -'ShippingDimension', -'ShippingWeight', -'SubscriptionCost', -'SubscriptionPeriod', -'Tax', -'UnitPricingBaseMeasure', -'UnitPricingMeasure', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_metadata.json deleted file mode 100644 index ac0f69541032..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_metadata.json +++ /dev/null @@ -1,107 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_products_v1beta", - "protoPackage": "google.shopping.merchant.products.v1beta", - "schema": "1.0", - "services": { - "ProductInputsService": { - "clients": { - "grpc": { - "libraryClient": "ProductInputsServiceClient", - "rpcs": { - "DeleteProductInput": { - "methods": [ - "delete_product_input" - ] - }, - "InsertProductInput": { - "methods": [ - "insert_product_input" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductInputsServiceAsyncClient", - "rpcs": { - "DeleteProductInput": { - "methods": [ - "delete_product_input" - ] - }, - "InsertProductInput": { - "methods": [ - "insert_product_input" - ] - } - } - }, - "rest": { - "libraryClient": "ProductInputsServiceClient", - "rpcs": { - "DeleteProductInput": { - "methods": [ - "delete_product_input" - ] - }, - "InsertProductInput": { - "methods": [ - "insert_product_input" - ] - } - } - } - } - }, - "ProductsService": { - "clients": { - "grpc": { - "libraryClient": "ProductsServiceClient", - "rpcs": { - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProductsServiceAsyncClient", - "rpcs": { - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - } - } - }, - "rest": { - "libraryClient": "ProductsServiceClient", - "rpcs": { - "GetProduct": { - "methods": [ - "get_product" - ] - }, - "ListProducts": { - "methods": [ - "list_products" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_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-products/v1beta/google/shopping/merchant_products_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/py.typed deleted file mode 100644 index 962817aecdcd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-products package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_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-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/__init__.py deleted file mode 100644 index 6bcc06bac82d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_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 ProductInputsServiceClient -from .async_client import ProductInputsServiceAsyncClient - -__all__ = ( - 'ProductInputsServiceClient', - 'ProductInputsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/async_client.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/async_client.py deleted file mode 100644 index 68e62b1ccb77..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/async_client.py +++ /dev/null @@ -1,462 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.shopping.merchant_products_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_products_v1beta.types import productinputs -from google.shopping.merchant_products_v1beta.types import products_common -from google.shopping.type.types import types -from .transports.base import ProductInputsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductInputsServiceGrpcAsyncIOTransport -from .client import ProductInputsServiceClient - - -class ProductInputsServiceAsyncClient: - """Service to use ProductInput resource. - This service works for products with online channel only. - """ - - _client: ProductInputsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ProductInputsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ProductInputsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ProductInputsServiceClient._DEFAULT_UNIVERSE - - product_path = staticmethod(ProductInputsServiceClient.product_path) - parse_product_path = staticmethod(ProductInputsServiceClient.parse_product_path) - product_input_path = staticmethod(ProductInputsServiceClient.product_input_path) - parse_product_input_path = staticmethod(ProductInputsServiceClient.parse_product_input_path) - common_billing_account_path = staticmethod(ProductInputsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductInputsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductInputsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductInputsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductInputsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductInputsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductInputsServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductInputsServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductInputsServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductInputsServiceClient.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: - ProductInputsServiceAsyncClient: The constructed client. - """ - return ProductInputsServiceClient.from_service_account_info.__func__(ProductInputsServiceAsyncClient, 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: - ProductInputsServiceAsyncClient: The constructed client. - """ - return ProductInputsServiceClient.from_service_account_file.__func__(ProductInputsServiceAsyncClient, 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 ProductInputsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductInputsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductInputsServiceTransport: 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 = ProductInputsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ProductInputsServiceTransport, Callable[..., ProductInputsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product inputs 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,ProductInputsServiceTransport,Callable[..., ProductInputsServiceTransport]]]): - 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 ProductInputsServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = ProductInputsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def insert_product_input(self, - request: Optional[Union[productinputs.InsertProductInputRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> productinputs.ProductInput: - r"""Uploads a product input to your Merchant Center - account. If an input with the same contentLanguage, - offerId, and dataSource already exists, this method - replaces that entry. - - After inserting, updating, or deleting a product input, - it may take several minutes before the processed product - 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_products_v1beta - - async def sample_insert_product_input(): - # Create a client - client = merchant_products_v1beta.ProductInputsServiceAsyncClient() - - # Initialize request argument(s) - product_input = merchant_products_v1beta.ProductInput() - product_input.channel = "LOCAL" - product_input.offer_id = "offer_id_value" - product_input.content_language = "content_language_value" - product_input.feed_label = "feed_label_value" - - request = merchant_products_v1beta.InsertProductInputRequest( - parent="parent_value", - product_input=product_input, - data_source="data_source_value", - ) - - # Make the request - response = await client.insert_product_input(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_products_v1beta.types.InsertProductInputRequest, dict]]): - The request object. Request message for the - InsertProductInput 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.shopping.merchant_products_v1beta.types.ProductInput: - This resource represents input data you submit for a product, not the - processed product that you see in Merchant Center, in - Shopping ads, or across Google surfaces. Product - inputs, rules and supplemental data source data are - combined to create the processed - [product][google.shopping.content.bundles.Products.Product]. - - Required product input attributes to pass data - validation checks are primarily defined in the - [Products Data - Specification](\ https://support.google.com/merchants/answer/188494). - - The following attributes are required: - [feedLabel][google.shopping.content.bundles.Products.feed_label], - [contentLanguage][google.shopping.content.bundles.Products.content_language] - and - [offerId][google.shopping.content.bundles.Products.offer_id]. - - After inserting, updating, or deleting a product - input, it may take several minutes before the - processed product can be retrieved. - - All fields in the product input and its sub-messages - match the English name of their corresponding - attribute in the vertical spec with [some - exceptions](\ https://support.google.com/merchants/answer/7052112). - - """ - # 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, productinputs.InsertProductInputRequest): - request = productinputs.InsertProductInputRequest(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_product_input] - - # Certain fields should be provided within 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_product_input(self, - request: Optional[Union[productinputs.DeleteProductInputRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a product input from your Merchant Center - account. - After inserting, updating, or deleting a product input, - it may take several minutes before the processed product - 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_products_v1beta - - async def sample_delete_product_input(): - # Create a client - client = merchant_products_v1beta.ProductInputsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.DeleteProductInputRequest( - name="name_value", - data_source="data_source_value", - ) - - # Make the request - await client.delete_product_input(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_products_v1beta.types.DeleteProductInputRequest, dict]]): - The request object. Request message for the - DeleteProductInput method. - name (:class:`str`): - Required. The name of the product - input resource to delete. Format: - accounts/{account}/productInputs/{product} - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, productinputs.DeleteProductInputRequest): - request = productinputs.DeleteProductInputRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_product_input] - - # Certain fields should be provided within 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) -> "ProductInputsServiceAsyncClient": - 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__ = ( - "ProductInputsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/client.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/client.py deleted file mode 100644 index f0ca70750bc6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/client.py +++ /dev/null @@ -1,827 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.shopping.merchant_products_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 - -from google.shopping.merchant_products_v1beta.types import productinputs -from google.shopping.merchant_products_v1beta.types import products_common -from google.shopping.type.types import types -from .transports.base import ProductInputsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductInputsServiceGrpcTransport -from .transports.grpc_asyncio import ProductInputsServiceGrpcAsyncIOTransport -from .transports.rest import ProductInputsServiceRestTransport - - -class ProductInputsServiceClientMeta(type): - """Metaclass for the ProductInputsService 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[ProductInputsServiceTransport]] - _transport_registry["grpc"] = ProductInputsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductInputsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ProductInputsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ProductInputsServiceTransport]: - """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 ProductInputsServiceClient(metaclass=ProductInputsServiceClientMeta): - """Service to use ProductInput resource. - This service works for products with online channel only. - """ - - @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: - ProductInputsServiceClient: 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: - ProductInputsServiceClient: 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) -> ProductInputsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductInputsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(account: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "accounts/{account}/products/{product}".format(account=account, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def product_input_path(account: str,productinput: str,) -> str: - """Returns a fully-qualified product_input string.""" - return "accounts/{account}/productInputs/{productinput}".format(account=account, productinput=productinput, ) - - @staticmethod - def parse_product_input_path(path: str) -> Dict[str,str]: - """Parses a product_input path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/productInputs/(?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 = ProductInputsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ProductInputsServiceClient._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 = ProductInputsServiceClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ProductInputsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - ProductInputsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, ProductInputsServiceTransport, Callable[..., ProductInputsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the product inputs 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,ProductInputsServiceTransport,Callable[..., ProductInputsServiceTransport]]]): - 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 ProductInputsServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = ProductInputsServiceClient._read_environment_variables() - self._client_cert_source = ProductInputsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ProductInputsServiceClient._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 - - 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, ProductInputsServiceTransport) - if transport_provided: - # transport is a ProductInputsServiceTransport 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(ProductInputsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ProductInputsServiceClient._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[ProductInputsServiceTransport], Callable[..., ProductInputsServiceTransport]] = ( - ProductInputsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ProductInputsServiceTransport], 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, - ) - - def insert_product_input(self, - request: Optional[Union[productinputs.InsertProductInputRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> productinputs.ProductInput: - r"""Uploads a product input to your Merchant Center - account. If an input with the same contentLanguage, - offerId, and dataSource already exists, this method - replaces that entry. - - After inserting, updating, or deleting a product input, - it may take several minutes before the processed product - 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_products_v1beta - - def sample_insert_product_input(): - # Create a client - client = merchant_products_v1beta.ProductInputsServiceClient() - - # Initialize request argument(s) - product_input = merchant_products_v1beta.ProductInput() - product_input.channel = "LOCAL" - product_input.offer_id = "offer_id_value" - product_input.content_language = "content_language_value" - product_input.feed_label = "feed_label_value" - - request = merchant_products_v1beta.InsertProductInputRequest( - parent="parent_value", - product_input=product_input, - data_source="data_source_value", - ) - - # Make the request - response = client.insert_product_input(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_products_v1beta.types.InsertProductInputRequest, dict]): - The request object. Request message for the - InsertProductInput method. - retry (google.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. - - Returns: - google.shopping.merchant_products_v1beta.types.ProductInput: - This resource represents input data you submit for a product, not the - processed product that you see in Merchant Center, in - Shopping ads, or across Google surfaces. Product - inputs, rules and supplemental data source data are - combined to create the processed - [product][google.shopping.content.bundles.Products.Product]. - - Required product input attributes to pass data - validation checks are primarily defined in the - [Products Data - Specification](\ https://support.google.com/merchants/answer/188494). - - The following attributes are required: - [feedLabel][google.shopping.content.bundles.Products.feed_label], - [contentLanguage][google.shopping.content.bundles.Products.content_language] - and - [offerId][google.shopping.content.bundles.Products.offer_id]. - - After inserting, updating, or deleting a product - input, it may take several minutes before the - processed product can be retrieved. - - All fields in the product input and its sub-messages - match the English name of their corresponding - attribute in the vertical spec with [some - exceptions](\ https://support.google.com/merchants/answer/7052112). - - """ - # 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, productinputs.InsertProductInputRequest): - request = productinputs.InsertProductInputRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_product_input] - - # Certain fields should be provided within 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_product_input(self, - request: Optional[Union[productinputs.DeleteProductInputRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a product input from your Merchant Center - account. - After inserting, updating, or deleting a product input, - it may take several minutes before the processed product - 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_products_v1beta - - def sample_delete_product_input(): - # Create a client - client = merchant_products_v1beta.ProductInputsServiceClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.DeleteProductInputRequest( - name="name_value", - data_source="data_source_value", - ) - - # Make the request - client.delete_product_input(request=request) - - Args: - request (Union[google.shopping.merchant_products_v1beta.types.DeleteProductInputRequest, dict]): - The request object. Request message for the - DeleteProductInput method. - name (str): - Required. The name of the product - input resource to delete. Format: - accounts/{account}/productInputs/{product} - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick 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, productinputs.DeleteProductInputRequest): - request = productinputs.DeleteProductInputRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_product_input] - - # Certain fields should be provided within 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) -> "ProductInputsServiceClient": - 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__ = ( - "ProductInputsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/README.rst deleted file mode 100644 index fa031e4be3c9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ProductInputsServiceTransport` is the ABC for all transports. -- public child `ProductInputsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ProductInputsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseProductInputsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ProductInputsServiceRestTransport` 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-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/__init__.py deleted file mode 100644 index e1e036be5719..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_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 ProductInputsServiceTransport -from .grpc import ProductInputsServiceGrpcTransport -from .grpc_asyncio import ProductInputsServiceGrpcAsyncIOTransport -from .rest import ProductInputsServiceRestTransport -from .rest import ProductInputsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductInputsServiceTransport]] -_transport_registry['grpc'] = ProductInputsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductInputsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ProductInputsServiceRestTransport - -__all__ = ( - 'ProductInputsServiceTransport', - 'ProductInputsServiceGrpcTransport', - 'ProductInputsServiceGrpcAsyncIOTransport', - 'ProductInputsServiceRestTransport', - 'ProductInputsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/base.py deleted file mode 100644 index 3d16fcf605f3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/base.py +++ /dev/null @@ -1,169 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_products_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_products_v1beta.types import productinputs - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ProductInputsServiceTransport(abc.ABC): - """Abstract transport class for ProductInputsService.""" - - 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_product_input: gapic_v1.method.wrap_method( - self.insert_product_input, - default_timeout=None, - client_info=client_info, - ), - self.delete_product_input: gapic_v1.method.wrap_method( - self.delete_product_input, - 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_product_input(self) -> Callable[ - [productinputs.InsertProductInputRequest], - Union[ - productinputs.ProductInput, - Awaitable[productinputs.ProductInput] - ]]: - raise NotImplementedError() - - @property - def delete_product_input(self) -> Callable[ - [productinputs.DeleteProductInputRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductInputsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc.py deleted file mode 100644 index 935022958cfc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc.py +++ /dev/null @@ -1,309 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 - -import grpc # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_products_v1beta.types import productinputs -from .base import ProductInputsServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductInputsServiceGrpcTransport(ProductInputsServiceTransport): - """gRPC backend transport for ProductInputsService. - - Service to use ProductInput resource. - This service works for products with online channel only. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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_product_input(self) -> Callable[ - [productinputs.InsertProductInputRequest], - productinputs.ProductInput]: - r"""Return a callable for the insert product input method over gRPC. - - Uploads a product input to your Merchant Center - account. If an input with the same contentLanguage, - offerId, and dataSource already exists, this method - replaces that entry. - - After inserting, updating, or deleting a product input, - it may take several minutes before the processed product - can be retrieved. - - Returns: - Callable[[~.InsertProductInputRequest], - ~.ProductInput]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product_input' not in self._stubs: - self._stubs['insert_product_input'] = self.grpc_channel.unary_unary( - '/google.shopping.merchant.products.v1beta.ProductInputsService/InsertProductInput', - request_serializer=productinputs.InsertProductInputRequest.serialize, - response_deserializer=productinputs.ProductInput.deserialize, - ) - return self._stubs['insert_product_input'] - - @property - def delete_product_input(self) -> Callable[ - [productinputs.DeleteProductInputRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete product input method over gRPC. - - Deletes a product input from your Merchant Center - account. - After inserting, updating, or deleting a product input, - it may take several minutes before the processed product - can be retrieved. - - Returns: - Callable[[~.DeleteProductInputRequest], - ~.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_product_input' not in self._stubs: - self._stubs['delete_product_input'] = self.grpc_channel.unary_unary( - '/google.shopping.merchant.products.v1beta.ProductInputsService/DeleteProductInput', - request_serializer=productinputs.DeleteProductInputRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product_input'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductInputsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc_asyncio.py deleted file mode 100644 index fce4093a6a7a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,335 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_products_v1beta.types import productinputs -from .base import ProductInputsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductInputsServiceGrpcTransport - - -class ProductInputsServiceGrpcAsyncIOTransport(ProductInputsServiceTransport): - """gRPC AsyncIO backend transport for ProductInputsService. - - Service to use ProductInput resource. - This service works for products with online channel only. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_product_input(self) -> Callable[ - [productinputs.InsertProductInputRequest], - Awaitable[productinputs.ProductInput]]: - r"""Return a callable for the insert product input method over gRPC. - - Uploads a product input to your Merchant Center - account. If an input with the same contentLanguage, - offerId, and dataSource already exists, this method - replaces that entry. - - After inserting, updating, or deleting a product input, - it may take several minutes before the processed product - can be retrieved. - - Returns: - Callable[[~.InsertProductInputRequest], - Awaitable[~.ProductInput]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product_input' not in self._stubs: - self._stubs['insert_product_input'] = self.grpc_channel.unary_unary( - '/google.shopping.merchant.products.v1beta.ProductInputsService/InsertProductInput', - request_serializer=productinputs.InsertProductInputRequest.serialize, - response_deserializer=productinputs.ProductInput.deserialize, - ) - return self._stubs['insert_product_input'] - - @property - def delete_product_input(self) -> Callable[ - [productinputs.DeleteProductInputRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete product input method over gRPC. - - Deletes a product input from your Merchant Center - account. - After inserting, updating, or deleting a product input, - it may take several minutes before the processed product - can be retrieved. - - Returns: - Callable[[~.DeleteProductInputRequest], - 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_product_input' not in self._stubs: - self._stubs['delete_product_input'] = self.grpc_channel.unary_unary( - '/google.shopping.merchant.products.v1beta.ProductInputsService/DeleteProductInput', - request_serializer=productinputs.DeleteProductInputRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_product_input'] - - 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_product_input: self._wrap_method( - self.insert_product_input, - default_timeout=None, - client_info=client_info, - ), - self.delete_product_input: self._wrap_method( - self.delete_product_input, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'ProductInputsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py deleted file mode 100644 index 5bff979ef5bb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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_products_v1beta.types import productinputs - - -from .rest_base import _BaseProductInputsServiceRestTransport -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 - - -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 ProductInputsServiceRestInterceptor: - """Interceptor for ProductInputsService. - - 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 ProductInputsServiceRestTransport. - - .. code-block:: python - class MyCustomProductInputsServiceInterceptor(ProductInputsServiceRestInterceptor): - def pre_delete_product_input(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_insert_product_input(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_product_input(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ProductInputsServiceRestTransport(interceptor=MyCustomProductInputsServiceInterceptor()) - client = ProductInputsServiceClient(transport=transport) - - - """ - def pre_delete_product_input(self, request: productinputs.DeleteProductInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[productinputs.DeleteProductInputRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_product_input - - Override in a subclass to manipulate the request or metadata - before they are sent to the ProductInputsService server. - """ - return request, metadata - - def pre_insert_product_input(self, request: productinputs.InsertProductInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[productinputs.InsertProductInputRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for insert_product_input - - Override in a subclass to manipulate the request or metadata - before they are sent to the ProductInputsService server. - """ - return request, metadata - - def post_insert_product_input(self, response: productinputs.ProductInput) -> productinputs.ProductInput: - """Post-rpc interceptor for insert_product_input - - Override in a subclass to manipulate the response - after it is returned by the ProductInputsService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ProductInputsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ProductInputsServiceRestInterceptor - - -class ProductInputsServiceRestTransport(_BaseProductInputsServiceRestTransport): - """REST backend synchronous transport for ProductInputsService. - - Service to use ProductInput resource. - This service works for products with online channel only. - - This class defines the same methods as the primary client, so the - primary client can 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[ProductInputsServiceRestInterceptor] = 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 ProductInputsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _DeleteProductInput(_BaseProductInputsServiceRestTransport._BaseDeleteProductInput, ProductInputsServiceRestStub): - def __hash__(self): - return hash("ProductInputsServiceRestTransport.DeleteProductInput") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: productinputs.DeleteProductInputRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete product input method over HTTP. - - Args: - request (~.productinputs.DeleteProductInputRequest): - The request object. Request message for the - DeleteProductInput method. - retry (google.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. - """ - - http_options = _BaseProductInputsServiceRestTransport._BaseDeleteProductInput._get_http_options() - request, metadata = self._interceptor.pre_delete_product_input(request, metadata) - transcoded_request = _BaseProductInputsServiceRestTransport._BaseDeleteProductInput._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseProductInputsServiceRestTransport._BaseDeleteProductInput._get_query_params_json(transcoded_request) - - # Send the request - response = ProductInputsServiceRestTransport._DeleteProductInput._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 _InsertProductInput(_BaseProductInputsServiceRestTransport._BaseInsertProductInput, ProductInputsServiceRestStub): - def __hash__(self): - return hash("ProductInputsServiceRestTransport.InsertProductInput") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: productinputs.InsertProductInputRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> productinputs.ProductInput: - r"""Call the insert product input method over HTTP. - - Args: - request (~.productinputs.InsertProductInputRequest): - The request object. Request message for the - InsertProductInput method. - retry (google.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. - - Returns: - ~.productinputs.ProductInput: - This resource represents input data you submit for a - product, not the processed product that you see in - Merchant Center, in Shopping ads, or across Google - surfaces. Product inputs, rules and supplemental data - source data are combined to create the processed - [product][google.shopping.content.bundles.Products.Product]. - - Required product input attributes to pass data - validation checks are primarily defined in the `Products - Data - Specification `__. - - The following attributes are required: - [feedLabel][google.shopping.content.bundles.Products.feed_label], - [contentLanguage][google.shopping.content.bundles.Products.content_language] - and - [offerId][google.shopping.content.bundles.Products.offer_id]. - - After inserting, updating, or deleting a product input, - it may take several minutes before the processed product - can be retrieved. - - All fields in the product input and its sub-messages - match the English name of their corresponding attribute - in the vertical spec with `some - exceptions `__. - - """ - - http_options = _BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_http_options() - request, metadata = self._interceptor.pre_insert_product_input(request, metadata) - transcoded_request = _BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_transcoded_request(http_options, request) - - body = _BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_query_params_json(transcoded_request) - - # Send the request - response = ProductInputsServiceRestTransport._InsertProductInput._get_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 = productinputs.ProductInput() - pb_resp = productinputs.ProductInput.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_insert_product_input(resp) - return resp - - @property - def delete_product_input(self) -> Callable[ - [productinputs.DeleteProductInputRequest], - 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._DeleteProductInput(self._session, self._host, self._interceptor) # type: ignore - - @property - def insert_product_input(self) -> Callable[ - [productinputs.InsertProductInputRequest], - productinputs.ProductInput]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._InsertProductInput(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ProductInputsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest_base.py deleted file mode 100644 index ee9987784bae..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest_base.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. -# -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 ProductInputsServiceTransport, 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_products_v1beta.types import productinputs - - -class _BaseProductInputsServiceRestTransport(ProductInputsServiceTransport): - """Base REST backend transport for ProductInputsService. - - 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 _BaseDeleteProductInput: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "dataSource" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/products/v1beta/{name=accounts/*/productInputs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = productinputs.DeleteProductInputRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseProductInputsServiceRestTransport._BaseDeleteProductInput._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseInsertProductInput: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "dataSource" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in 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': '/products/v1beta/{parent=accounts/*}/productInputs:insert', - 'body': 'product_input', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = productinputs.InsertProductInputRequest.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(_BaseProductInputsServiceRestTransport._BaseInsertProductInput._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseProductInputsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/__init__.py deleted file mode 100644 index 83e3a381efc6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_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 ProductsServiceClient -from .async_client import ProductsServiceAsyncClient - -__all__ = ( - 'ProductsServiceClient', - 'ProductsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/async_client.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/async_client.py deleted file mode 100644 index 1fdd043a4e65..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/async_client.py +++ /dev/null @@ -1,490 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.shopping.merchant_products_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_products_v1beta.services.products_service import pagers -from google.shopping.merchant_products_v1beta.types import products -from google.shopping.merchant_products_v1beta.types import products_common -from google.shopping.type.types import types -from .transports.base import ProductsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductsServiceGrpcAsyncIOTransport -from .client import ProductsServiceClient - - -class ProductsServiceAsyncClient: - """Service to use Product resource. - This service works for products with online channel only. - """ - - _client: ProductsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ProductsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProductsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ProductsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ProductsServiceClient._DEFAULT_UNIVERSE - - product_path = staticmethod(ProductsServiceClient.product_path) - parse_product_path = staticmethod(ProductsServiceClient.parse_product_path) - common_billing_account_path = staticmethod(ProductsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProductsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProductsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProductsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProductsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProductsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProductsServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProductsServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProductsServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProductsServiceClient.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: - ProductsServiceAsyncClient: The constructed client. - """ - return ProductsServiceClient.from_service_account_info.__func__(ProductsServiceAsyncClient, 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: - ProductsServiceAsyncClient: The constructed client. - """ - return ProductsServiceClient.from_service_account_file.__func__(ProductsServiceAsyncClient, 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 ProductsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProductsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductsServiceTransport: 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 = ProductsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ProductsServiceTransport, Callable[..., ProductsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the products 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,ProductsServiceTransport,Callable[..., ProductsServiceTransport]]]): - 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 ProductsServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = ProductsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_product(self, - request: Optional[Union[products.GetProductRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> products.Product: - r"""Retrieves the processed product from your Merchant - Center account. - After inserting, updating, or deleting a product input, - it may take several minutes before the updated final - product 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_products_v1beta - - async def sample_get_product(): - # Create a client - client = merchant_products_v1beta.ProductsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_products_v1beta.types.GetProductRequest, dict]]): - The request object. Request message for the GetProduct - method. - name (:class:`str`): - Required. The name of the product to retrieve. Format: - ``accounts/{account}/products/{product}`` - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.shopping.merchant_products_v1beta.types.Product: - The processed product, built from multiple [product - inputs][[google.shopping.content.bundles.Products.ProductInput] - after applying rules and supplemental data sources. - This processed product matches what is shown in your - Merchant Center account and in Shopping ads and other - surfaces across Google. Each product is built from - exactly one primary data source product input, and - multiple supplemental data source inputs. After - inserting, updating, or deleting a product input, it - may take several minutes before the updated processed - product can be retrieved. - - All fields in the processed product and its - sub-messages match the name of their corresponding - attribute in the [Product data - specification](\ https://support.google.com/merchants/answer/7052112) - with some exceptions. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, products.GetProductRequest): - request = products.GetProductRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_products(self, - request: Optional[Union[products.ListProductsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsAsyncPager: - r"""Lists the processed products 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, updating, or deleting a product input, - it may take several minutes before the updated processed - product 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_products_v1beta - - async def sample_list_products(): - # Create a client - client = merchant_products_v1beta.ProductsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_products_v1beta.types.ListProductsRequest, dict]]): - The request object. Request message for the ListProducts - method. - parent (:class:`str`): - Required. The account to list - processed products 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.shopping.merchant_products_v1beta.services.products_service.pagers.ListProductsAsyncPager: - Response message for the ListProducts - 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, products.ListProductsRequest): - request = products.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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.ListProductsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "ProductsServiceAsyncClient": - 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__ = ( - "ProductsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/client.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/client.py deleted file mode 100644 index e11759667b94..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/client.py +++ /dev/null @@ -1,845 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.shopping.merchant_products_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 - -from google.shopping.merchant_products_v1beta.services.products_service import pagers -from google.shopping.merchant_products_v1beta.types import products -from google.shopping.merchant_products_v1beta.types import products_common -from google.shopping.type.types import types -from .transports.base import ProductsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProductsServiceGrpcTransport -from .transports.grpc_asyncio import ProductsServiceGrpcAsyncIOTransport -from .transports.rest import ProductsServiceRestTransport - - -class ProductsServiceClientMeta(type): - """Metaclass for the ProductsService 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[ProductsServiceTransport]] - _transport_registry["grpc"] = ProductsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProductsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ProductsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ProductsServiceTransport]: - """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 ProductsServiceClient(metaclass=ProductsServiceClientMeta): - """Service to use Product resource. - This service works for products with online channel only. - """ - - @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: - ProductsServiceClient: 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: - ProductsServiceClient: 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) -> ProductsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProductsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def product_path(account: str,product: str,) -> str: - """Returns a fully-qualified product string.""" - return "accounts/{account}/products/{product}".format(account=account, product=product, ) - - @staticmethod - def parse_product_path(path: str) -> Dict[str,str]: - """Parses a product path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/products/(?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 = ProductsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ProductsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ProductsServiceClient._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 = ProductsServiceClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ProductsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - ProductsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def 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, ProductsServiceTransport, Callable[..., ProductsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the products 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,ProductsServiceTransport,Callable[..., ProductsServiceTransport]]]): - 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 ProductsServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = ProductsServiceClient._read_environment_variables() - self._client_cert_source = ProductsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ProductsServiceClient._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 - - 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, ProductsServiceTransport) - if transport_provided: - # transport is a ProductsServiceTransport 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(ProductsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ProductsServiceClient._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[ProductsServiceTransport], Callable[..., ProductsServiceTransport]] = ( - ProductsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ProductsServiceTransport], 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, - ) - - def get_product(self, - request: Optional[Union[products.GetProductRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> products.Product: - r"""Retrieves the processed product from your Merchant - Center account. - After inserting, updating, or deleting a product input, - it may take several minutes before the updated final - product 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_products_v1beta - - def sample_get_product(): - # Create a client - client = merchant_products_v1beta.ProductsServiceClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_products_v1beta.types.GetProductRequest, dict]): - The request object. Request message for the GetProduct - method. - name (str): - Required. The name of the product to retrieve. Format: - ``accounts/{account}/products/{product}`` - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.shopping.merchant_products_v1beta.types.Product: - The processed product, built from multiple [product - inputs][[google.shopping.content.bundles.Products.ProductInput] - after applying rules and supplemental data sources. - This processed product matches what is shown in your - Merchant Center account and in Shopping ads and other - surfaces across Google. Each product is built from - exactly one primary data source product input, and - multiple supplemental data source inputs. After - inserting, updating, or deleting a product input, it - may take several minutes before the updated processed - product can be retrieved. - - All fields in the processed product and its - sub-messages match the name of their corresponding - attribute in the [Product data - specification](\ https://support.google.com/merchants/answer/7052112) - with some exceptions. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, products.GetProductRequest): - request = products.GetProductRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_product] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_products(self, - request: Optional[Union[products.ListProductsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProductsPager: - r"""Lists the processed products 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, updating, or deleting a product input, - it may take several minutes before the updated processed - product 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_products_v1beta - - def sample_list_products(): - # Create a client - client = merchant_products_v1beta.ProductsServiceClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_products_v1beta.types.ListProductsRequest, dict]): - The request object. Request message for the ListProducts - method. - parent (str): - Required. The account to list - processed products 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.shopping.merchant_products_v1beta.services.products_service.pagers.ListProductsPager: - Response message for the ListProducts - 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, products.ListProductsRequest): - request = products.ListProductsRequest(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_products] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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.ListProductsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ProductsServiceClient": - 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__ = ( - "ProductsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/pagers.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/pagers.py deleted file mode 100644 index 030d3c3e9284..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_products_v1beta.types import products - - -class ListProductsPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_products_v1beta.types.ListProductsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_products_v1beta.types.ListProductsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., products.ListProductsResponse], - request: products.ListProductsRequest, - response: products.ListProductsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_products_v1beta.types.ListProductsRequest): - The initial request object. - response (google.shopping.merchant_products_v1beta.types.ListProductsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = products.ListProductsRequest(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[products.ListProductsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[products.Product]: - for page in self.pages: - yield from page.products - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProductsAsyncPager: - """A pager for iterating through ``list_products`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_products_v1beta.types.ListProductsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``products`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProducts`` requests and continue to iterate - through the ``products`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_products_v1beta.types.ListProductsResponse` - attributes are available on the 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[products.ListProductsResponse]], - request: products.ListProductsRequest, - response: products.ListProductsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_products_v1beta.types.ListProductsRequest): - The initial request object. - response (google.shopping.merchant_products_v1beta.types.ListProductsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = products.ListProductsRequest(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[products.ListProductsResponse]: - 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[products.Product]: - async def async_generator(): - async for page in self.pages: - for response in page.products: - 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-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/README.rst deleted file mode 100644 index c1cbe3d98697..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ProductsServiceTransport` is the ABC for all transports. -- public child `ProductsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ProductsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseProductsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ProductsServiceRestTransport` 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-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/__init__.py deleted file mode 100644 index 328b51677c37..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_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 ProductsServiceTransport -from .grpc import ProductsServiceGrpcTransport -from .grpc_asyncio import ProductsServiceGrpcAsyncIOTransport -from .rest import ProductsServiceRestTransport -from .rest import ProductsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProductsServiceTransport]] -_transport_registry['grpc'] = ProductsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProductsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ProductsServiceRestTransport - -__all__ = ( - 'ProductsServiceTransport', - 'ProductsServiceGrpcTransport', - 'ProductsServiceGrpcAsyncIOTransport', - 'ProductsServiceRestTransport', - 'ProductsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/base.py deleted file mode 100644 index d9294b8fb782..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_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_products_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_products_v1beta.types import products - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ProductsServiceTransport(abc.ABC): - """Abstract transport class for ProductsService.""" - - 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_product: gapic_v1.method.wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: gapic_v1.method.wrap_method( - self.list_products, - 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_product(self) -> Callable[ - [products.GetProductRequest], - Union[ - products.Product, - Awaitable[products.Product] - ]]: - raise NotImplementedError() - - @property - def list_products(self) -> Callable[ - [products.ListProductsRequest], - Union[ - products.ListProductsResponse, - Awaitable[products.ListProductsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProductsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc.py deleted file mode 100644 index 1d1389b6dee7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc.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. -# -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 - -import grpc # type: ignore - -from google.shopping.merchant_products_v1beta.types import products -from .base import ProductsServiceTransport, DEFAULT_CLIENT_INFO - - -class ProductsServiceGrpcTransport(ProductsServiceTransport): - """gRPC backend transport for ProductsService. - - Service to use Product resource. - This service works for products with online channel only. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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_product(self) -> Callable[ - [products.GetProductRequest], - products.Product]: - r"""Return a callable for the get product method over gRPC. - - Retrieves the processed product from your Merchant - Center account. - After inserting, updating, or deleting a product input, - it may take several minutes before the updated final - product can be retrieved. - - Returns: - Callable[[~.GetProductRequest], - ~.Product]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.shopping.merchant.products.v1beta.ProductsService/GetProduct', - request_serializer=products.GetProductRequest.serialize, - response_deserializer=products.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [products.ListProductsRequest], - products.ListProductsResponse]: - r"""Return a callable for the list products method over gRPC. - - Lists the processed products 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, updating, or deleting a product input, - it may take several minutes before the updated processed - product can be retrieved. - - Returns: - Callable[[~.ListProductsRequest], - ~.ListProductsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.shopping.merchant.products.v1beta.ProductsService/ListProducts', - request_serializer=products.ListProductsRequest.serialize, - response_deserializer=products.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProductsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc_asyncio.py deleted file mode 100644 index 064e2defaa37..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/grpc_asyncio.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 inspect -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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.shopping.merchant_products_v1beta.types import products -from .base import ProductsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProductsServiceGrpcTransport - - -class ProductsServiceGrpcAsyncIOTransport(ProductsServiceTransport): - """gRPC AsyncIO backend transport for ProductsService. - - Service to use Product resource. - This service works for products with online channel only. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_product(self) -> Callable[ - [products.GetProductRequest], - Awaitable[products.Product]]: - r"""Return a callable for the get product method over gRPC. - - Retrieves the processed product from your Merchant - Center account. - After inserting, updating, or deleting a product input, - it may take several minutes before the updated final - product can be retrieved. - - Returns: - Callable[[~.GetProductRequest], - Awaitable[~.Product]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_product' not in self._stubs: - self._stubs['get_product'] = self.grpc_channel.unary_unary( - '/google.shopping.merchant.products.v1beta.ProductsService/GetProduct', - request_serializer=products.GetProductRequest.serialize, - response_deserializer=products.Product.deserialize, - ) - return self._stubs['get_product'] - - @property - def list_products(self) -> Callable[ - [products.ListProductsRequest], - Awaitable[products.ListProductsResponse]]: - r"""Return a callable for the list products method over gRPC. - - Lists the processed products 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, updating, or deleting a product input, - it may take several minutes before the updated processed - product can be retrieved. - - Returns: - Callable[[~.ListProductsRequest], - Awaitable[~.ListProductsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_products' not in self._stubs: - self._stubs['list_products'] = self.grpc_channel.unary_unary( - '/google.shopping.merchant.products.v1beta.ProductsService/ListProducts', - request_serializer=products.ListProductsRequest.serialize, - response_deserializer=products.ListProductsResponse.deserialize, - ) - return self._stubs['list_products'] - - 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_product: self._wrap_method( - self.get_product, - default_timeout=None, - client_info=client_info, - ), - self.list_products: self._wrap_method( - self.list_products, - 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.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'ProductsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py deleted file mode 100644 index 9e0d6af98d9f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py +++ /dev/null @@ -1,398 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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_products_v1beta.types import products - - -from .rest_base import _BaseProductsServiceRestTransport -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 - - -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 ProductsServiceRestInterceptor: - """Interceptor for ProductsService. - - 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 ProductsServiceRestTransport. - - .. code-block:: python - class MyCustomProductsServiceInterceptor(ProductsServiceRestInterceptor): - def pre_get_product(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_product(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_products(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_products(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ProductsServiceRestTransport(interceptor=MyCustomProductsServiceInterceptor()) - client = ProductsServiceClient(transport=transport) - - - """ - def pre_get_product(self, request: products.GetProductRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[products.GetProductRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_product - - Override in a subclass to manipulate the request or metadata - before they are sent to the ProductsService server. - """ - return request, metadata - - def post_get_product(self, response: products.Product) -> products.Product: - """Post-rpc interceptor for get_product - - Override in a subclass to manipulate the response - after it is returned by the ProductsService server but before - it is returned to user code. - """ - return response - - def pre_list_products(self, request: products.ListProductsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[products.ListProductsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_products - - Override in a subclass to manipulate the request or metadata - before they are sent to the ProductsService server. - """ - return request, metadata - - def post_list_products(self, response: products.ListProductsResponse) -> products.ListProductsResponse: - """Post-rpc interceptor for list_products - - Override in a subclass to manipulate the response - after it is returned by the ProductsService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ProductsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ProductsServiceRestInterceptor - - -class ProductsServiceRestTransport(_BaseProductsServiceRestTransport): - """REST backend synchronous transport for ProductsService. - - Service to use Product resource. - This service works for products with online channel only. - - This class defines the same methods as the primary client, so the - primary client can 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[ProductsServiceRestInterceptor] = 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 ProductsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetProduct(_BaseProductsServiceRestTransport._BaseGetProduct, ProductsServiceRestStub): - def __hash__(self): - return hash("ProductsServiceRestTransport.GetProduct") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: products.GetProductRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> products.Product: - r"""Call the get product method over HTTP. - - Args: - request (~.products.GetProductRequest): - The request object. Request message for the GetProduct - method. - retry (google.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. - - Returns: - ~.products.Product: - The processed product, built from multiple [product - inputs][[google.shopping.content.bundles.Products.ProductInput] - after applying rules and supplemental data sources. This - processed product matches what is shown in your Merchant - Center account and in Shopping ads and other surfaces - across Google. Each product is built from exactly one - primary data source product input, and multiple - supplemental data source inputs. After inserting, - updating, or deleting a product input, it may take - several minutes before the updated processed product can - be retrieved. - - All fields in the processed product and its sub-messages - match the name of their corresponding attribute in the - `Product data - specification `__ - with some exceptions. - - """ - - http_options = _BaseProductsServiceRestTransport._BaseGetProduct._get_http_options() - request, metadata = self._interceptor.pre_get_product(request, metadata) - transcoded_request = _BaseProductsServiceRestTransport._BaseGetProduct._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseProductsServiceRestTransport._BaseGetProduct._get_query_params_json(transcoded_request) - - # Send the request - response = ProductsServiceRestTransport._GetProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = products.Product() - pb_resp = products.Product.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_product(resp) - return resp - - class _ListProducts(_BaseProductsServiceRestTransport._BaseListProducts, ProductsServiceRestStub): - def __hash__(self): - return hash("ProductsServiceRestTransport.ListProducts") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: products.ListProductsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> products.ListProductsResponse: - r"""Call the list products method over HTTP. - - Args: - request (~.products.ListProductsRequest): - The request object. Request message for the ListProducts - method. - retry (google.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. - - Returns: - ~.products.ListProductsResponse: - Response message for the ListProducts - method. - - """ - - http_options = _BaseProductsServiceRestTransport._BaseListProducts._get_http_options() - request, metadata = self._interceptor.pre_list_products(request, metadata) - transcoded_request = _BaseProductsServiceRestTransport._BaseListProducts._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseProductsServiceRestTransport._BaseListProducts._get_query_params_json(transcoded_request) - - # Send the request - response = ProductsServiceRestTransport._ListProducts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = products.ListProductsResponse() - pb_resp = products.ListProductsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_products(resp) - return resp - - @property - def get_product(self) -> Callable[ - [products.GetProductRequest], - products.Product]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProduct(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_products(self) -> Callable[ - [products.ListProductsRequest], - products.ListProductsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProducts(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ProductsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_service/transports/rest_base.py deleted file mode 100644 index ea9a202f4e6d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/services/products_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 ProductsServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_products_v1beta.types import products - - -class _BaseProductsServiceRestTransport(ProductsServiceTransport): - """Base REST backend transport for ProductsService. - - 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 _BaseGetProduct: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/products/v1beta/{name=accounts/*/products/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = products.GetProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseProductsServiceRestTransport._BaseGetProduct._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListProducts: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/products/v1beta/{parent=accounts/*}/products', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = products.ListProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseProductsServiceRestTransport._BaseListProducts._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseProductsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/__init__.py deleted file mode 100644 index 34321319c6a0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .productinputs import ( - DeleteProductInputRequest, - InsertProductInputRequest, - ProductInput, -) -from .products import ( - GetProductRequest, - ListProductsRequest, - ListProductsResponse, - Product, -) -from .products_common import ( - Attributes, - Certification, - CloudExportAdditionalProperties, - FreeShippingThreshold, - Installment, - LoyaltyPoints, - LoyaltyProgram, - ProductDetail, - ProductDimension, - ProductStatus, - ProductStructuredDescription, - ProductStructuredTitle, - ProductWeight, - Shipping, - ShippingDimension, - ShippingWeight, - SubscriptionCost, - Tax, - UnitPricingBaseMeasure, - UnitPricingMeasure, - SubscriptionPeriod, -) - -__all__ = ( - 'DeleteProductInputRequest', - 'InsertProductInputRequest', - 'ProductInput', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - 'Product', - 'Attributes', - 'Certification', - 'CloudExportAdditionalProperties', - 'FreeShippingThreshold', - 'Installment', - 'LoyaltyPoints', - 'LoyaltyProgram', - 'ProductDetail', - 'ProductDimension', - 'ProductStatus', - 'ProductStructuredDescription', - 'ProductStructuredTitle', - 'ProductWeight', - 'Shipping', - 'ShippingDimension', - 'ShippingWeight', - 'SubscriptionCost', - 'Tax', - 'UnitPricingBaseMeasure', - 'UnitPricingMeasure', - 'SubscriptionPeriod', -) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/productinputs.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/productinputs.py deleted file mode 100644 index c436ce740300..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/productinputs.py +++ /dev/null @@ -1,220 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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_products_v1beta.types import products_common -from google.shopping.type.types import types - - -__protobuf__ = proto.module( - package='google.shopping.merchant.products.v1beta', - manifest={ - 'ProductInput', - 'InsertProductInputRequest', - 'DeleteProductInputRequest', - }, -) - - -class ProductInput(proto.Message): - r"""This resource represents input data you submit for a product, not - the processed product that you see in Merchant Center, in Shopping - ads, or across Google surfaces. Product inputs, rules and - supplemental data source data are combined to create the processed - [product][google.shopping.content.bundles.Products.Product]. - - Required product input attributes to pass data validation checks are - primarily defined in the `Products Data - Specification `__. - - The following attributes are required: - [feedLabel][google.shopping.content.bundles.Products.feed_label], - [contentLanguage][google.shopping.content.bundles.Products.content_language] - and [offerId][google.shopping.content.bundles.Products.offer_id]. - - After inserting, updating, or deleting a product input, it may take - several minutes before the processed product can be retrieved. - - All fields in the product input and its sub-messages match the - English name of their corresponding attribute in the vertical spec - with `some - exceptions `__. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The name of the product input. Format: - ``"{productinput.name=accounts/{account}/productInputs/{productinput}}"`` - product (str): - Output only. The name of the processed product. Format: - ``"{product.name=accounts/{account}/products/{product}}"`` - channel (google.shopping.type.types.Channel.ChannelEnum): - Required. Immutable. The - `channel `__ - of the product. - offer_id (str): - Required. Immutable. Your unique identifier for the product. - This is the same for the product input and processed - product. Leading and trailing whitespaces are stripped and - multiple whitespaces are replaced by a single whitespace - upon submission. See the `products data - specification `__ - for details. - content_language (str): - Required. Immutable. The two-letter `ISO - 639-1 `__ language - code for the product. - feed_label (str): - Required. Immutable. The `feed - label `__ - for the product. - version_number (int): - Optional. Represents the existing version (freshness) of the - product, 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 - product. Re-insertion (for example, product refresh after 30 - days) can be performed with the current ``version_number``. - - Only supported for insertions into primary data sources. - - If the operation is prevented, the aborted exception will be - thrown. - - This field is a member of `oneof`_ ``_version_number``. - attributes (google.shopping.merchant_products_v1beta.types.Attributes): - Optional. A list of product 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, such as additional attributes used for Buy on - Google. Maximum allowed number of characters for each custom - attribute is 10240 (represents sum of characters for name - and value). Maximum 2500 custom attributes can be set per - product, with total size of 102.4kB. Underscores in custom - attribute names are replaced by spaces upon insertion. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - product: str = proto.Field( - proto.STRING, - number=2, - ) - channel: types.Channel.ChannelEnum = proto.Field( - proto.ENUM, - number=3, - enum=types.Channel.ChannelEnum, - ) - offer_id: str = proto.Field( - proto.STRING, - number=4, - ) - content_language: str = proto.Field( - proto.STRING, - number=5, - ) - feed_label: str = proto.Field( - proto.STRING, - number=6, - ) - version_number: int = proto.Field( - proto.INT64, - number=7, - optional=True, - ) - attributes: products_common.Attributes = proto.Field( - proto.MESSAGE, - number=8, - message=products_common.Attributes, - ) - custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=types.CustomAttribute, - ) - - -class InsertProductInputRequest(proto.Message): - r"""Request message for the InsertProductInput method. - - Attributes: - parent (str): - Required. The account where this product will - be inserted. Format: accounts/{account} - product_input (google.shopping.merchant_products_v1beta.types.ProductInput): - Required. The product input to insert. - data_source (str): - Required. The primary or supplemental product data source - name. If the product already exists and data source provided - is different, then the product will be moved to a new data - source. Format: - ``accounts/{account}/dataSources/{datasource}``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - product_input: 'ProductInput' = proto.Field( - proto.MESSAGE, - number=2, - message='ProductInput', - ) - data_source: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteProductInputRequest(proto.Message): - r"""Request message for the DeleteProductInput method. - - Attributes: - name (str): - Required. The name of the product input - resource to delete. Format: - accounts/{account}/productInputs/{product} - data_source (str): - Required. The primary or supplemental data source from which - the product input should be deleted. Format: - ``accounts/{account}/dataSources/{datasource}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data_source: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products.py deleted file mode 100644 index ae8d34200ede..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products.py +++ /dev/null @@ -1,240 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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_products_v1beta.types import products_common -from google.shopping.type.types import types - - -__protobuf__ = proto.module( - package='google.shopping.merchant.products.v1beta', - manifest={ - 'Product', - 'GetProductRequest', - 'ListProductsRequest', - 'ListProductsResponse', - }, -) - - -class Product(proto.Message): - r"""The processed product, built from multiple [product - inputs][[google.shopping.content.bundles.Products.ProductInput] - after applying rules and supplemental data sources. This processed - product matches what is shown in your Merchant Center account and in - Shopping ads and other surfaces across Google. Each product is built - from exactly one primary data source product input, and multiple - supplemental data source inputs. After inserting, updating, or - deleting a product input, it may take several minutes before the - updated processed product can be retrieved. - - All fields in the processed product and its sub-messages match the - name of their corresponding attribute in the `Product data - specification `__ - with some exceptions. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The name of the product. Format: - ``"{product.name=accounts/{account}/products/{product}}"`` - channel (google.shopping.type.types.Channel.ChannelEnum): - Output only. The - `channel `__ - of the product. - offer_id (str): - Output only. Your unique identifier for the product. This is - the same for the product input and processed product. - Leading and trailing whitespaces are stripped and multiple - whitespaces are replaced by a single whitespace upon - submission. See the `product data - specification `__ - for details. - content_language (str): - Output only. The two-letter `ISO - 639-1 `__ language - code for the product. - feed_label (str): - Output only. The feed label for the product. - data_source (str): - Output only. The primary data source of the - product. - version_number (int): - Output only. Represents the existing version (freshness) of - the product, 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 - product. Re-insertion (for example, product refresh after 30 - days) can be performed with the current ``version_number``. - - Only supported for insertions into primary data sources. - - If the operation is prevented, the aborted exception will be - thrown. - - This field is a member of `oneof`_ ``_version_number``. - attributes (google.shopping.merchant_products_v1beta.types.Attributes): - Output only. A list of product attributes. - custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): - Output only. A list of custom (merchant-provided) - attributes. It can also be used to submit 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, such as additional attributes used for Buy on - Google. - product_status (google.shopping.merchant_products_v1beta.types.ProductStatus): - Output only. The status of a product, data - validation issues, that is, information about a - product computed asynchronously. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - channel: types.Channel.ChannelEnum = proto.Field( - proto.ENUM, - number=2, - enum=types.Channel.ChannelEnum, - ) - offer_id: str = proto.Field( - proto.STRING, - number=3, - ) - content_language: str = proto.Field( - proto.STRING, - number=4, - ) - feed_label: str = proto.Field( - proto.STRING, - number=5, - ) - data_source: str = proto.Field( - proto.STRING, - number=6, - ) - version_number: int = proto.Field( - proto.INT64, - number=7, - optional=True, - ) - attributes: products_common.Attributes = proto.Field( - proto.MESSAGE, - number=8, - message=products_common.Attributes, - ) - custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=types.CustomAttribute, - ) - product_status: products_common.ProductStatus = proto.Field( - proto.MESSAGE, - number=10, - message=products_common.ProductStatus, - ) - - -class GetProductRequest(proto.Message): - r"""Request message for the GetProduct method. - - Attributes: - name (str): - Required. The name of the product to retrieve. Format: - ``accounts/{account}/products/{product}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProductsRequest(proto.Message): - r"""Request message for the ListProducts method. - - Attributes: - parent (str): - Required. The account to list processed - products for. Format: accounts/{account} - page_size (int): - The maximum number of products 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 products will be returned. - page_token (str): - A page token, received from a previous ``ListProducts`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListProducts`` 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 ListProductsResponse(proto.Message): - r"""Response message for the ListProducts method. - - Attributes: - products (MutableSequence[google.shopping.merchant_products_v1beta.types.Product]): - The processed products from the specified - account. These are your processed products after - applying rules and supplemental data sources. - 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 - - products: MutableSequence['Product'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Product', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products_common.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products_common.py deleted file mode 100644 index 17ed5bd1355b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/google/shopping/merchant_products_v1beta/types/products_common.py +++ /dev/null @@ -1,1906 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.products.v1beta', - manifest={ - 'SubscriptionPeriod', - 'Attributes', - 'Tax', - 'ShippingWeight', - 'ShippingDimension', - 'UnitPricingBaseMeasure', - 'UnitPricingMeasure', - 'SubscriptionCost', - 'Installment', - 'LoyaltyPoints', - 'LoyaltyProgram', - 'Shipping', - 'FreeShippingThreshold', - 'ProductDetail', - 'Certification', - 'ProductStructuredTitle', - 'ProductStructuredDescription', - 'ProductDimension', - 'ProductWeight', - 'ProductStatus', - 'CloudExportAdditionalProperties', - }, -) - - -class SubscriptionPeriod(proto.Enum): - r"""The subscription period of the product. - - Values: - SUBSCRIPTION_PERIOD_UNSPECIFIED (0): - Indicates that the subscription period is - unspecified. - MONTH (1): - Indicates that the subscription period is - month. - YEAR (2): - Indicates that the subscription period is - year. - """ - SUBSCRIPTION_PERIOD_UNSPECIFIED = 0 - MONTH = 1 - YEAR = 2 - - -class Attributes(proto.Message): - r"""Attributes. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - identifier_exists (bool): - Set this value to false when the item does - not have unique product identifiers appropriate - to its category, such as GTIN, MPN, and brand. - Defaults to true, if not provided. - - This field is a member of `oneof`_ ``_identifier_exists``. - is_bundle (bool): - Whether the item is a merchant-defined - bundle. A bundle is a custom grouping of - different products sold by a merchant for a - single price. - - This field is a member of `oneof`_ ``_is_bundle``. - title (str): - Title of the item. - - This field is a member of `oneof`_ ``_title``. - description (str): - Description of the item. - - This field is a member of `oneof`_ ``_description``. - link (str): - URL directly linking to your item's page on - your online store. - - This field is a member of `oneof`_ ``_link``. - mobile_link (str): - URL for the mobile-optimized version of your - item's landing page. - - This field is a member of `oneof`_ ``_mobile_link``. - canonical_link (str): - URL for the canonical version of your item's - landing page. - - This field is a member of `oneof`_ ``_canonical_link``. - image_link (str): - URL of an image of the item. - - This field is a member of `oneof`_ ``_image_link``. - additional_image_links (MutableSequence[str]): - Additional URLs of images of the item. - expiration_date (google.protobuf.timestamp_pb2.Timestamp): - Date on which the item should expire, as specified upon - insertion, in `ISO - 8601 `__ format. The - actual expiration date is exposed in ``productstatuses`` as - `googleExpirationDate `__ - and might be earlier if ``expirationDate`` is too far in the - future. - disclosure_date (google.protobuf.timestamp_pb2.Timestamp): - The date time when an offer becomes visible in search - results across Google’s YouTube surfaces, in `ISO - 8601 `__ format. See - `Disclosure - date `__ - for more information. - adult (bool): - Set to true if the item is targeted towards - adults. - - This field is a member of `oneof`_ ``_adult``. - age_group (str): - Target `age - group `__ - of the item. - - This field is a member of `oneof`_ ``_age_group``. - availability (str): - Availability status of the item. - - This field is a member of `oneof`_ ``_availability``. - availability_date (google.protobuf.timestamp_pb2.Timestamp): - The day a pre-ordered product becomes available for - delivery, in `ISO - 8601 `__ format. - brand (str): - Brand of the item. - - This field is a member of `oneof`_ ``_brand``. - color (str): - Color of the item. - - This field is a member of `oneof`_ ``_color``. - condition (str): - Condition or state of the item. - - This field is a member of `oneof`_ ``_condition``. - gender (str): - Target gender of the item. - - This field is a member of `oneof`_ ``_gender``. - google_product_category (str): - Google's category of the item (see `Google product - taxonomy `__). - When querying products, this field will contain the user - provided value. There is currently no way to get back the - auto assigned google product categories through the API. - - This field is a member of `oneof`_ ``_google_product_category``. - gtin (str): - Global Trade Item Number - (`GTIN `__) - of the item. - - This field is a member of `oneof`_ ``_gtin``. - item_group_id (str): - Shared identifier for all variants of the - same product. - - This field is a member of `oneof`_ ``_item_group_id``. - material (str): - The material of which the item is made. - - This field is a member of `oneof`_ ``_material``. - mpn (str): - Manufacturer Part Number - (`MPN `__) - of the item. - - This field is a member of `oneof`_ ``_mpn``. - pattern (str): - The item's pattern (for example, polka dots). - - This field is a member of `oneof`_ ``_pattern``. - price (google.shopping.type.types.Price): - Price of the item. - installment (google.shopping.merchant_products_v1beta.types.Installment): - Number and amount of installments to pay for - an item. - subscription_cost (google.shopping.merchant_products_v1beta.types.SubscriptionCost): - Number of periods (months or years) and - amount of payment per period for an item with an - associated subscription contract. - loyalty_points (google.shopping.merchant_products_v1beta.types.LoyaltyPoints): - Loyalty points that users receive after - purchasing the item. Japan only. - loyalty_programs (MutableSequence[google.shopping.merchant_products_v1beta.types.LoyaltyProgram]): - A list of loyalty program information that is - used to surface loyalty benefits (for example, - better pricing, points, etc) to the user of this - item. - product_types (MutableSequence[str]): - Categories of the item (formatted as in `product data - specification `__). - sale_price (google.shopping.type.types.Price): - Advertised sale price of the item. - sale_price_effective_date (google.type.interval_pb2.Interval): - Date range during which the item is on sale (see `product - data - specification `__). - sell_on_google_quantity (int): - The quantity of the product that is available - for selling on Google. Supported only for online - products. - - This field is a member of `oneof`_ ``_sell_on_google_quantity``. - product_height (google.shopping.merchant_products_v1beta.types.ProductDimension): - The height of the product in the units - provided. The value must be between - 0 (exclusive) and 3000 (inclusive). - product_length (google.shopping.merchant_products_v1beta.types.ProductDimension): - The length of the product in the units - provided. The value must be between 0 - (exclusive) and 3000 (inclusive). - product_width (google.shopping.merchant_products_v1beta.types.ProductDimension): - The width of the product in the units - provided. The value must be between 0 - (exclusive) and 3000 (inclusive). - product_weight (google.shopping.merchant_products_v1beta.types.ProductWeight): - The weight of the product in the units - provided. The value must be between 0 - (exclusive) and 2000 (inclusive). - shipping (MutableSequence[google.shopping.merchant_products_v1beta.types.Shipping]): - Shipping rules. - free_shipping_threshold (MutableSequence[google.shopping.merchant_products_v1beta.types.FreeShippingThreshold]): - Conditions to be met for a product to have - free shipping. - shipping_weight (google.shopping.merchant_products_v1beta.types.ShippingWeight): - Weight of the item for shipping. - shipping_length (google.shopping.merchant_products_v1beta.types.ShippingDimension): - Length of the item for shipping. - shipping_width (google.shopping.merchant_products_v1beta.types.ShippingDimension): - Width of the item for shipping. - shipping_height (google.shopping.merchant_products_v1beta.types.ShippingDimension): - Height of the item for shipping. - max_handling_time (int): - Maximal product handling time (in business - days). - - This field is a member of `oneof`_ ``_max_handling_time``. - min_handling_time (int): - Minimal product handling time (in business - days). - - This field is a member of `oneof`_ ``_min_handling_time``. - shipping_label (str): - The shipping label of the product, used to - group product in account-level shipping rules. - - This field is a member of `oneof`_ ``_shipping_label``. - transit_time_label (str): - The transit time label of the product, used - to group product in account-level transit time - tables. - - This field is a member of `oneof`_ ``_transit_time_label``. - size (str): - Size of the item. Only one value is allowed. For variants - with different sizes, insert a separate product for each - size with the same ``itemGroupId`` value (see - [https://support.google.com/merchants/answer/6324492](size - definition)). - - This field is a member of `oneof`_ ``_size``. - size_system (str): - System in which the size is specified. - Recommended for apparel items. - - This field is a member of `oneof`_ ``_size_system``. - size_types (MutableSequence[str]): - The cut of the item. It can be used to represent combined - size types for apparel items. Maximum two of size types can - be provided (see - [https://support.google.com/merchants/answer/6324497](size - type)). - taxes (MutableSequence[google.shopping.merchant_products_v1beta.types.Tax]): - Tax information. - tax_category (str): - The tax category of the product, used to - configure detailed tax nexus in account-level - tax settings. - - This field is a member of `oneof`_ ``_tax_category``. - energy_efficiency_class (str): - The energy efficiency class as defined in EU - directive 2010/30/EU. - - This field is a member of `oneof`_ ``_energy_efficiency_class``. - min_energy_efficiency_class (str): - The energy efficiency class as defined in EU - directive 2010/30/EU. - - This field is a member of `oneof`_ ``_min_energy_efficiency_class``. - max_energy_efficiency_class (str): - The energy efficiency class as defined in EU - directive 2010/30/EU. - - This field is a member of `oneof`_ ``_max_energy_efficiency_class``. - unit_pricing_measure (google.shopping.merchant_products_v1beta.types.UnitPricingMeasure): - The measure and dimension of an item. - unit_pricing_base_measure (google.shopping.merchant_products_v1beta.types.UnitPricingBaseMeasure): - The preference of the denominator of the unit - price. - multipack (int): - The number of identical products in a - merchant-defined multipack. - - This field is a member of `oneof`_ ``_multipack``. - ads_grouping (str): - Used to group items in an arbitrary way. Only - for CPA%, discouraged otherwise. - - This field is a member of `oneof`_ ``_ads_grouping``. - ads_labels (MutableSequence[str]): - Similar to ads_grouping, but only works on CPC. - ads_redirect (str): - Allows advertisers to override the item URL - when the product is shown within the context of - Product ads. - - This field is a member of `oneof`_ ``_ads_redirect``. - cost_of_goods_sold (google.shopping.type.types.Price): - Cost of goods sold. Used for gross profit - reporting. - product_details (MutableSequence[google.shopping.merchant_products_v1beta.types.ProductDetail]): - Technical specification or additional product - details. - product_highlights (MutableSequence[str]): - Bullet points describing the most relevant - highlights of a product. - display_ads_id (str): - An identifier for an item for dynamic - remarketing campaigns. - - This field is a member of `oneof`_ ``_display_ads_id``. - display_ads_similar_ids (MutableSequence[str]): - Advertiser-specified recommendations. - display_ads_title (str): - Title of an item for dynamic remarketing - campaigns. - - This field is a member of `oneof`_ ``_display_ads_title``. - display_ads_link (str): - URL directly to your item's landing page for - dynamic remarketing campaigns. - - This field is a member of `oneof`_ ``_display_ads_link``. - display_ads_value (float): - Offer margin for dynamic remarketing - campaigns. - - This field is a member of `oneof`_ ``_display_ads_value``. - promotion_ids (MutableSequence[str]): - The unique ID of a promotion. - pickup_method (str): - The pick up option for the item. - - This field is a member of `oneof`_ ``_pickup_method``. - pickup_sla (str): - Item store pickup timeline. - - This field is a member of `oneof`_ ``_pickup_sla``. - link_template (str): - Link template for merchant hosted local - storefront. - - This field is a member of `oneof`_ ``_link_template``. - mobile_link_template (str): - Link template for merchant hosted local - storefront optimized for mobile devices. - - This field is a member of `oneof`_ ``_mobile_link_template``. - custom_label_0 (str): - Custom label 0 for custom grouping of items - in a Shopping campaign. - - This field is a member of `oneof`_ ``_custom_label_0``. - custom_label_1 (str): - Custom label 1 for custom grouping of items - in a Shopping campaign. - - This field is a member of `oneof`_ ``_custom_label_1``. - custom_label_2 (str): - Custom label 2 for custom grouping of items - in a Shopping campaign. - - This field is a member of `oneof`_ ``_custom_label_2``. - custom_label_3 (str): - Custom label 3 for custom grouping of items - in a Shopping campaign. - - This field is a member of `oneof`_ ``_custom_label_3``. - custom_label_4 (str): - Custom label 4 for custom grouping of items - in a Shopping campaign. - - This field is a member of `oneof`_ ``_custom_label_4``. - included_destinations (MutableSequence[str]): - The list of destinations to include for this target - (corresponds to checked check boxes in Merchant Center). - Default destinations are always included unless provided in - ``excludedDestinations``. - excluded_destinations (MutableSequence[str]): - The list of destinations to exclude for this - target (corresponds to unchecked check boxes in - Merchant Center). - shopping_ads_excluded_countries (MutableSequence[str]): - List of country codes (ISO 3166-1 alpha-2) to - exclude the offer from Shopping Ads destination. - Countries from this list are removed from - countries configured in data source settings. - external_seller_id (str): - Required for multi-seller accounts. Use this - attribute if you're a marketplace uploading - products for various sellers to your - multi-seller account. - - This field is a member of `oneof`_ ``_external_seller_id``. - pause (str): - Publication of this item will be temporarily - `paused `__. - - This field is a member of `oneof`_ ``_pause``. - lifestyle_image_links (MutableSequence[str]): - Additional URLs of lifestyle images of the item, used to - explicitly identify images that showcase your item in a - real-world context. See the `Help Center - article `__ - for more information. - cloud_export_additional_properties (MutableSequence[google.shopping.merchant_products_v1beta.types.CloudExportAdditionalProperties]): - Extra fields to export to the Cloud Retail - program. - virtual_model_link (str): - URL of the 3D image of the item. See the `Help Center - article `__ - for more information. - - This field is a member of `oneof`_ ``_virtual_model_link``. - certifications (MutableSequence[google.shopping.merchant_products_v1beta.types.Certification]): - Product Certifications, for example for energy efficiency - labeling of products recorded in the `EU - EPREL `__ database. - See the `Help - Center `__ - article for more information. - structured_title (google.shopping.merchant_products_v1beta.types.ProductStructuredTitle): - Structured title, for algorithmically - (AI)-generated titles. - - This field is a member of `oneof`_ ``_structured_title``. - structured_description (google.shopping.merchant_products_v1beta.types.ProductStructuredDescription): - Structured description, for algorithmically - (AI)-generated descriptions. - - This field is a member of `oneof`_ ``_structured_description``. - auto_pricing_min_price (google.shopping.type.types.Price): - A safeguard in the "Automated Discounts" - (https://support.google.com/merchants/answer/10295759) - and "Dynamic Promotions" - (https://support.google.com/merchants/answer/13949249) - projects, ensuring that discounts on merchants' - offers do not fall below this value, thereby - preserving the offer's value and profitability. - """ - - identifier_exists: bool = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - is_bundle: bool = proto.Field( - proto.BOOL, - number=5, - optional=True, - ) - title: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - description: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - link: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - mobile_link: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - canonical_link: str = proto.Field( - proto.STRING, - number=10, - optional=True, - ) - image_link: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - additional_image_links: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=12, - ) - expiration_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=16, - message=timestamp_pb2.Timestamp, - ) - disclosure_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=79, - message=timestamp_pb2.Timestamp, - ) - adult: bool = proto.Field( - proto.BOOL, - number=17, - optional=True, - ) - age_group: str = proto.Field( - proto.STRING, - number=18, - optional=True, - ) - availability: str = proto.Field( - proto.STRING, - number=19, - optional=True, - ) - availability_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=20, - message=timestamp_pb2.Timestamp, - ) - brand: str = proto.Field( - proto.STRING, - number=21, - optional=True, - ) - color: str = proto.Field( - proto.STRING, - number=22, - optional=True, - ) - condition: str = proto.Field( - proto.STRING, - number=23, - optional=True, - ) - gender: str = proto.Field( - proto.STRING, - number=24, - optional=True, - ) - google_product_category: str = proto.Field( - proto.STRING, - number=25, - optional=True, - ) - gtin: str = proto.Field( - proto.STRING, - number=26, - optional=True, - ) - item_group_id: str = proto.Field( - proto.STRING, - number=27, - optional=True, - ) - material: str = proto.Field( - proto.STRING, - number=28, - optional=True, - ) - mpn: str = proto.Field( - proto.STRING, - number=29, - optional=True, - ) - pattern: str = proto.Field( - proto.STRING, - number=30, - optional=True, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=31, - message=types.Price, - ) - installment: 'Installment' = proto.Field( - proto.MESSAGE, - number=32, - message='Installment', - ) - subscription_cost: 'SubscriptionCost' = proto.Field( - proto.MESSAGE, - number=33, - message='SubscriptionCost', - ) - loyalty_points: 'LoyaltyPoints' = proto.Field( - proto.MESSAGE, - number=34, - message='LoyaltyPoints', - ) - loyalty_programs: MutableSequence['LoyaltyProgram'] = proto.RepeatedField( - proto.MESSAGE, - number=136, - message='LoyaltyProgram', - ) - product_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=35, - ) - sale_price: types.Price = proto.Field( - proto.MESSAGE, - number=36, - message=types.Price, - ) - sale_price_effective_date: interval_pb2.Interval = proto.Field( - proto.MESSAGE, - number=37, - message=interval_pb2.Interval, - ) - sell_on_google_quantity: int = proto.Field( - proto.INT64, - number=38, - optional=True, - ) - product_height: 'ProductDimension' = proto.Field( - proto.MESSAGE, - number=119, - message='ProductDimension', - ) - product_length: 'ProductDimension' = proto.Field( - proto.MESSAGE, - number=120, - message='ProductDimension', - ) - product_width: 'ProductDimension' = proto.Field( - proto.MESSAGE, - number=121, - message='ProductDimension', - ) - product_weight: 'ProductWeight' = proto.Field( - proto.MESSAGE, - number=122, - message='ProductWeight', - ) - shipping: MutableSequence['Shipping'] = proto.RepeatedField( - proto.MESSAGE, - number=39, - message='Shipping', - ) - free_shipping_threshold: MutableSequence['FreeShippingThreshold'] = proto.RepeatedField( - proto.MESSAGE, - number=135, - message='FreeShippingThreshold', - ) - shipping_weight: 'ShippingWeight' = proto.Field( - proto.MESSAGE, - number=40, - message='ShippingWeight', - ) - shipping_length: 'ShippingDimension' = proto.Field( - proto.MESSAGE, - number=41, - message='ShippingDimension', - ) - shipping_width: 'ShippingDimension' = proto.Field( - proto.MESSAGE, - number=42, - message='ShippingDimension', - ) - shipping_height: 'ShippingDimension' = proto.Field( - proto.MESSAGE, - number=43, - message='ShippingDimension', - ) - max_handling_time: int = proto.Field( - proto.INT64, - number=44, - optional=True, - ) - min_handling_time: int = proto.Field( - proto.INT64, - number=45, - optional=True, - ) - shipping_label: str = proto.Field( - proto.STRING, - number=46, - optional=True, - ) - transit_time_label: str = proto.Field( - proto.STRING, - number=47, - optional=True, - ) - size: str = proto.Field( - proto.STRING, - number=48, - optional=True, - ) - size_system: str = proto.Field( - proto.STRING, - number=49, - optional=True, - ) - size_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=50, - ) - taxes: MutableSequence['Tax'] = proto.RepeatedField( - proto.MESSAGE, - number=51, - message='Tax', - ) - tax_category: str = proto.Field( - proto.STRING, - number=52, - optional=True, - ) - energy_efficiency_class: str = proto.Field( - proto.STRING, - number=53, - optional=True, - ) - min_energy_efficiency_class: str = proto.Field( - proto.STRING, - number=54, - optional=True, - ) - max_energy_efficiency_class: str = proto.Field( - proto.STRING, - number=55, - optional=True, - ) - unit_pricing_measure: 'UnitPricingMeasure' = proto.Field( - proto.MESSAGE, - number=56, - message='UnitPricingMeasure', - ) - unit_pricing_base_measure: 'UnitPricingBaseMeasure' = proto.Field( - proto.MESSAGE, - number=57, - message='UnitPricingBaseMeasure', - ) - multipack: int = proto.Field( - proto.INT64, - number=58, - optional=True, - ) - ads_grouping: str = proto.Field( - proto.STRING, - number=59, - optional=True, - ) - ads_labels: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=60, - ) - ads_redirect: str = proto.Field( - proto.STRING, - number=61, - optional=True, - ) - cost_of_goods_sold: types.Price = proto.Field( - proto.MESSAGE, - number=62, - message=types.Price, - ) - product_details: MutableSequence['ProductDetail'] = proto.RepeatedField( - proto.MESSAGE, - number=63, - message='ProductDetail', - ) - product_highlights: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=64, - ) - display_ads_id: str = proto.Field( - proto.STRING, - number=65, - optional=True, - ) - display_ads_similar_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=66, - ) - display_ads_title: str = proto.Field( - proto.STRING, - number=67, - optional=True, - ) - display_ads_link: str = proto.Field( - proto.STRING, - number=68, - optional=True, - ) - display_ads_value: float = proto.Field( - proto.DOUBLE, - number=69, - optional=True, - ) - promotion_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=70, - ) - pickup_method: str = proto.Field( - proto.STRING, - number=80, - optional=True, - ) - pickup_sla: str = proto.Field( - proto.STRING, - number=81, - optional=True, - ) - link_template: str = proto.Field( - proto.STRING, - number=82, - optional=True, - ) - mobile_link_template: str = proto.Field( - proto.STRING, - number=83, - optional=True, - ) - custom_label_0: str = proto.Field( - proto.STRING, - number=71, - optional=True, - ) - custom_label_1: str = proto.Field( - proto.STRING, - number=72, - optional=True, - ) - custom_label_2: str = proto.Field( - proto.STRING, - number=73, - optional=True, - ) - custom_label_3: str = proto.Field( - proto.STRING, - number=74, - optional=True, - ) - custom_label_4: str = proto.Field( - proto.STRING, - number=75, - optional=True, - ) - included_destinations: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=76, - ) - excluded_destinations: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=77, - ) - shopping_ads_excluded_countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=78, - ) - external_seller_id: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - pause: str = proto.Field( - proto.STRING, - number=13, - optional=True, - ) - lifestyle_image_links: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=14, - ) - cloud_export_additional_properties: MutableSequence['CloudExportAdditionalProperties'] = proto.RepeatedField( - proto.MESSAGE, - number=84, - message='CloudExportAdditionalProperties', - ) - virtual_model_link: str = proto.Field( - proto.STRING, - number=130, - optional=True, - ) - certifications: MutableSequence['Certification'] = proto.RepeatedField( - proto.MESSAGE, - number=123, - message='Certification', - ) - structured_title: 'ProductStructuredTitle' = proto.Field( - proto.MESSAGE, - number=132, - optional=True, - message='ProductStructuredTitle', - ) - structured_description: 'ProductStructuredDescription' = proto.Field( - proto.MESSAGE, - number=133, - optional=True, - message='ProductStructuredDescription', - ) - auto_pricing_min_price: types.Price = proto.Field( - proto.MESSAGE, - number=124, - message=types.Price, - ) - - -class Tax(proto.Message): - r"""The Tax of the product. - - Attributes: - rate (float): - The percentage of tax rate that applies to - the item price. - country (str): - The country within which the item is taxed, specified as a - `CLDR territory - code `__. - region (str): - The geographic region to which the tax rate - applies. - tax_ship (bool): - Set to true if tax is charged on shipping. - location_id (int): - The numeric ID of a location that the tax rate applies to as - defined in the `AdWords - API `__. - postal_code (str): - The postal code range that the tax rate applies to, - represented by a ZIP code, a ZIP code prefix using \* - wildcard, a range between two ZIP codes or two ZIP code - prefixes of equal length. Examples: 94114, 94*, 94002-95460, - 94*-95*. - """ - - rate: float = proto.Field( - proto.DOUBLE, - number=1, - ) - country: str = proto.Field( - proto.STRING, - number=2, - ) - region: str = proto.Field( - proto.STRING, - number=3, - ) - tax_ship: bool = proto.Field( - proto.BOOL, - number=4, - ) - location_id: int = proto.Field( - proto.INT64, - number=5, - ) - postal_code: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ShippingWeight(proto.Message): - r"""The ShippingWeight of the product. - - Attributes: - value (float): - The weight of the product used to calculate - the shipping cost of the item. - unit (str): - The unit of value. - """ - - value: float = proto.Field( - proto.DOUBLE, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ShippingDimension(proto.Message): - r"""The ShippingDimension of the product. - - Attributes: - value (float): - The dimension of the product used to - calculate the shipping cost of the item. - unit (str): - The unit of value. - """ - - value: float = proto.Field( - proto.DOUBLE, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UnitPricingBaseMeasure(proto.Message): - r"""The UnitPricingBaseMeasure of the product. - - Attributes: - value (int): - The denominator of the unit price. - unit (str): - The unit of the denominator. - """ - - value: int = proto.Field( - proto.INT64, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UnitPricingMeasure(proto.Message): - r"""The UnitPricingMeasure of the product. - - Attributes: - value (float): - The measure of an item. - unit (str): - The unit of the measure. - """ - - value: float = proto.Field( - proto.DOUBLE, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SubscriptionCost(proto.Message): - r"""The SubscriptionCost of the product. - - Attributes: - period (google.shopping.merchant_products_v1beta.types.SubscriptionPeriod): - The type of subscription period. Supported values are: - - - "``month``" - - "``year``". - period_length (int): - The number of subscription periods the buyer - has to pay. - amount (google.shopping.type.types.Price): - The amount the buyer has to pay per - subscription period. - """ - - period: 'SubscriptionPeriod' = proto.Field( - proto.ENUM, - number=1, - enum='SubscriptionPeriod', - ) - period_length: int = proto.Field( - proto.INT64, - number=2, - ) - amount: types.Price = proto.Field( - proto.MESSAGE, - number=3, - message=types.Price, - ) - - -class Installment(proto.Message): - r"""A message that represents installment. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - months (int): - The number of installments the buyer has to - pay. - amount (google.shopping.type.types.Price): - The amount the buyer has to pay per month. - downpayment (google.shopping.type.types.Price): - The up-front down payment amount the buyer - has to pay. - - This field is a member of `oneof`_ ``_downpayment``. - credit_type (str): - Type of installment payments. Supported values are: - - - "``finance``" - - "``lease``". - - This field is a member of `oneof`_ ``_credit_type``. - """ - - months: int = proto.Field( - proto.INT64, - number=1, - ) - amount: types.Price = proto.Field( - proto.MESSAGE, - number=2, - message=types.Price, - ) - downpayment: types.Price = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message=types.Price, - ) - credit_type: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - - -class LoyaltyPoints(proto.Message): - r"""A message that represents loyalty points. - - Attributes: - name (str): - Name of loyalty points program. It is - recommended to limit the name to 12 full-width - characters or 24 Roman characters. - points_value (int): - The retailer's loyalty points in absolute - value. - ratio (float): - The ratio of a point when converted to - currency. Google assumes currency based on - Merchant Center settings. If ratio is left out, - it defaults to 1.0. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - points_value: int = proto.Field( - proto.INT64, - number=2, - ) - ratio: float = proto.Field( - proto.DOUBLE, - number=3, - ) - - -class LoyaltyProgram(proto.Message): - r"""A message that represents loyalty program. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - program_label (str): - The label of the loyalty program. This is an - internal label that uniquely identifies the - relationship between a merchant entity and a - loyalty program entity. The label must be - provided so that the system can associate the - assets below (for example, price and points) - with a merchant. The corresponding program must - be linked to the merchant account. - - This field is a member of `oneof`_ ``_program_label``. - tier_label (str): - The label of the tier within the loyalty - program. Must match one of the labels within the - program. - - This field is a member of `oneof`_ ``_tier_label``. - price (google.shopping.type.types.Price): - The price for members of the given tier, that - is, the instant discount price. Must be smaller - or equal to the regular price. - - This field is a member of `oneof`_ ``_price``. - cashback_for_future_use (google.shopping.type.types.Price): - The cashback that can be used for future - purchases. - - This field is a member of `oneof`_ ``_cashback_for_future_use``. - loyalty_points (int): - The amount of loyalty points earned on a - purchase. - - This field is a member of `oneof`_ ``_loyalty_points``. - """ - - program_label: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - tier_label: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message=types.Price, - ) - cashback_for_future_use: types.Price = proto.Field( - proto.MESSAGE, - number=4, - optional=True, - message=types.Price, - ) - loyalty_points: int = proto.Field( - proto.INT64, - number=5, - optional=True, - ) - - -class Shipping(proto.Message): - r"""The Shipping of the product. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - price (google.shopping.type.types.Price): - Fixed shipping price, represented as a - number. - country (str): - The `CLDR territory - code `__ - of the country to which an item will ship. - region (str): - The geographic region to which a shipping rate applies. See - `region `__ - for more information. - service (str): - A free-form description of the service class - or delivery speed. - location_id (int): - The numeric ID of a location that the shipping rate applies - to as defined in the `AdWords - API `__. - location_group_name (str): - The location where the shipping is - applicable, represented by a location group - name. - postal_code (str): - The postal code range that the shipping rate applies to, - represented by a postal code, a postal code prefix followed - by a \* wildcard, a range between two postal codes or two - postal code prefixes of equal length. - min_handling_time (int): - Minimum handling time (inclusive) between when the order is - received and shipped in business days. 0 means that the - order is shipped on the same day as it is received if it - happens before the cut-off time. - [minHandlingTime][google.shopping.content.bundles.Products.Shipping.min_handling_time] - can only be present together with - [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time]; - but it is not required if - [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time] - is present. - - This field is a member of `oneof`_ ``_min_handling_time``. - max_handling_time (int): - Maximum handling time (inclusive) between when the order is - received and shipped in business days. 0 means that the - order is shipped on the same day as it is received if it - happens before the cut-off time. Both - [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time] - and - [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time] - are required if providing shipping speeds. - [minHandlingTime][google.shopping.content.bundles.Products.Shipping.min_handling_time] - is optional if - [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time] - is present. - - This field is a member of `oneof`_ ``_max_handling_time``. - min_transit_time (int): - Minimum transit time (inclusive) between when the order has - shipped and when it is delivered in business days. 0 means - that the order is delivered on the same day as it ships. - [minTransitTime][google.shopping.content.bundles.Products.Shipping.min_transit_time] - can only be present together with - [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time]; - but it is not required if - [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time] - is present. - - This field is a member of `oneof`_ ``_min_transit_time``. - max_transit_time (int): - Maximum transit time (inclusive) between when the order has - shipped and when it is delivered in business days. 0 means - that the order is delivered on the same day as it ships. - Both - [maxHandlingTime][google.shopping.content.bundles.Products.Shipping.max_handling_time] - and - [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time] - are required if providing shipping speeds. - [minTransitTime][google.shopping.content.bundles.Products.Shipping.min_transit_time] - is optional if - [maxTransitTime][google.shopping.content.bundles.Products.Shipping.max_transit_time] - is present. - - This field is a member of `oneof`_ ``_max_transit_time``. - """ - - price: types.Price = proto.Field( - proto.MESSAGE, - number=1, - message=types.Price, - ) - country: str = proto.Field( - proto.STRING, - number=2, - ) - region: str = proto.Field( - proto.STRING, - number=3, - ) - service: str = proto.Field( - proto.STRING, - number=4, - ) - location_id: int = proto.Field( - proto.INT64, - number=5, - ) - location_group_name: str = proto.Field( - proto.STRING, - number=6, - ) - postal_code: str = proto.Field( - proto.STRING, - number=7, - ) - min_handling_time: int = proto.Field( - proto.INT64, - number=8, - optional=True, - ) - max_handling_time: int = proto.Field( - proto.INT64, - number=9, - optional=True, - ) - min_transit_time: int = proto.Field( - proto.INT64, - number=10, - optional=True, - ) - max_transit_time: int = proto.Field( - proto.INT64, - number=11, - optional=True, - ) - - -class FreeShippingThreshold(proto.Message): - r"""Conditions to be met for a product to have free shipping. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - country (str): - The `CLDR territory - code `__ - of the country to which an item will ship. - - This field is a member of `oneof`_ ``_country``. - price_threshold (google.shopping.type.types.Price): - The minimum product price for the shipping - cost to become free. Represented as a number. - - This field is a member of `oneof`_ ``_price_threshold``. - """ - - country: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - price_threshold: types.Price = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message=types.Price, - ) - - -class ProductDetail(proto.Message): - r"""The product details. - - Attributes: - section_name (str): - The section header used to group a set of - product details. - attribute_name (str): - The name of the product detail. - attribute_value (str): - The value of the product detail. - """ - - section_name: str = proto.Field( - proto.STRING, - number=1, - ) - attribute_name: str = proto.Field( - proto.STRING, - number=2, - ) - attribute_value: str = proto.Field( - proto.STRING, - number=3, - ) - - -class Certification(proto.Message): - r"""Product - `certification `__, - initially introduced for EU energy efficiency labeling compliance - using the EU EPREL database. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - certification_authority (str): - The certification authority, for example - "European_Commission". Maximum length is 2000 characters. - - This field is a member of `oneof`_ ``_certification_authority``. - certification_name (str): - The name of the certification, for example - "EPREL". Maximum length is 2000 characters. - - This field is a member of `oneof`_ ``_certification_name``. - certification_code (str): - The certification code. - Maximum length is 2000 characters. - - This field is a member of `oneof`_ ``_certification_code``. - certification_value (str): - The certification value (also known as class, - level or grade), for example "A+", "C", "gold". - Maximum length is 2000 characters. - - This field is a member of `oneof`_ ``_certification_value``. - """ - - certification_authority: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - certification_name: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - certification_code: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - certification_value: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - - -class ProductStructuredTitle(proto.Message): - r"""Structured title, for algorithmically (AI)-generated titles. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - digital_source_type (str): - The digital source type, for example - "trained_algorithmic_media". Following - `IPTC `__. - Maximum length is 40 characters. - - This field is a member of `oneof`_ ``_digital_source_type``. - content (str): - The title text - Maximum length is 150 characters - - This field is a member of `oneof`_ ``_content``. - """ - - digital_source_type: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - content: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - - -class ProductStructuredDescription(proto.Message): - r"""Structured description, for algorithmically (AI)-generated - descriptions. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - digital_source_type (str): - The digital source type, for example - "trained_algorithmic_media". Following - `IPTC `__. - Maximum length is 40 characters. - - This field is a member of `oneof`_ ``_digital_source_type``. - content (str): - The description text - Maximum length is 5000 characters - - This field is a member of `oneof`_ ``_content``. - """ - - digital_source_type: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - content: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - - -class ProductDimension(proto.Message): - r"""The dimension of the product. - - Attributes: - value (float): - Required. The dimension value represented as - a number. The value can have a maximum precision - of four decimal places. - unit (str): - Required. The dimension units. Acceptable values are: - - - "``in``" - - "``cm``". - """ - - value: float = proto.Field( - proto.DOUBLE, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ProductWeight(proto.Message): - r"""The weight of the product. - - Attributes: - value (float): - Required. The weight represented as a number. - The weight can have a maximum precision of four - decimal places. - unit (str): - Required. The weight unit. Acceptable values are: - - - "``g``" - - "``kg``" - - "``oz``" - - "``lb``". - """ - - value: float = proto.Field( - proto.DOUBLE, - number=1, - ) - unit: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ProductStatus(proto.Message): - r"""The status of a product, data validation issues, that is, - information about a product computed asynchronously. - - Attributes: - destination_statuses (MutableSequence[google.shopping.merchant_products_v1beta.types.ProductStatus.DestinationStatus]): - The intended destinations for the product. - item_level_issues (MutableSequence[google.shopping.merchant_products_v1beta.types.ProductStatus.ItemLevelIssue]): - A list of all issues associated with the - product. - creation_date (google.protobuf.timestamp_pb2.Timestamp): - Date on which the item has been created, in `ISO - 8601 `__ format. - last_update_date (google.protobuf.timestamp_pb2.Timestamp): - Date on which the item has been last updated, in `ISO - 8601 `__ format. - google_expiration_date (google.protobuf.timestamp_pb2.Timestamp): - Date on which the item expires, in `ISO - 8601 `__ format. - """ - - class DestinationStatus(proto.Message): - r"""The destination status of the product status. - - Attributes: - reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): - The name of the reporting context. - approved_countries (MutableSequence[str]): - List of country codes (ISO 3166-1 alpha-2) - where the offer is approved. - pending_countries (MutableSequence[str]): - List of country codes (ISO 3166-1 alpha-2) - where the offer is pending approval. - disapproved_countries (MutableSequence[str]): - List of country codes (ISO 3166-1 alpha-2) - where the offer is disapproved. - """ - - reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( - proto.ENUM, - number=1, - enum=types.ReportingContext.ReportingContextEnum, - ) - approved_countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - pending_countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - disapproved_countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - class ItemLevelIssue(proto.Message): - r"""The ItemLevelIssue of the product status. - - Attributes: - code (str): - The error code of the issue. - severity (google.shopping.merchant_products_v1beta.types.ProductStatus.ItemLevelIssue.Severity): - How this issue affects serving of the offer. - resolution (str): - Whether the issue can be resolved by the - merchant. - attribute (str): - The attribute's name, if the issue is caused - by a single attribute. - reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): - The reporting context the issue applies to. - description (str): - A short issue description in English. - detail (str): - A detailed issue description in English. - documentation (str): - The URL of a web page to help with resolving - this issue. - applicable_countries (MutableSequence[str]): - List of country codes (ISO 3166-1 alpha-2) - where issue applies to the offer. - """ - class Severity(proto.Enum): - r"""How the issue affects the serving of the product. - - Values: - SEVERITY_UNSPECIFIED (0): - Not specified. - NOT_IMPACTED (1): - This issue represents a warning and does not - have a direct affect on the product. - DEMOTED (2): - The product is demoted and most likely have - limited performance in search results - DISAPPROVED (3): - Issue disapproves the product. - """ - SEVERITY_UNSPECIFIED = 0 - NOT_IMPACTED = 1 - DEMOTED = 2 - DISAPPROVED = 3 - - code: str = proto.Field( - proto.STRING, - number=1, - ) - severity: 'ProductStatus.ItemLevelIssue.Severity' = proto.Field( - proto.ENUM, - number=2, - enum='ProductStatus.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=3, - message=DestinationStatus, - ) - item_level_issues: MutableSequence[ItemLevelIssue] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=ItemLevelIssue, - ) - creation_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - last_update_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - google_expiration_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - - -class CloudExportAdditionalProperties(proto.Message): - r"""Product property for the Cloud Retail API. - For example, properties for a TV product could be - "Screen-Resolution" or "Screen-Size". - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - property_name (str): - Name of the given property. For example, - "Screen-Resolution" for a TV product. Maximum - string size is 256 characters. - - This field is a member of `oneof`_ ``_property_name``. - text_value (MutableSequence[str]): - Text value of the given property. For - example, "8K(UHD)" could be a text value for a - TV product. Maximum repeatedness of this value - is 400. Values are stored in an arbitrary but - consistent order. Maximum string size is 256 - characters. - bool_value (bool): - Boolean value of the given property. For - example for a TV product, "True" or "False" if - the screen is UHD. - - This field is a member of `oneof`_ ``_bool_value``. - int_value (MutableSequence[int]): - Integer values of the given property. For - example, 1080 for a TV product's Screen - Resolution. Maximum repeatedness of this value - is 400. Values are stored in an arbitrary but - consistent order. - float_value (MutableSequence[float]): - Float values of the given property. For - example for a TV product 1.2345. Maximum - repeatedness of this value is 400. Values are - stored in an arbitrary but consistent order. - min_value (float): - Minimum float value of the given property. - For example for a TV product 1.00. - - This field is a member of `oneof`_ ``_min_value``. - max_value (float): - Maximum float value of the given property. - For example for a TV product 100.00. - - This field is a member of `oneof`_ ``_max_value``. - unit_code (str): - Unit of the given property. For example, - "Pixels" for a TV product. Maximum string size - is 256B. - - This field is a member of `oneof`_ ``_unit_code``. - """ - - property_name: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - text_value: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - bool_value: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - int_value: MutableSequence[int] = proto.RepeatedField( - proto.INT64, - number=4, - ) - float_value: MutableSequence[float] = proto.RepeatedField( - proto.FLOAT, - number=5, - ) - min_value: float = proto.Field( - proto.FLOAT, - number=6, - optional=True, - ) - max_value: float = proto.Field( - proto.FLOAT, - number=7, - optional=True, - ) - unit_code: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-products/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/noxfile.py deleted file mode 100644 index 1379acce6dcc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products' - -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_products_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_products_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-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py deleted file mode 100644 index 6674700d5aad..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_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 DeleteProductInput -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-products - - -# [START merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_products_v1beta - - -async def sample_delete_product_input(): - # Create a client - client = merchant_products_v1beta.ProductInputsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.DeleteProductInputRequest( - name="name_value", - data_source="data_source_value", - ) - - # Make the request - await client.delete_product_input(request=request) - - -# [END merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_async] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py deleted file mode 100644 index 9124f5eb48f6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_delete_product_input_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 DeleteProductInput -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-products - - -# [START merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_products_v1beta - - -def sample_delete_product_input(): - # Create a client - client = merchant_products_v1beta.ProductInputsServiceClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.DeleteProductInputRequest( - name="name_value", - data_source="data_source_value", - ) - - # Make the request - client.delete_product_input(request=request) - - -# [END merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_sync] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_async.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_async.py deleted file mode 100644 index f42f63bd9437..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_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 InsertProductInput -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-products - - -# [START merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_products_v1beta - - -async def sample_insert_product_input(): - # Create a client - client = merchant_products_v1beta.ProductInputsServiceAsyncClient() - - # Initialize request argument(s) - product_input = merchant_products_v1beta.ProductInput() - product_input.channel = "LOCAL" - product_input.offer_id = "offer_id_value" - product_input.content_language = "content_language_value" - product_input.feed_label = "feed_label_value" - - request = merchant_products_v1beta.InsertProductInputRequest( - parent="parent_value", - product_input=product_input, - data_source="data_source_value", - ) - - # Make the request - response = await client.insert_product_input(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_async] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_sync.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_sync.py deleted file mode 100644 index 2a339ed09b3c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_product_inputs_service_insert_product_input_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 InsertProductInput -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-products - - -# [START merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_products_v1beta - - -def sample_insert_product_input(): - # Create a client - client = merchant_products_v1beta.ProductInputsServiceClient() - - # Initialize request argument(s) - product_input = merchant_products_v1beta.ProductInput() - product_input.channel = "LOCAL" - product_input.offer_id = "offer_id_value" - product_input.content_language = "content_language_value" - product_input.feed_label = "feed_label_value" - - request = merchant_products_v1beta.InsertProductInputRequest( - parent="parent_value", - product_input=product_input, - data_source="data_source_value", - ) - - # Make the request - response = client.insert_product_input(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_sync] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_async.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_async.py deleted file mode 100644 index 6f176867a7f1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_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 GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-products - - -# [START merchantapi_v1beta_generated_ProductsService_GetProduct_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_products_v1beta - - -async def sample_get_product(): - # Create a client - client = merchant_products_v1beta.ProductsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = await client.get_product(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProductsService_GetProduct_async] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_sync.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_sync.py deleted file mode 100644 index 9cbb8a0c4bba..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_get_product_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 GetProduct -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-products - - -# [START merchantapi_v1beta_generated_ProductsService_GetProduct_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_products_v1beta - - -def sample_get_product(): - # Create a client - client = merchant_products_v1beta.ProductsServiceClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.GetProductRequest( - name="name_value", - ) - - # Make the request - response = client.get_product(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProductsService_GetProduct_sync] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_async.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_async.py deleted file mode 100644 index 2c618af2956b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_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 ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-products - - -# [START merchantapi_v1beta_generated_ProductsService_ListProducts_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_products_v1beta - - -async def sample_list_products(): - # Create a client - client = merchant_products_v1beta.ProductsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_ProductsService_ListProducts_async] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_sync.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_sync.py deleted file mode 100644 index b76624178a59..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/merchantapi_v1beta_generated_products_service_list_products_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 ListProducts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-products - - -# [START merchantapi_v1beta_generated_ProductsService_ListProducts_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_products_v1beta - - -def sample_list_products(): - # Create a client - client = merchant_products_v1beta.ProductsServiceClient() - - # Initialize request argument(s) - request = merchant_products_v1beta.ListProductsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_products(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_ProductsService_ListProducts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.products.v1beta.json b/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.products.v1beta.json deleted file mode 100644 index 10f94f8cadc7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.products.v1beta.json +++ /dev/null @@ -1,645 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.products.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-products", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceAsyncClient", - "shortName": "ProductInputsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceAsyncClient.delete_product_input", - "method": { - "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService.DeleteProductInput", - "service": { - "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService", - "shortName": "ProductInputsService" - }, - "shortName": "DeleteProductInput" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_products_v1beta.types.DeleteProductInputRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_product_input" - }, - "description": "Sample for DeleteProductInput", - "file": "merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_product_inputs_service_delete_product_input_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceClient", - "shortName": "ProductInputsServiceClient" - }, - "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceClient.delete_product_input", - "method": { - "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService.DeleteProductInput", - "service": { - "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService", - "shortName": "ProductInputsService" - }, - "shortName": "DeleteProductInput" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_products_v1beta.types.DeleteProductInputRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_product_input" - }, - "description": "Sample for DeleteProductInput", - "file": "merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProductInputsService_DeleteProductInput_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_product_inputs_service_delete_product_input_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceAsyncClient", - "shortName": "ProductInputsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceAsyncClient.insert_product_input", - "method": { - "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService.InsertProductInput", - "service": { - "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService", - "shortName": "ProductInputsService" - }, - "shortName": "InsertProductInput" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_products_v1beta.types.InsertProductInputRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.shopping.merchant_products_v1beta.types.ProductInput", - "shortName": "insert_product_input" - }, - "description": "Sample for InsertProductInput", - "file": "merchantapi_v1beta_generated_product_inputs_service_insert_product_input_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_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_product_inputs_service_insert_product_input_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceClient", - "shortName": "ProductInputsServiceClient" - }, - "fullName": "google.shopping.merchant_products_v1beta.ProductInputsServiceClient.insert_product_input", - "method": { - "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService.InsertProductInput", - "service": { - "fullName": "google.shopping.merchant.products.v1beta.ProductInputsService", - "shortName": "ProductInputsService" - }, - "shortName": "InsertProductInput" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_products_v1beta.types.InsertProductInputRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.shopping.merchant_products_v1beta.types.ProductInput", - "shortName": "insert_product_input" - }, - "description": "Sample for InsertProductInput", - "file": "merchantapi_v1beta_generated_product_inputs_service_insert_product_input_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProductInputsService_InsertProductInput_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_product_inputs_service_insert_product_input_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceAsyncClient", - "shortName": "ProductsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceAsyncClient.get_product", - "method": { - "fullName": "google.shopping.merchant.products.v1beta.ProductsService.GetProduct", - "service": { - "fullName": "google.shopping.merchant.products.v1beta.ProductsService", - "shortName": "ProductsService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_products_v1beta.types.GetProductRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.shopping.merchant_products_v1beta.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "merchantapi_v1beta_generated_products_service_get_product_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProductsService_GetProduct_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_products_service_get_product_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceClient", - "shortName": "ProductsServiceClient" - }, - "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceClient.get_product", - "method": { - "fullName": "google.shopping.merchant.products.v1beta.ProductsService.GetProduct", - "service": { - "fullName": "google.shopping.merchant.products.v1beta.ProductsService", - "shortName": "ProductsService" - }, - "shortName": "GetProduct" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_products_v1beta.types.GetProductRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.shopping.merchant_products_v1beta.types.Product", - "shortName": "get_product" - }, - "description": "Sample for GetProduct", - "file": "merchantapi_v1beta_generated_products_service_get_product_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProductsService_GetProduct_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_products_service_get_product_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceAsyncClient", - "shortName": "ProductsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceAsyncClient.list_products", - "method": { - "fullName": "google.shopping.merchant.products.v1beta.ProductsService.ListProducts", - "service": { - "fullName": "google.shopping.merchant.products.v1beta.ProductsService", - "shortName": "ProductsService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_products_v1beta.types.ListProductsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.shopping.merchant_products_v1beta.services.products_service.pagers.ListProductsAsyncPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "merchantapi_v1beta_generated_products_service_list_products_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProductsService_ListProducts_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_products_service_list_products_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceClient", - "shortName": "ProductsServiceClient" - }, - "fullName": "google.shopping.merchant_products_v1beta.ProductsServiceClient.list_products", - "method": { - "fullName": "google.shopping.merchant.products.v1beta.ProductsService.ListProducts", - "service": { - "fullName": "google.shopping.merchant.products.v1beta.ProductsService", - "shortName": "ProductsService" - }, - "shortName": "ListProducts" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_products_v1beta.types.ListProductsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.shopping.merchant_products_v1beta.services.products_service.pagers.ListProductsPager", - "shortName": "list_products" - }, - "description": "Sample for ListProducts", - "file": "merchantapi_v1beta_generated_products_service_list_products_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProductsService_ListProducts_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_products_service_list_products_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/scripts/fixup_merchant_products_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/scripts/fixup_merchant_products_v1beta_keywords.py deleted file mode 100644 index 9ec72e193341..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/scripts/fixup_merchant_products_v1beta_keywords.py +++ /dev/null @@ -1,179 +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_productsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'delete_product_input': ('name', 'data_source', ), - 'get_product': ('name', ), - 'insert_product_input': ('parent', 'product_input', 'data_source', ), - 'list_products': ('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_productsCallTransformer(), -): - """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_products 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-products/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/setup.py deleted file mode 100644 index 2463758762c3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products' - - -description = "Google Shopping Merchant Products API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_products/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-products" - -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-products/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 130a0c0f80ab..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/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-products/v1beta/tests/unit/gapic/merchant_products_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_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-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_product_inputs_service.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_product_inputs_service.py deleted file mode 100644 index 86ae41a6011d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_product_inputs_service.py +++ /dev/null @@ -1,2788 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_products_v1beta.services.product_inputs_service import ProductInputsServiceAsyncClient -from google.shopping.merchant_products_v1beta.services.product_inputs_service import ProductInputsServiceClient -from google.shopping.merchant_products_v1beta.services.product_inputs_service import transports -from google.shopping.merchant_products_v1beta.types import productinputs -from google.shopping.merchant_products_v1beta.types import products_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 ProductInputsServiceClient._get_default_mtls_endpoint(None) is None - assert ProductInputsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductInputsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductInputsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductInputsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductInputsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ProductInputsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ProductInputsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ProductInputsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ProductInputsServiceClient._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 ProductInputsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ProductInputsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ProductInputsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ProductInputsServiceClient._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 ProductInputsServiceClient._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 ProductInputsServiceClient._get_client_cert_source(None, False) is None - assert ProductInputsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ProductInputsServiceClient._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 ProductInputsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ProductInputsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ProductInputsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceClient)) -@mock.patch.object(ProductInputsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ProductInputsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ProductInputsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ProductInputsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ProductInputsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ProductInputsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProductInputsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ProductInputsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProductInputsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProductInputsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProductInputsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ProductInputsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ProductInputsServiceClient._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 ProductInputsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ProductInputsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ProductInputsServiceClient._get_universe_domain(None, None) == ProductInputsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ProductInputsServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc"), - (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductInputsServiceClient, "grpc"), - (ProductInputsServiceAsyncClient, "grpc_asyncio"), - (ProductInputsServiceClient, "rest"), -]) -def test_product_inputs_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.ProductInputsServiceGrpcTransport, "grpc"), - (transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ProductInputsServiceRestTransport, "rest"), -]) -def test_product_inputs_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", [ - (ProductInputsServiceClient, "grpc"), - (ProductInputsServiceAsyncClient, "grpc_asyncio"), - (ProductInputsServiceClient, "rest"), -]) -def test_product_inputs_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_product_inputs_service_client_get_transport_class(): - transport = ProductInputsServiceClient.get_transport_class() - available_transports = [ - transports.ProductInputsServiceGrpcTransport, - transports.ProductInputsServiceRestTransport, - ] - assert transport in available_transports - - transport = ProductInputsServiceClient.get_transport_class("grpc") - assert transport == transports.ProductInputsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc"), - (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest"), -]) -@mock.patch.object(ProductInputsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceClient)) -@mock.patch.object(ProductInputsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceAsyncClient)) -def test_product_inputs_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(ProductInputsServiceClient, '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(ProductInputsServiceClient, '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", [ - (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc", "true"), - (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc", "false"), - (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest", "true"), - (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ProductInputsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceClient)) -@mock.patch.object(ProductInputsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_inputs_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", [ - ProductInputsServiceClient, ProductInputsServiceAsyncClient -]) -@mock.patch.object(ProductInputsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductInputsServiceClient)) -@mock.patch.object(ProductInputsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductInputsServiceAsyncClient)) -def test_product_inputs_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", [ - ProductInputsServiceClient, ProductInputsServiceAsyncClient -]) -@mock.patch.object(ProductInputsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceClient)) -@mock.patch.object(ProductInputsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductInputsServiceAsyncClient)) -def test_product_inputs_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ProductInputsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ProductInputsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ProductInputsServiceClient._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", [ - (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc"), - (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest"), -]) -def test_product_inputs_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", [ - (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc", grpc_helpers), - (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ProductInputsServiceClient, transports.ProductInputsServiceRestTransport, "rest", None), -]) -def test_product_inputs_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_product_inputs_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_products_v1beta.services.product_inputs_service.transports.ProductInputsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductInputsServiceClient( - 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", [ - (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport, "grpc", grpc_helpers), - (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_product_inputs_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", [ - productinputs.InsertProductInputRequest, - dict, -]) -def test_insert_product_input(request_type, transport: str = 'grpc'): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product_input), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = productinputs.ProductInput( - name='name_value', - product='product_value', - channel=types.Channel.ChannelEnum.ONLINE, - offer_id='offer_id_value', - content_language='content_language_value', - feed_label='feed_label_value', - version_number=1518, - ) - response = client.insert_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = productinputs.InsertProductInputRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, productinputs.ProductInput) - assert response.name == 'name_value' - assert response.product == 'product_value' - assert response.channel == types.Channel.ChannelEnum.ONLINE - assert response.offer_id == 'offer_id_value' - assert response.content_language == 'content_language_value' - assert response.feed_label == 'feed_label_value' - assert response.version_number == 1518 - - -def test_insert_product_input_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = productinputs.InsertProductInputRequest( - 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_product_input), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_product_input(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == productinputs.InsertProductInputRequest( - parent='parent_value', - data_source='data_source_value', - ) - -def test_insert_product_input_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_product_input in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_product_input] = mock_rpc - request = {} - client.insert_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_product_input(request) - - # Establish that a new wrapper 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_product_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ProductInputsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_product_input in client._client._transport._wrapped_methods - - # 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_product_input] = mock_rpc - - request = {} - await client.insert_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_product_input(request) - - # Establish that a new wrapper 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_product_input_async(transport: str = 'grpc_asyncio', request_type=productinputs.InsertProductInputRequest): - client = ProductInputsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product_input), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(productinputs.ProductInput( - name='name_value', - product='product_value', - channel=types.Channel.ChannelEnum.ONLINE, - offer_id='offer_id_value', - content_language='content_language_value', - feed_label='feed_label_value', - version_number=1518, - )) - response = await client.insert_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = productinputs.InsertProductInputRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, productinputs.ProductInput) - assert response.name == 'name_value' - assert response.product == 'product_value' - assert response.channel == types.Channel.ChannelEnum.ONLINE - assert response.offer_id == 'offer_id_value' - assert response.content_language == 'content_language_value' - assert response.feed_label == 'feed_label_value' - assert response.version_number == 1518 - - -@pytest.mark.asyncio -async def test_insert_product_input_async_from_dict(): - await test_insert_product_input_async(request_type=dict) - -def test_insert_product_input_field_headers(): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = productinputs.InsertProductInputRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_product_input), - '__call__') as call: - call.return_value = productinputs.ProductInput() - client.insert_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_input_field_headers_async(): - client = ProductInputsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = productinputs.InsertProductInputRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_product_input), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(productinputs.ProductInput()) - await client.insert_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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", [ - productinputs.DeleteProductInputRequest, - dict, -]) -def test_delete_product_input(request_type, transport: str = 'grpc'): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product_input), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = productinputs.DeleteProductInputRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_product_input_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = productinputs.DeleteProductInputRequest( - name='name_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.delete_product_input), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_product_input(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == productinputs.DeleteProductInputRequest( - name='name_value', - data_source='data_source_value', - ) - -def test_delete_product_input_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_product_input in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_product_input] = mock_rpc - request = {} - client.delete_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_product_input(request) - - # Establish that a new wrapper 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_product_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ProductInputsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_product_input in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_product_input] = mock_rpc - - request = {} - await client.delete_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_product_input(request) - - # Establish that a new wrapper 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_product_input_async(transport: str = 'grpc_asyncio', request_type=productinputs.DeleteProductInputRequest): - client = ProductInputsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product_input), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = productinputs.DeleteProductInputRequest() - 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_product_input_async_from_dict(): - await test_delete_product_input_async(request_type=dict) - -def test_delete_product_input_field_headers(): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = productinputs.DeleteProductInputRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product_input), - '__call__') as call: - call.return_value = None - client.delete_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_input_field_headers_async(): - client = ProductInputsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = productinputs.DeleteProductInputRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product_input), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_input_flattened(): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product_input), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_product_input( - 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_product_input_flattened_error(): - client = ProductInputsServiceClient( - credentials=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_product_input( - productinputs.DeleteProductInputRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_product_input_flattened_async(): - client = ProductInputsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_product_input), - '__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_product_input( - 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_product_input_flattened_error_async(): - client = ProductInputsServiceAsyncClient( - credentials=async_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_product_input( - productinputs.DeleteProductInputRequest(), - name='name_value', - ) - - -def test_insert_product_input_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_product_input in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_product_input] = mock_rpc - - request = {} - client.insert_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_product_input(request) - - # Establish 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_product_input_rest_required_fields(request_type=productinputs.InsertProductInputRequest): - transport_class = transports.ProductInputsServiceRestTransport - - 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 - assert "dataSource" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_product_input._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "dataSource" in jsonified_request - assert jsonified_request["dataSource"] == request_init["data_source"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["dataSource"] = 'data_source_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_product_input._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("data_source", )) - 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 = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = productinputs.ProductInput() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = productinputs.ProductInput.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.insert_product_input(request) - - expected_params = [ - ( - "dataSource", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_product_input_rest_unset_required_fields(): - transport = transports.ProductInputsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_product_input._get_unset_required_fields({}) - assert set(unset_fields) == (set(("dataSource", )) & set(("parent", "productInput", "dataSource", ))) - - -def test_delete_product_input_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_product_input in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_product_input] = mock_rpc - - request = {} - client.delete_product_input(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_product_input(request) - - # Establish 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_product_input_rest_required_fields(request_type=productinputs.DeleteProductInputRequest): - transport_class = transports.ProductInputsServiceRestTransport - - request_init = {} - request_init["name"] = "" - 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 - assert "dataSource" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_input._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "dataSource" in jsonified_request - assert jsonified_request["dataSource"] == request_init["data_source"] - - jsonified_request["name"] = 'name_value' - jsonified_request["dataSource"] = 'data_source_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_input._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("data_source", )) - jsonified_request.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 "dataSource" in jsonified_request - assert jsonified_request["dataSource"] == 'data_source_value' - - client = ProductInputsServiceClient( - 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 - - response = client.delete_product_input(request) - - expected_params = [ - ( - "dataSource", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_product_input_rest_unset_required_fields(): - transport = transports.ProductInputsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_product_input._get_unset_required_fields({}) - assert set(unset_fields) == (set(("dataSource", )) & set(("name", "dataSource", ))) - - -def test_delete_product_input_rest_flattened(): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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/productInputs/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 - - client.delete_product_input(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/products/v1beta/{name=accounts/*/productInputs/*}" % client.transport._host, args[1]) - - -def test_delete_product_input_rest_flattened_error(transport: str = 'rest'): - client = ProductInputsServiceClient( - credentials=ga_credentials.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_product_input( - productinputs.DeleteProductInputRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductInputsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductInputsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductInputsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductInputsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductInputsServiceClient( - 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 = ProductInputsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductInputsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductInputsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductInputsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductInputsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductInputsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductInputsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductInputsServiceGrpcTransport, - transports.ProductInputsServiceGrpcAsyncIOTransport, - transports.ProductInputsServiceRestTransport, -]) -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 = ProductInputsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ProductInputsServiceClient( - 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_product_input_empty_call_grpc(): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_product_input), - '__call__') as call: - call.return_value = productinputs.ProductInput() - client.insert_product_input(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = productinputs.InsertProductInputRequest() - - assert args[0] == request_msg - - -# This 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_product_input_empty_call_grpc(): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_product_input), - '__call__') as call: - call.return_value = None - client.delete_product_input(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = productinputs.DeleteProductInputRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ProductInputsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ProductInputsServiceAsyncClient( - 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_product_input_empty_call_grpc_asyncio(): - client = ProductInputsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_product_input), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(productinputs.ProductInput( - name='name_value', - product='product_value', - channel=types.Channel.ChannelEnum.ONLINE, - offer_id='offer_id_value', - content_language='content_language_value', - feed_label='feed_label_value', - version_number=1518, - )) - await client.insert_product_input(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = productinputs.InsertProductInputRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_product_input_empty_call_grpc_asyncio(): - client = ProductInputsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_product_input), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product_input(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = productinputs.DeleteProductInputRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ProductInputsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_insert_product_input_rest_bad_request(request_type=productinputs.InsertProductInputRequest): - client = ProductInputsServiceClient( - 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 - client.insert_product_input(request) - - -@pytest.mark.parametrize("request_type", [ - productinputs.InsertProductInputRequest, - dict, -]) -def test_insert_product_input_rest_call_success(request_type): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["product_input"] = {'name': 'name_value', 'product': 'product_value', 'channel': 1, 'offer_id': 'offer_id_value', 'content_language': 'content_language_value', 'feed_label': 'feed_label_value', 'version_number': 1518, 'attributes': {'identifier_exists': True, 'is_bundle': True, 'title': 'title_value', 'description': 'description_value', 'link': 'link_value', 'mobile_link': 'mobile_link_value', 'canonical_link': 'canonical_link_value', 'image_link': 'image_link_value', 'additional_image_links': ['additional_image_links_value1', 'additional_image_links_value2'], 'expiration_date': {'seconds': 751, 'nanos': 543}, 'disclosure_date': {}, 'adult': True, 'age_group': 'age_group_value', 'availability': 'availability_value', 'availability_date': {}, 'brand': 'brand_value', 'color': 'color_value', 'condition': 'condition_value', 'gender': 'gender_value', 'google_product_category': 'google_product_category_value', 'gtin': 'gtin_value', 'item_group_id': 'item_group_id_value', 'material': 'material_value', 'mpn': 'mpn_value', 'pattern': 'pattern_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'installment': {'months': 665, 'amount': {}, 'downpayment': {}, 'credit_type': 'credit_type_value'}, 'subscription_cost': {'period': 1, 'period_length': 1380, 'amount': {}}, 'loyalty_points': {'name': 'name_value', 'points_value': 1305, 'ratio': 0.543}, 'loyalty_programs': [{'program_label': 'program_label_value', 'tier_label': 'tier_label_value', 'price': {}, 'cashback_for_future_use': {}, 'loyalty_points': 1546}], 'product_types': ['product_types_value1', 'product_types_value2'], 'sale_price': {}, 'sale_price_effective_date': {'start_time': {}, 'end_time': {}}, 'sell_on_google_quantity': 2470, 'product_height': {'value': 0.541, 'unit': 'unit_value'}, 'product_length': {}, 'product_width': {}, 'product_weight': {'value': 0.541, 'unit': 'unit_value'}, 'shipping': [{'price': {}, 'country': 'country_value', 'region': 'region_value', 'service': 'service_value', 'location_id': 1157, 'location_group_name': 'location_group_name_value', 'postal_code': 'postal_code_value', 'min_handling_time': 1782, 'max_handling_time': 1784, 'min_transit_time': 1718, 'max_transit_time': 1720}], 'free_shipping_threshold': [{'country': 'country_value', 'price_threshold': {}}], 'shipping_weight': {'value': 0.541, 'unit': 'unit_value'}, 'shipping_length': {'value': 0.541, 'unit': 'unit_value'}, 'shipping_width': {}, 'shipping_height': {}, 'max_handling_time': 1784, 'min_handling_time': 1782, 'shipping_label': 'shipping_label_value', 'transit_time_label': 'transit_time_label_value', 'size': 'size_value', 'size_system': 'size_system_value', 'size_types': ['size_types_value1', 'size_types_value2'], 'taxes': [{'rate': 0.428, 'country': 'country_value', 'region': 'region_value', 'tax_ship': True, 'location_id': 1157, 'postal_code': 'postal_code_value'}], 'tax_category': 'tax_category_value', 'energy_efficiency_class': 'energy_efficiency_class_value', 'min_energy_efficiency_class': 'min_energy_efficiency_class_value', 'max_energy_efficiency_class': 'max_energy_efficiency_class_value', 'unit_pricing_measure': {'value': 0.541, 'unit': 'unit_value'}, 'unit_pricing_base_measure': {'value': 541, 'unit': 'unit_value'}, 'multipack': 970, 'ads_grouping': 'ads_grouping_value', 'ads_labels': ['ads_labels_value1', 'ads_labels_value2'], 'ads_redirect': 'ads_redirect_value', 'cost_of_goods_sold': {}, 'product_details': [{'section_name': 'section_name_value', 'attribute_name': 'attribute_name_value', 'attribute_value': 'attribute_value_value'}], 'product_highlights': ['product_highlights_value1', 'product_highlights_value2'], 'display_ads_id': 'display_ads_id_value', 'display_ads_similar_ids': ['display_ads_similar_ids_value1', 'display_ads_similar_ids_value2'], 'display_ads_title': 'display_ads_title_value', 'display_ads_link': 'display_ads_link_value', 'display_ads_value': 0.1801, 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2'], 'pickup_method': 'pickup_method_value', 'pickup_sla': 'pickup_sla_value', 'link_template': 'link_template_value', 'mobile_link_template': 'mobile_link_template_value', 'custom_label_0': 'custom_label_0_value', 'custom_label_1': 'custom_label_1_value', 'custom_label_2': 'custom_label_2_value', 'custom_label_3': 'custom_label_3_value', 'custom_label_4': 'custom_label_4_value', 'included_destinations': ['included_destinations_value1', 'included_destinations_value2'], 'excluded_destinations': ['excluded_destinations_value1', 'excluded_destinations_value2'], 'shopping_ads_excluded_countries': ['shopping_ads_excluded_countries_value1', 'shopping_ads_excluded_countries_value2'], 'external_seller_id': 'external_seller_id_value', 'pause': 'pause_value', 'lifestyle_image_links': ['lifestyle_image_links_value1', 'lifestyle_image_links_value2'], 'cloud_export_additional_properties': [{'property_name': 'property_name_value', 'text_value': ['text_value_value1', 'text_value_value2'], 'bool_value': True, 'int_value': [968, 969], 'float_value': [0.11710000000000001, 0.11720000000000001], 'min_value': 0.96, 'max_value': 0.962, 'unit_code': 'unit_code_value'}], 'virtual_model_link': 'virtual_model_link_value', 'certifications': [{'certification_authority': 'certification_authority_value', 'certification_name': 'certification_name_value', 'certification_code': 'certification_code_value', 'certification_value': 'certification_value_value'}], 'structured_title': {'digital_source_type': 'digital_source_type_value', 'content': 'content_value'}, 'structured_description': {'digital_source_type': 'digital_source_type_value', 'content': 'content_value'}, 'auto_pricing_min_price': {}}, '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 = productinputs.InsertProductInputRequest.meta.fields["product_input"] - - 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["product_input"].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["product_input"][field])): - del request_init["product_input"][field][i][subfield] - else: - del request_init["product_input"][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 = productinputs.ProductInput( - name='name_value', - product='product_value', - channel=types.Channel.ChannelEnum.ONLINE, - offer_id='offer_id_value', - content_language='content_language_value', - feed_label='feed_label_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 = productinputs.ProductInput.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.insert_product_input(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, productinputs.ProductInput) - assert response.name == 'name_value' - assert response.product == 'product_value' - assert response.channel == types.Channel.ChannelEnum.ONLINE - assert response.offer_id == 'offer_id_value' - assert response.content_language == 'content_language_value' - assert response.feed_label == 'feed_label_value' - assert response.version_number == 1518 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_product_input_rest_interceptors(null_interceptor): - transport = transports.ProductInputsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProductInputsServiceRestInterceptor(), - ) - client = ProductInputsServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProductInputsServiceRestInterceptor, "post_insert_product_input") as post, \ - mock.patch.object(transports.ProductInputsServiceRestInterceptor, "pre_insert_product_input") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = productinputs.InsertProductInputRequest.pb(productinputs.InsertProductInputRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = productinputs.ProductInput.to_json(productinputs.ProductInput()) - req.return_value.content = return_value - - request = productinputs.InsertProductInputRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = productinputs.ProductInput() - - client.insert_product_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_product_input_rest_bad_request(request_type=productinputs.DeleteProductInputRequest): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/productInputs/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 - client.delete_product_input(request) - - -@pytest.mark.parametrize("request_type", [ - productinputs.DeleteProductInputRequest, - dict, -]) -def test_delete_product_input_rest_call_success(request_type): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/productInputs/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 - response = client.delete_product_input(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_product_input_rest_interceptors(null_interceptor): - transport = transports.ProductInputsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProductInputsServiceRestInterceptor(), - ) - client = ProductInputsServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProductInputsServiceRestInterceptor, "pre_delete_product_input") as pre: - pre.assert_not_called() - pb_message = productinputs.DeleteProductInputRequest.pb(productinputs.DeleteProductInputRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - - request = productinputs.DeleteProductInputRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_product_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = ProductInputsServiceClient( - 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_product_input_empty_call_rest(): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_product_input), - '__call__') as call: - client.insert_product_input(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = productinputs.InsertProductInputRequest() - - assert args[0] == request_msg - - -# This 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_product_input_empty_call_rest(): - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_product_input), - '__call__') as call: - client.delete_product_input(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = productinputs.DeleteProductInputRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductInputsServiceGrpcTransport, - ) - -def test_product_inputs_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductInputsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_product_inputs_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_products_v1beta.services.product_inputs_service.transports.ProductInputsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductInputsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'insert_product_input', - 'delete_product_input', - ) - 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_product_inputs_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_products_v1beta.services.product_inputs_service.transports.ProductInputsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductInputsServiceTransport( - 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_product_inputs_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_products_v1beta.services.product_inputs_service.transports.ProductInputsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductInputsServiceTransport() - adc.assert_called_once() - - -def test_product_inputs_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) - ProductInputsServiceClient() - 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.ProductInputsServiceGrpcTransport, - transports.ProductInputsServiceGrpcAsyncIOTransport, - ], -) -def test_product_inputs_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.ProductInputsServiceGrpcTransport, - transports.ProductInputsServiceGrpcAsyncIOTransport, - transports.ProductInputsServiceRestTransport, - ], -) -def test_product_inputs_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.ProductInputsServiceGrpcTransport, grpc_helpers), - (transports.ProductInputsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_product_inputs_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.ProductInputsServiceGrpcTransport, transports.ProductInputsServiceGrpcAsyncIOTransport]) -def test_product_inputs_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_product_inputs_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.ProductInputsServiceRestTransport ( - 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_product_inputs_service_host_no_port(transport_name): - client = ProductInputsServiceClient( - 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_product_inputs_service_host_with_port(transport_name): - client = ProductInputsServiceClient( - 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_product_inputs_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ProductInputsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ProductInputsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.insert_product_input._session - session2 = client2.transport.insert_product_input._session - assert session1 != session2 - session1 = client1.transport.delete_product_input._session - session2 = client2.transport.delete_product_input._session - assert session1 != session2 -def test_product_inputs_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductInputsServiceGrpcTransport( - 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_product_inputs_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductInputsServiceGrpcAsyncIOTransport( - 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.ProductInputsServiceGrpcTransport, transports.ProductInputsServiceGrpcAsyncIOTransport]) -def test_product_inputs_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.ProductInputsServiceGrpcTransport, transports.ProductInputsServiceGrpcAsyncIOTransport]) -def test_product_inputs_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_product_path(): - account = "squid" - product = "clam" - expected = "accounts/{account}/products/{product}".format(account=account, product=product, ) - actual = ProductInputsServiceClient.product_path(account, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "account": "whelk", - "product": "octopus", - } - path = ProductInputsServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductInputsServiceClient.parse_product_path(path) - assert expected == actual - -def test_product_input_path(): - account = "oyster" - productinput = "nudibranch" - expected = "accounts/{account}/productInputs/{productinput}".format(account=account, productinput=productinput, ) - actual = ProductInputsServiceClient.product_input_path(account, productinput) - assert expected == actual - - -def test_parse_product_input_path(): - expected = { - "account": "cuttlefish", - "productinput": "mussel", - } - path = ProductInputsServiceClient.product_input_path(**expected) - - # Check that the path construction is reversible. - actual = ProductInputsServiceClient.parse_product_input_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductInputsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = ProductInputsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductInputsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductInputsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = ProductInputsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductInputsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductInputsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = ProductInputsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductInputsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = ProductInputsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = ProductInputsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductInputsServiceClient.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 = ProductInputsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = ProductInputsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductInputsServiceClient.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.ProductInputsServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductInputsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductInputsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductInputsServiceClient.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 = ProductInputsServiceClient( - 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 = ProductInputsServiceAsyncClient( - 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 = ProductInputsServiceClient( - 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 = ProductInputsServiceClient( - 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", [ - (ProductInputsServiceClient, transports.ProductInputsServiceGrpcTransport), - (ProductInputsServiceAsyncClient, transports.ProductInputsServiceGrpcAsyncIOTransport), -]) -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-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_products_service.py b/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_products_service.py deleted file mode 100644 index 1a5ebb547cb6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-products/v1beta/tests/unit/gapic/merchant_products_v1beta/test_products_service.py +++ /dev/null @@ -1,3096 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_products_v1beta.services.products_service import ProductsServiceAsyncClient -from google.shopping.merchant_products_v1beta.services.products_service import ProductsServiceClient -from google.shopping.merchant_products_v1beta.services.products_service import pagers -from google.shopping.merchant_products_v1beta.services.products_service import transports -from google.shopping.merchant_products_v1beta.types import products -from google.shopping.merchant_products_v1beta.types import products_common -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 ProductsServiceClient._get_default_mtls_endpoint(None) is None - assert ProductsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProductsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProductsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProductsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProductsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ProductsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ProductsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ProductsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ProductsServiceClient._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 ProductsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ProductsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ProductsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ProductsServiceClient._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 ProductsServiceClient._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 ProductsServiceClient._get_client_cert_source(None, False) is None - assert ProductsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ProductsServiceClient._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 ProductsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ProductsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ProductsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceClient)) -@mock.patch.object(ProductsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ProductsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ProductsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ProductsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ProductsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ProductsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProductsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProductsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ProductsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ProductsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProductsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProductsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProductsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ProductsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ProductsServiceClient._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 ProductsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ProductsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ProductsServiceClient._get_universe_domain(None, None) == ProductsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ProductsServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc"), - (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProductsServiceClient, "grpc"), - (ProductsServiceAsyncClient, "grpc_asyncio"), - (ProductsServiceClient, "rest"), -]) -def test_products_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.ProductsServiceGrpcTransport, "grpc"), - (transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ProductsServiceRestTransport, "rest"), -]) -def test_products_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", [ - (ProductsServiceClient, "grpc"), - (ProductsServiceAsyncClient, "grpc_asyncio"), - (ProductsServiceClient, "rest"), -]) -def test_products_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_products_service_client_get_transport_class(): - transport = ProductsServiceClient.get_transport_class() - available_transports = [ - transports.ProductsServiceGrpcTransport, - transports.ProductsServiceRestTransport, - ] - assert transport in available_transports - - transport = ProductsServiceClient.get_transport_class("grpc") - assert transport == transports.ProductsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc"), - (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest"), -]) -@mock.patch.object(ProductsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceClient)) -@mock.patch.object(ProductsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceAsyncClient)) -def test_products_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(ProductsServiceClient, '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(ProductsServiceClient, '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", [ - (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc", "true"), - (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc", "false"), - (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest", "true"), - (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ProductsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceClient)) -@mock.patch.object(ProductsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_products_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", [ - ProductsServiceClient, ProductsServiceAsyncClient -]) -@mock.patch.object(ProductsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductsServiceClient)) -@mock.patch.object(ProductsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductsServiceAsyncClient)) -def test_products_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", [ - ProductsServiceClient, ProductsServiceAsyncClient -]) -@mock.patch.object(ProductsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceClient)) -@mock.patch.object(ProductsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductsServiceAsyncClient)) -def test_products_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ProductsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ProductsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ProductsServiceClient._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", [ - (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc"), - (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest"), -]) -def test_products_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", [ - (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc", grpc_helpers), - (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ProductsServiceClient, transports.ProductsServiceRestTransport, "rest", None), -]) -def test_products_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_products_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_products_v1beta.services.products_service.transports.ProductsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProductsServiceClient( - 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", [ - (ProductsServiceClient, transports.ProductsServiceGrpcTransport, "grpc", grpc_helpers), - (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_products_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", [ - products.GetProductRequest, - dict, -]) -def test_get_product(request_type, transport: str = 'grpc'): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = products.Product( - name='name_value', - channel=types.Channel.ChannelEnum.ONLINE, - offer_id='offer_id_value', - content_language='content_language_value', - feed_label='feed_label_value', - data_source='data_source_value', - version_number=1518, - ) - response = client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = products.GetProductRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, products.Product) - assert response.name == 'name_value' - assert response.channel == types.Channel.ChannelEnum.ONLINE - assert response.offer_id == 'offer_id_value' - assert response.content_language == 'content_language_value' - assert response.feed_label == 'feed_label_value' - assert response.data_source == 'data_source_value' - assert response.version_number == 1518 - - -def test_get_product_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = products.GetProductRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_product(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == products.GetProductRequest( - name='name_value', - ) - -def test_get_product_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_product in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_product] = mock_rpc - request = {} - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_product(request) - - # Establish that a new wrapper 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_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_product in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_product] = mock_rpc - - request = {} - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_product(request) - - # Establish that a new wrapper 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_product_async(transport: str = 'grpc_asyncio', request_type=products.GetProductRequest): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(products.Product( - name='name_value', - channel=types.Channel.ChannelEnum.ONLINE, - offer_id='offer_id_value', - content_language='content_language_value', - feed_label='feed_label_value', - data_source='data_source_value', - version_number=1518, - )) - response = await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = products.GetProductRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, products.Product) - assert response.name == 'name_value' - assert response.channel == types.Channel.ChannelEnum.ONLINE - assert response.offer_id == 'offer_id_value' - assert response.content_language == 'content_language_value' - assert response.feed_label == 'feed_label_value' - assert response.data_source == 'data_source_value' - assert response.version_number == 1518 - - -@pytest.mark.asyncio -async def test_get_product_async_from_dict(): - await test_get_product_async(request_type=dict) - -def test_get_product_field_headers(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = products.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = products.Product() - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_field_headers_async(): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = products.GetProductRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.Product()) - await client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_product_flattened(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = products.Product() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_product( - name='name_value', - ) - - # Establish that the 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_product_flattened_error(): - client = ProductsServiceClient( - credentials=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_product( - products.GetProductRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_product_flattened_async(): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = products.Product() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.Product()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_product( - name='name_value', - ) - - # Establish that 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_product_flattened_error_async(): - client = ProductsServiceAsyncClient( - credentials=async_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_product( - products.GetProductRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - products.ListProductsRequest, - dict, -]) -def test_list_products(request_type, transport: str = 'grpc'): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = products.ListProductsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = products.ListProductsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_products_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = products.ListProductsRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_products(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == products.ListProductsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_products_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_products in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_products] = mock_rpc - request = {} - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_products(request) - - # Establish that a new wrapper 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_products_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap 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_products in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_products] = mock_rpc - - request = {} - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_products(request) - - # Establish that a new wrapper 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_products_async(transport: str = 'grpc_asyncio', request_type=products.ListProductsRequest): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(products.ListProductsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = products.ListProductsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_products_async_from_dict(): - await test_list_products_async(request_type=dict) - -def test_list_products_field_headers(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = products.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = products.ListProductsResponse() - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_field_headers_async(): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = products.ListProductsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.ListProductsResponse()) - await client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_products_flattened(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = products.ListProductsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_products( - parent='parent_value', - ) - - # Establish that the 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_products_flattened_error(): - client = ProductsServiceClient( - credentials=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_products( - products.ListProductsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_products_flattened_async(): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = products.ListProductsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.ListProductsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_products( - parent='parent_value', - ) - - # Establish that 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_products_flattened_error_async(): - client = ProductsServiceAsyncClient( - credentials=async_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_products( - products.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_pager(transport_name: str = "grpc"): - client = ProductsServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - products.Product(), - ], - next_page_token='abc', - ), - products.ListProductsResponse( - products=[], - next_page_token='def', - ), - products.ListProductsResponse( - products=[ - products.Product(), - ], - next_page_token='ghi', - ), - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_products(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, products.Product) - for i in results) -def test_list_products_pages(transport_name: str = "grpc"): - client = ProductsServiceClient( - 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_products), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - products.Product(), - ], - next_page_token='abc', - ), - products.ListProductsResponse( - products=[], - next_page_token='def', - ), - products.ListProductsResponse( - products=[ - products.Product(), - ], - next_page_token='ghi', - ), - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - ], - ), - RuntimeError, - ) - pages = list(client.list_products(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_products_async_pager(): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - products.Product(), - ], - next_page_token='abc', - ), - products.ListProductsResponse( - products=[], - next_page_token='def', - ), - products.ListProductsResponse( - products=[ - products.Product(), - ], - next_page_token='ghi', - ), - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_products(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, products.Product) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_products_async_pages(): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - products.Product(), - ], - next_page_token='abc', - ), - products.ListProductsResponse( - products=[], - next_page_token='def', - ), - products.ListProductsResponse( - products=[ - products.Product(), - ], - next_page_token='ghi', - ), - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - ], - ), - 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_products(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_product_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_product in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_product] = mock_rpc - - request = {} - client.get_product(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_product(request) - - # Establish 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_product_rest_required_fields(request_type=products.GetProductRequest): - transport_class = transports.ProductsServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product._get_unset_required_fields(jsonified_request) - 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_product._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = products.Product() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = products.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_product(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_product_rest_unset_required_fields(): - transport = transports.ProductsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_product_rest_flattened(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = products.Product() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/products/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 = products.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_product(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/products/v1beta/{name=accounts/*/products/*}" % client.transport._host, args[1]) - - -def test_get_product_rest_flattened_error(transport: str = 'rest'): - client = ProductsServiceClient( - credentials=ga_credentials.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_product( - products.GetProductRequest(), - name='name_value', - ) - - -def test_list_products_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_products in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_products] = mock_rpc - - request = {} - client.list_products(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_products(request) - - # Establish 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_products_rest_required_fields(request_type=products.ListProductsRequest): - transport_class = transports.ProductsServiceRestTransport - - 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_products._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - 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 = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = products.ListProductsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = products.ListProductsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_products(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_products_rest_unset_required_fields(): - transport = transports.ProductsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_products._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_products_rest_flattened(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = products.ListProductsResponse() - - # 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 = products.ListProductsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_products(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/products/v1beta/{parent=accounts/*}/products" % client.transport._host, args[1]) - - -def test_list_products_rest_flattened_error(transport: str = 'rest'): - client = ProductsServiceClient( - credentials=ga_credentials.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_products( - products.ListProductsRequest(), - parent='parent_value', - ) - - -def test_list_products_rest_pager(transport: str = 'rest'): - client = ProductsServiceClient( - 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 = ( - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - products.Product(), - ], - next_page_token='abc', - ), - products.ListProductsResponse( - products=[], - next_page_token='def', - ), - products.ListProductsResponse( - products=[ - products.Product(), - ], - next_page_token='ghi', - ), - products.ListProductsResponse( - products=[ - products.Product(), - products.Product(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(products.ListProductsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'accounts/sample1'} - - pager = client.list_products(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, products.Product) - for i in results) - - pages = list(client.list_products(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.ProductsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductsServiceClient( - 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 = ProductsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProductsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProductsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProductsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProductsServiceGrpcTransport, - transports.ProductsServiceGrpcAsyncIOTransport, - transports.ProductsServiceRestTransport, -]) -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 = ProductsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ProductsServiceClient( - 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_product_empty_call_grpc(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - call.return_value = products.Product() - client.get_product(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = products.GetProductRequest() - - assert args[0] == request_msg - - -# This 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_products_empty_call_grpc(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - call.return_value = products.ListProductsResponse() - client.list_products(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = products.ListProductsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ProductsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ProductsServiceAsyncClient( - 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_product_empty_call_grpc_asyncio(): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.Product( - name='name_value', - channel=types.Channel.ChannelEnum.ONLINE, - offer_id='offer_id_value', - content_language='content_language_value', - feed_label='feed_label_value', - data_source='data_source_value', - version_number=1518, - )) - await client.get_product(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = products.GetProductRequest() - - assert args[0] == request_msg - - -# This test is a coverage 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_products_empty_call_grpc_asyncio(): - client = ProductsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(products.ListProductsResponse( - next_page_token='next_page_token_value', - )) - await client.list_products(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = products.ListProductsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ProductsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_product_rest_bad_request(request_type=products.GetProductRequest): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': '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 - client.get_product(request) - - -@pytest.mark.parametrize("request_type", [ - products.GetProductRequest, - dict, -]) -def test_get_product_rest_call_success(request_type): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': '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 = products.Product( - name='name_value', - channel=types.Channel.ChannelEnum.ONLINE, - offer_id='offer_id_value', - content_language='content_language_value', - feed_label='feed_label_value', - 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 = products.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_product(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, products.Product) - assert response.name == 'name_value' - assert response.channel == types.Channel.ChannelEnum.ONLINE - assert response.offer_id == 'offer_id_value' - assert response.content_language == 'content_language_value' - assert response.feed_label == 'feed_label_value' - assert response.data_source == 'data_source_value' - assert response.version_number == 1518 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_product_rest_interceptors(null_interceptor): - transport = transports.ProductsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProductsServiceRestInterceptor(), - ) - client = ProductsServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProductsServiceRestInterceptor, "post_get_product") as post, \ - mock.patch.object(transports.ProductsServiceRestInterceptor, "pre_get_product") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = products.GetProductRequest.pb(products.GetProductRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = products.Product.to_json(products.Product()) - req.return_value.content = return_value - - request = products.GetProductRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = products.Product() - - client.get_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_products_rest_bad_request(request_type=products.ListProductsRequest): - client = ProductsServiceClient( - 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 - client.list_products(request) - - -@pytest.mark.parametrize("request_type", [ - products.ListProductsRequest, - dict, -]) -def test_list_products_rest_call_success(request_type): - client = ProductsServiceClient( - 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 = products.ListProductsResponse( - 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 = products.ListProductsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_products(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_products_rest_interceptors(null_interceptor): - transport = transports.ProductsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProductsServiceRestInterceptor(), - ) - client = ProductsServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProductsServiceRestInterceptor, "post_list_products") as post, \ - mock.patch.object(transports.ProductsServiceRestInterceptor, "pre_list_products") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = products.ListProductsRequest.pb(products.ListProductsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = products.ListProductsResponse.to_json(products.ListProductsResponse()) - req.return_value.content = return_value - - request = products.ListProductsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = products.ListProductsResponse() - - client.list_products(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = ProductsServiceClient( - 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_product_empty_call_rest(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_product), - '__call__') as call: - client.get_product(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = products.GetProductRequest() - - assert args[0] == request_msg - - -# This 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_products_empty_call_rest(): - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_products), - '__call__') as call: - client.list_products(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = products.ListProductsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProductsServiceGrpcTransport, - ) - -def test_products_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProductsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_products_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_products_v1beta.services.products_service.transports.ProductsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProductsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_product', - 'list_products', - ) - 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_products_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_products_v1beta.services.products_service.transports.ProductsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductsServiceTransport( - 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_products_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_products_v1beta.services.products_service.transports.ProductsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProductsServiceTransport() - adc.assert_called_once() - - -def test_products_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) - ProductsServiceClient() - 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.ProductsServiceGrpcTransport, - transports.ProductsServiceGrpcAsyncIOTransport, - ], -) -def test_products_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.ProductsServiceGrpcTransport, - transports.ProductsServiceGrpcAsyncIOTransport, - transports.ProductsServiceRestTransport, - ], -) -def test_products_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.ProductsServiceGrpcTransport, grpc_helpers), - (transports.ProductsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_products_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.ProductsServiceGrpcTransport, transports.ProductsServiceGrpcAsyncIOTransport]) -def test_products_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_products_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.ProductsServiceRestTransport ( - 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_products_service_host_no_port(transport_name): - client = ProductsServiceClient( - 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_products_service_host_with_port(transport_name): - client = ProductsServiceClient( - 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_products_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ProductsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ProductsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_product._session - session2 = client2.transport.get_product._session - assert session1 != session2 - session1 = client1.transport.list_products._session - session2 = client2.transport.list_products._session - assert session1 != session2 -def test_products_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductsServiceGrpcTransport( - 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_products_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProductsServiceGrpcAsyncIOTransport( - 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.ProductsServiceGrpcTransport, transports.ProductsServiceGrpcAsyncIOTransport]) -def test_products_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.ProductsServiceGrpcTransport, transports.ProductsServiceGrpcAsyncIOTransport]) -def test_products_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_product_path(): - account = "squid" - product = "clam" - expected = "accounts/{account}/products/{product}".format(account=account, product=product, ) - actual = ProductsServiceClient.product_path(account, product) - assert expected == actual - - -def test_parse_product_path(): - expected = { - "account": "whelk", - "product": "octopus", - } - path = ProductsServiceClient.product_path(**expected) - - # Check that the path construction is reversible. - actual = ProductsServiceClient.parse_product_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProductsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = ProductsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProductsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProductsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = ProductsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProductsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProductsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = ProductsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProductsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = ProductsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = ProductsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProductsServiceClient.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 = ProductsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = ProductsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProductsServiceClient.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.ProductsServiceTransport, '_prep_wrapped_messages') as prep: - client = ProductsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProductsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProductsServiceClient.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 = ProductsServiceClient( - 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 = ProductsServiceAsyncClient( - 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 = ProductsServiceClient( - 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 = ProductsServiceClient( - 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", [ - (ProductsServiceClient, transports.ProductsServiceGrpcTransport), - (ProductsServiceAsyncClient, transports.ProductsServiceGrpcAsyncIOTransport), -]) -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-cloud-websecurityscanner/.flake8 b/packages/google-cloud-websecurityscanner/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-cloud-websecurityscanner/.flake8 +++ b/packages/google-cloud-websecurityscanner/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-websecurityscanner/CONTRIBUTING.rst b/packages/google-cloud-websecurityscanner/CONTRIBUTING.rst index 1ad415409657..87f0949b3143 100644 --- a/packages/google-cloud-websecurityscanner/CONTRIBUTING.rst +++ b/packages/google-cloud-websecurityscanner/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-cloud-websecurityscanner/MANIFEST.in b/packages/google-cloud-websecurityscanner/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-cloud-websecurityscanner/MANIFEST.in +++ b/packages/google-cloud-websecurityscanner/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-websecurityscanner/docs/conf.py b/packages/google-cloud-websecurityscanner/docs/conf.py index 1b3c95afd562..e9ec027bfedf 100644 --- a/packages/google-cloud-websecurityscanner/docs/conf.py +++ b/packages/google-cloud-websecurityscanner/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py index ce8df608b902..e391218e0948 100644 --- a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py +++ b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py @@ -47,7 +47,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py index 6237c1dceafc..a3f21e7077c7 100644 --- a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py +++ b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py @@ -45,7 +45,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py index 15c9c7df662f..dd1012c8d09f 100644 --- a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py +++ b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py @@ -45,7 +45,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-cloud-websecurityscanner/noxfile.py b/packages/google-cloud-websecurityscanner/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-cloud-websecurityscanner/noxfile.py +++ b/packages/google-cloud-websecurityscanner/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-cloud-websecurityscanner/scripts/decrypt-secrets.sh b/packages/google-cloud-websecurityscanner/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-cloud-websecurityscanner/scripts/decrypt-secrets.sh +++ b/packages/google-cloud-websecurityscanner/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-websecurityscanner/setup.py b/packages/google-cloud-websecurityscanner/setup.py index 1088967ecc8b..8532449fd2d2 100644 --- a/packages/google-cloud-websecurityscanner/setup.py +++ b/packages/google-cloud-websecurityscanner/setup.py @@ -46,6 +46,7 @@ # 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 = {} @@ -84,6 +85,7 @@ "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", ], diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.13.txt b/packages/google-cloud-websecurityscanner/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-cloud-websecurityscanner/v1/testing/constraints-3.13.txt rename to packages/google-cloud-websecurityscanner/testing/constraints-3.13.txt diff --git a/packages/google-cloud-workflows/.flake8 b/packages/google-cloud-workflows/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-cloud-workflows/.flake8 +++ b/packages/google-cloud-workflows/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workflows/CONTRIBUTING.rst b/packages/google-cloud-workflows/CONTRIBUTING.rst index 046ef04f44f4..8f6fefa1849c 100644 --- a/packages/google-cloud-workflows/CONTRIBUTING.rst +++ b/packages/google-cloud-workflows/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-cloud-workflows/MANIFEST.in b/packages/google-cloud-workflows/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-cloud-workflows/MANIFEST.in +++ b/packages/google-cloud-workflows/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workflows/docs/conf.py b/packages/google-cloud-workflows/docs/conf.py index ce3e034786a3..40840d869249 100644 --- a/packages/google-cloud-workflows/docs/conf.py +++ b/packages/google-cloud-workflows/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workflows/google/cloud/workflows_v1/services/workflows/transports/rest.py b/packages/google-cloud-workflows/google/cloud/workflows_v1/services/workflows/transports/rest.py index efa4088dcca6..2df29537d5b2 100644 --- a/packages/google-cloud-workflows/google/cloud/workflows_v1/services/workflows/transports/rest.py +++ b/packages/google-cloud-workflows/google/cloud/workflows_v1/services/workflows/transports/rest.py @@ -43,7 +43,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-cloud-workflows/google/cloud/workflows_v1beta/services/workflows/transports/rest.py b/packages/google-cloud-workflows/google/cloud/workflows_v1beta/services/workflows/transports/rest.py index 406abacf7e32..fa45293023b2 100644 --- a/packages/google-cloud-workflows/google/cloud/workflows_v1beta/services/workflows/transports/rest.py +++ b/packages/google-cloud-workflows/google/cloud/workflows_v1beta/services/workflows/transports/rest.py @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-cloud-workflows/noxfile.py b/packages/google-cloud-workflows/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-cloud-workflows/noxfile.py +++ b/packages/google-cloud-workflows/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-cloud-workflows/scripts/decrypt-secrets.sh b/packages/google-cloud-workflows/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-cloud-workflows/scripts/decrypt-secrets.sh +++ b/packages/google-cloud-workflows/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workflows/setup.py b/packages/google-cloud-workflows/setup.py index ff67c40e6350..b51d7c2b3cc3 100644 --- a/packages/google-cloud-workflows/setup.py +++ b/packages/google-cloud-workflows/setup.py @@ -44,6 +44,7 @@ # 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 = {} @@ -82,6 +83,7 @@ "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", ], diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.13.txt b/packages/google-cloud-workflows/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-cloud-websecurityscanner/v1alpha/testing/constraints-3.13.txt rename to packages/google-cloud-workflows/testing/constraints-3.13.txt diff --git a/packages/google-cloud-workstations/.flake8 b/packages/google-cloud-workstations/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-cloud-workstations/.flake8 +++ b/packages/google-cloud-workstations/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workstations/CONTRIBUTING.rst b/packages/google-cloud-workstations/CONTRIBUTING.rst index 274276f0349b..aa17c4eeebed 100644 --- a/packages/google-cloud-workstations/CONTRIBUTING.rst +++ b/packages/google-cloud-workstations/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-cloud-workstations/MANIFEST.in b/packages/google-cloud-workstations/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-cloud-workstations/MANIFEST.in +++ b/packages/google-cloud-workstations/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workstations/docs/conf.py b/packages/google-cloud-workstations/docs/conf.py index 919d2e7028f8..666d0305f9e6 100644 --- a/packages/google-cloud-workstations/docs/conf.py +++ b/packages/google-cloud-workstations/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workstations/google/cloud/workstations_v1/services/workstations/transports/rest.py b/packages/google-cloud-workstations/google/cloud/workstations_v1/services/workstations/transports/rest.py index 916331250cae..e14a7d180d16 100644 --- a/packages/google-cloud-workstations/google/cloud/workstations_v1/services/workstations/transports/rest.py +++ b/packages/google-cloud-workstations/google/cloud/workstations_v1/services/workstations/transports/rest.py @@ -45,7 +45,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-cloud-workstations/google/cloud/workstations_v1beta/services/workstations/transports/rest.py b/packages/google-cloud-workstations/google/cloud/workstations_v1beta/services/workstations/transports/rest.py index 6e34b9481d61..7403b20868c9 100644 --- a/packages/google-cloud-workstations/google/cloud/workstations_v1beta/services/workstations/transports/rest.py +++ b/packages/google-cloud-workstations/google/cloud/workstations_v1beta/services/workstations/transports/rest.py @@ -45,7 +45,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-cloud-workstations/noxfile.py b/packages/google-cloud-workstations/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-cloud-workstations/noxfile.py +++ b/packages/google-cloud-workstations/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-cloud-workstations/scripts/decrypt-secrets.sh b/packages/google-cloud-workstations/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-cloud-workstations/scripts/decrypt-secrets.sh +++ b/packages/google-cloud-workstations/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workstations/setup.py b/packages/google-cloud-workstations/setup.py index e55fce16fbed..329686704260 100644 --- a/packages/google-cloud-workstations/setup.py +++ b/packages/google-cloud-workstations/setup.py @@ -46,6 +46,7 @@ # 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", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] @@ -85,6 +86,7 @@ "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", ], diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.13.txt b/packages/google-cloud-workstations/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.13.txt rename to packages/google-cloud-workstations/testing/constraints-3.13.txt diff --git a/packages/google-geo-type/.flake8 b/packages/google-geo-type/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-geo-type/.flake8 +++ b/packages/google-geo-type/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-geo-type/CONTRIBUTING.rst b/packages/google-geo-type/CONTRIBUTING.rst index 644229198628..b2ca014578bc 100644 --- a/packages/google-geo-type/CONTRIBUTING.rst +++ b/packages/google-geo-type/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-geo-type/MANIFEST.in b/packages/google-geo-type/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-geo-type/MANIFEST.in +++ b/packages/google-geo-type/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-geo-type/docs/conf.py b/packages/google-geo-type/docs/conf.py index 0020fbf56042..7f03cfeb63cb 100644 --- a/packages/google-geo-type/docs/conf.py +++ b/packages/google-geo-type/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-geo-type/docs/index.rst b/packages/google-geo-type/docs/index.rst index 278971d39e0e..527b02224c0e 100644 --- a/packages/google-geo-type/docs/index.rst +++ b/packages/google-geo-type/docs/index.rst @@ -7,6 +7,7 @@ API Reference .. toctree:: :maxdepth: 2 + type/services_ type/types_ diff --git a/packages/google-geo-type/noxfile.py b/packages/google-geo-type/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-geo-type/noxfile.py +++ b/packages/google-geo-type/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-geo-type/scripts/decrypt-secrets.sh b/packages/google-geo-type/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-geo-type/scripts/decrypt-secrets.sh +++ b/packages/google-geo-type/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-geo-type/setup.py b/packages/google-geo-type/setup.py index 3488b5fd8e4d..aa386670ef74 100644 --- a/packages/google-geo-type/setup.py +++ b/packages/google-geo-type/setup.py @@ -44,6 +44,7 @@ # 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 = {} @@ -82,6 +83,7 @@ "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", ], diff --git a/owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.13.txt b/packages/google-geo-type/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-cloud-websecurityscanner/v1beta/testing/constraints-3.13.txt rename to packages/google-geo-type/testing/constraints-3.13.txt diff --git a/packages/google-maps-addressvalidation/.flake8 b/packages/google-maps-addressvalidation/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-maps-addressvalidation/.flake8 +++ b/packages/google-maps-addressvalidation/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-addressvalidation/CONTRIBUTING.rst b/packages/google-maps-addressvalidation/CONTRIBUTING.rst index ce0ae60f2ec0..39ad9d53144e 100644 --- a/packages/google-maps-addressvalidation/CONTRIBUTING.rst +++ b/packages/google-maps-addressvalidation/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-maps-addressvalidation/MANIFEST.in b/packages/google-maps-addressvalidation/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-maps-addressvalidation/MANIFEST.in +++ b/packages/google-maps-addressvalidation/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-addressvalidation/docs/conf.py b/packages/google-maps-addressvalidation/docs/conf.py index 58bb16e08146..d9fff8311410 100644 --- a/packages/google-maps-addressvalidation/docs/conf.py +++ b/packages/google-maps-addressvalidation/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-addressvalidation/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py b/packages/google-maps-addressvalidation/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py index 093b346bd6af..1e3dec085175 100644 --- a/packages/google-maps-addressvalidation/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py +++ b/packages/google-maps-addressvalidation/google/maps/addressvalidation_v1/services/address_validation/transports/rest.py @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-maps-addressvalidation/noxfile.py b/packages/google-maps-addressvalidation/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-maps-addressvalidation/noxfile.py +++ b/packages/google-maps-addressvalidation/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-maps-addressvalidation/scripts/decrypt-secrets.sh b/packages/google-maps-addressvalidation/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-maps-addressvalidation/scripts/decrypt-secrets.sh +++ b/packages/google-maps-addressvalidation/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-addressvalidation/setup.py b/packages/google-maps-addressvalidation/setup.py index 06e89659f89a..f0289f1140e1 100644 --- a/packages/google-maps-addressvalidation/setup.py +++ b/packages/google-maps-addressvalidation/setup.py @@ -46,6 +46,7 @@ # 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", ] @@ -85,6 +86,7 @@ "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", ], diff --git a/owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.13.txt b/packages/google-maps-addressvalidation/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-maps-addressvalidation/v1/testing/constraints-3.13.txt rename to packages/google-maps-addressvalidation/testing/constraints-3.13.txt diff --git a/packages/google-maps-areainsights/.flake8 b/packages/google-maps-areainsights/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-maps-areainsights/.flake8 +++ b/packages/google-maps-areainsights/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-areainsights/CONTRIBUTING.rst b/packages/google-maps-areainsights/CONTRIBUTING.rst index f47c4696d0d8..8b147a0707a3 100644 --- a/packages/google-maps-areainsights/CONTRIBUTING.rst +++ b/packages/google-maps-areainsights/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-maps-areainsights/MANIFEST.in b/packages/google-maps-areainsights/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-maps-areainsights/MANIFEST.in +++ b/packages/google-maps-areainsights/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-areainsights/docs/conf.py b/packages/google-maps-areainsights/docs/conf.py index cab51bcbeffc..89eaf10bb31d 100644 --- a/packages/google-maps-areainsights/docs/conf.py +++ b/packages/google-maps-areainsights/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-areainsights/google/maps/areainsights_v1/services/area_insights/transports/rest.py b/packages/google-maps-areainsights/google/maps/areainsights_v1/services/area_insights/transports/rest.py index e51680fdbd9e..0ed30438f8f9 100644 --- a/packages/google-maps-areainsights/google/maps/areainsights_v1/services/area_insights/transports/rest.py +++ b/packages/google-maps-areainsights/google/maps/areainsights_v1/services/area_insights/transports/rest.py @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-maps-areainsights/noxfile.py b/packages/google-maps-areainsights/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-maps-areainsights/noxfile.py +++ b/packages/google-maps-areainsights/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-maps-areainsights/scripts/decrypt-secrets.sh b/packages/google-maps-areainsights/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-maps-areainsights/scripts/decrypt-secrets.sh +++ b/packages/google-maps-areainsights/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-areainsights/setup.py b/packages/google-maps-areainsights/setup.py index 7e952f6afe94..9870f18063a4 100644 --- a/packages/google-maps-areainsights/setup.py +++ b/packages/google-maps-areainsights/setup.py @@ -46,6 +46,7 @@ # 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 = {} @@ -84,6 +85,7 @@ "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", ], diff --git a/owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.13.txt b/packages/google-maps-areainsights/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-cloud-workflows/v1/testing/constraints-3.13.txt rename to packages/google-maps-areainsights/testing/constraints-3.13.txt diff --git a/packages/google-maps-fleetengine-delivery/.flake8 b/packages/google-maps-fleetengine-delivery/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-maps-fleetengine-delivery/.flake8 +++ b/packages/google-maps-fleetengine-delivery/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-fleetengine-delivery/CONTRIBUTING.rst b/packages/google-maps-fleetengine-delivery/CONTRIBUTING.rst index 4a5b5bbba7ae..753050dd75f3 100644 --- a/packages/google-maps-fleetengine-delivery/CONTRIBUTING.rst +++ b/packages/google-maps-fleetengine-delivery/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-maps-fleetengine-delivery/MANIFEST.in b/packages/google-maps-fleetengine-delivery/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-maps-fleetengine-delivery/MANIFEST.in +++ b/packages/google-maps-fleetengine-delivery/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-fleetengine-delivery/docs/conf.py b/packages/google-maps-fleetengine-delivery/docs/conf.py index 1f1406b09dbb..9f552bd71a71 100644 --- a/packages/google-maps-fleetengine-delivery/docs/conf.py +++ b/packages/google-maps-fleetengine-delivery/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py index f90ff33f7b31..aef58bf5045a 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py @@ -46,7 +46,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/maps-fleetengine-delivery-v1-py.tar.gz b/packages/google-maps-fleetengine-delivery/maps-fleetengine-delivery-v1-py.tar.gz similarity index 100% rename from owl-bot-staging/google-maps-fleetengine-delivery/v1/maps-fleetengine-delivery-v1-py.tar.gz rename to packages/google-maps-fleetengine-delivery/maps-fleetengine-delivery-v1-py.tar.gz diff --git a/packages/google-maps-fleetengine-delivery/noxfile.py b/packages/google-maps-fleetengine-delivery/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-maps-fleetengine-delivery/noxfile.py +++ b/packages/google-maps-fleetengine-delivery/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-maps-fleetengine-delivery/scripts/decrypt-secrets.sh b/packages/google-maps-fleetengine-delivery/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-maps-fleetengine-delivery/scripts/decrypt-secrets.sh +++ b/packages/google-maps-fleetengine-delivery/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-fleetengine-delivery/setup.py b/packages/google-maps-fleetengine-delivery/setup.py index 0336e9cd7c8d..68a47884ddde 100644 --- a/packages/google-maps-fleetengine-delivery/setup.py +++ b/packages/google-maps-fleetengine-delivery/setup.py @@ -46,6 +46,7 @@ # 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", ] @@ -85,6 +86,7 @@ "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", ], diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.13.txt b/packages/google-maps-fleetengine-delivery/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.13.txt rename to packages/google-maps-fleetengine-delivery/testing/constraints-3.13.txt diff --git a/packages/google-maps-fleetengine/.flake8 b/packages/google-maps-fleetengine/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-maps-fleetengine/.flake8 +++ b/packages/google-maps-fleetengine/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-fleetengine/CONTRIBUTING.rst b/packages/google-maps-fleetengine/CONTRIBUTING.rst index 302d5c0e6475..dba9b8a9c52e 100644 --- a/packages/google-maps-fleetengine/CONTRIBUTING.rst +++ b/packages/google-maps-fleetengine/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-maps-fleetengine/MANIFEST.in b/packages/google-maps-fleetengine/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-maps-fleetengine/MANIFEST.in +++ b/packages/google-maps-fleetengine/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-fleetengine/docs/conf.py b/packages/google-maps-fleetengine/docs/conf.py index 4548280acc4d..cf9c5efaefd8 100644 --- a/packages/google-maps-fleetengine/docs/conf.py +++ b/packages/google-maps-fleetengine/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-fleetengine/noxfile.py b/packages/google-maps-fleetengine/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-maps-fleetengine/noxfile.py +++ b/packages/google-maps-fleetengine/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-maps-fleetengine/scripts/decrypt-secrets.sh b/packages/google-maps-fleetengine/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-maps-fleetengine/scripts/decrypt-secrets.sh +++ b/packages/google-maps-fleetengine/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-fleetengine/setup.py b/packages/google-maps-fleetengine/setup.py index a133aad01d84..d17cc128e0ac 100644 --- a/packages/google-maps-fleetengine/setup.py +++ b/packages/google-maps-fleetengine/setup.py @@ -44,6 +44,7 @@ # 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", ] @@ -83,6 +84,7 @@ "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", ], diff --git a/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.13.txt b/packages/google-maps-fleetengine/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.13.txt rename to packages/google-maps-fleetengine/testing/constraints-3.13.txt diff --git a/packages/google-maps-mapsplatformdatasets/.flake8 b/packages/google-maps-mapsplatformdatasets/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-maps-mapsplatformdatasets/.flake8 +++ b/packages/google-maps-mapsplatformdatasets/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-mapsplatformdatasets/CONTRIBUTING.rst b/packages/google-maps-mapsplatformdatasets/CONTRIBUTING.rst index e6b81de8d16e..4034e20ca07d 100644 --- a/packages/google-maps-mapsplatformdatasets/CONTRIBUTING.rst +++ b/packages/google-maps-mapsplatformdatasets/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-maps-mapsplatformdatasets/MANIFEST.in b/packages/google-maps-mapsplatformdatasets/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-maps-mapsplatformdatasets/MANIFEST.in +++ b/packages/google-maps-mapsplatformdatasets/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-mapsplatformdatasets/docs/conf.py b/packages/google-maps-mapsplatformdatasets/docs/conf.py index ee4dcc339a35..58688faa77ce 100644 --- a/packages/google-maps-mapsplatformdatasets/docs/conf.py +++ b/packages/google-maps-mapsplatformdatasets/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 b21eae08ff92..2264014d5ee6 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 @@ -44,7 +44,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-maps-mapsplatformdatasets/noxfile.py b/packages/google-maps-mapsplatformdatasets/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-maps-mapsplatformdatasets/noxfile.py +++ b/packages/google-maps-mapsplatformdatasets/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-maps-mapsplatformdatasets/scripts/decrypt-secrets.sh b/packages/google-maps-mapsplatformdatasets/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-maps-mapsplatformdatasets/scripts/decrypt-secrets.sh +++ b/packages/google-maps-mapsplatformdatasets/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-mapsplatformdatasets/setup.py b/packages/google-maps-mapsplatformdatasets/setup.py index abf8c5a3ecd3..70944cc1284a 100644 --- a/packages/google-maps-mapsplatformdatasets/setup.py +++ b/packages/google-maps-mapsplatformdatasets/setup.py @@ -46,6 +46,7 @@ # 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 = {} @@ -84,6 +85,7 @@ "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", ], diff --git a/owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.13.txt b/packages/google-maps-mapsplatformdatasets/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-cloud-workflows/v1beta/testing/constraints-3.13.txt rename to packages/google-maps-mapsplatformdatasets/testing/constraints-3.13.txt diff --git a/packages/google-maps-places/.flake8 b/packages/google-maps-places/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-maps-places/.flake8 +++ b/packages/google-maps-places/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-places/CONTRIBUTING.rst b/packages/google-maps-places/CONTRIBUTING.rst index c1a2aa14dbb1..8d30cb732313 100644 --- a/packages/google-maps-places/CONTRIBUTING.rst +++ b/packages/google-maps-places/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-maps-places/MANIFEST.in b/packages/google-maps-places/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-maps-places/MANIFEST.in +++ b/packages/google-maps-places/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-places/docs/conf.py b/packages/google-maps-places/docs/conf.py index 11ceb7b517d6..674d7cdbfde5 100644 --- a/packages/google-maps-places/docs/conf.py +++ b/packages/google-maps-places/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 89d6b4f90d0c..ffbd77013d0d 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-maps-places/noxfile.py b/packages/google-maps-places/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-maps-places/noxfile.py +++ b/packages/google-maps-places/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-maps-places/scripts/decrypt-secrets.sh b/packages/google-maps-places/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-maps-places/scripts/decrypt-secrets.sh +++ b/packages/google-maps-places/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-places/setup.py b/packages/google-maps-places/setup.py index aaee7a4dc2df..ab2b607f09c2 100644 --- a/packages/google-maps-places/setup.py +++ b/packages/google-maps-places/setup.py @@ -44,6 +44,7 @@ # 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", ] @@ -83,6 +84,7 @@ "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", ], diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt b/packages/google-maps-places/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt rename to packages/google-maps-places/testing/constraints-3.13.txt diff --git a/packages/google-maps-routeoptimization/.flake8 b/packages/google-maps-routeoptimization/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-maps-routeoptimization/.flake8 +++ b/packages/google-maps-routeoptimization/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-routeoptimization/CONTRIBUTING.rst b/packages/google-maps-routeoptimization/CONTRIBUTING.rst index 72ac94e37ab9..004a4c491341 100644 --- a/packages/google-maps-routeoptimization/CONTRIBUTING.rst +++ b/packages/google-maps-routeoptimization/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-maps-routeoptimization/MANIFEST.in b/packages/google-maps-routeoptimization/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-maps-routeoptimization/MANIFEST.in +++ b/packages/google-maps-routeoptimization/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-routeoptimization/docs/conf.py b/packages/google-maps-routeoptimization/docs/conf.py index 380aec7e8ec2..512ff9b39bd6 100644 --- a/packages/google-maps-routeoptimization/docs/conf.py +++ b/packages/google-maps-routeoptimization/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 3d43a8a44ba4..ab439b3fef3b 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-maps-routeoptimization/noxfile.py b/packages/google-maps-routeoptimization/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-maps-routeoptimization/noxfile.py +++ b/packages/google-maps-routeoptimization/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-maps-routeoptimization/scripts/decrypt-secrets.sh b/packages/google-maps-routeoptimization/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-maps-routeoptimization/scripts/decrypt-secrets.sh +++ b/packages/google-maps-routeoptimization/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-routeoptimization/setup.py b/packages/google-maps-routeoptimization/setup.py index a3013c482fa0..1884879a339c 100644 --- a/packages/google-maps-routeoptimization/setup.py +++ b/packages/google-maps-routeoptimization/setup.py @@ -46,6 +46,7 @@ # 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 = {} @@ -84,6 +85,7 @@ "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", ], diff --git a/owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.13.txt b/packages/google-maps-routeoptimization/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-geo-type/viewport-py/testing/constraints-3.13.txt rename to packages/google-maps-routeoptimization/testing/constraints-3.13.txt diff --git a/packages/google-maps-routing/.flake8 b/packages/google-maps-routing/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-maps-routing/.flake8 +++ b/packages/google-maps-routing/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-routing/CONTRIBUTING.rst b/packages/google-maps-routing/CONTRIBUTING.rst index bebb72e7ba26..ac31aa393d22 100644 --- a/packages/google-maps-routing/CONTRIBUTING.rst +++ b/packages/google-maps-routing/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-maps-routing/MANIFEST.in b/packages/google-maps-routing/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-maps-routing/MANIFEST.in +++ b/packages/google-maps-routing/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-routing/docs/conf.py b/packages/google-maps-routing/docs/conf.py index 17e8c4bdde5b..4d5b1a71f211 100644 --- a/packages/google-maps-routing/docs/conf.py +++ b/packages/google-maps-routing/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 53044250a575..7228185de516 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-maps-routing/noxfile.py b/packages/google-maps-routing/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-maps-routing/noxfile.py +++ b/packages/google-maps-routing/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-maps-routing/scripts/decrypt-secrets.sh b/packages/google-maps-routing/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-maps-routing/scripts/decrypt-secrets.sh +++ b/packages/google-maps-routing/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-routing/setup.py b/packages/google-maps-routing/setup.py index 34ba7f2de872..461bdb63eb76 100644 --- a/packages/google-maps-routing/setup.py +++ b/packages/google-maps-routing/setup.py @@ -44,6 +44,7 @@ # 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", ] @@ -83,6 +84,7 @@ "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", ], diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt b/packages/google-maps-routing/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt rename to packages/google-maps-routing/testing/constraints-3.13.txt diff --git a/packages/google-maps-solar/.flake8 b/packages/google-maps-solar/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-maps-solar/.flake8 +++ b/packages/google-maps-solar/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-solar/CONTRIBUTING.rst b/packages/google-maps-solar/CONTRIBUTING.rst index 2a1d58cf94ed..965e96d7c036 100644 --- a/packages/google-maps-solar/CONTRIBUTING.rst +++ b/packages/google-maps-solar/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-maps-solar/MANIFEST.in b/packages/google-maps-solar/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-maps-solar/MANIFEST.in +++ b/packages/google-maps-solar/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-solar/docs/conf.py b/packages/google-maps-solar/docs/conf.py index f40f62c5a91d..17c24af1e7bb 100644 --- a/packages/google-maps-solar/docs/conf.py +++ b/packages/google-maps-solar/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 4078f5ec3f23..27123714fe7d 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-maps-solar/noxfile.py b/packages/google-maps-solar/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-maps-solar/noxfile.py +++ b/packages/google-maps-solar/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-maps-solar/scripts/decrypt-secrets.sh b/packages/google-maps-solar/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-maps-solar/scripts/decrypt-secrets.sh +++ b/packages/google-maps-solar/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-maps-solar/setup.py b/packages/google-maps-solar/setup.py index a517dc74f4b4..ec0447f08702 100644 --- a/packages/google-maps-solar/setup.py +++ b/packages/google-maps-solar/setup.py @@ -44,6 +44,7 @@ # 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 = {} @@ -82,6 +83,7 @@ "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", ], diff --git a/owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.13.txt b/packages/google-maps-solar/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-maps-areainsights/v1/testing/constraints-3.13.txt rename to packages/google-maps-solar/testing/constraints-3.13.txt diff --git a/packages/google-shopping-merchant-accounts/.flake8 b/packages/google-shopping-merchant-accounts/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-shopping-merchant-accounts/.flake8 +++ b/packages/google-shopping-merchant-accounts/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-accounts/CONTRIBUTING.rst b/packages/google-shopping-merchant-accounts/CONTRIBUTING.rst index bd53f587099a..04732365f0ef 100644 --- a/packages/google-shopping-merchant-accounts/CONTRIBUTING.rst +++ b/packages/google-shopping-merchant-accounts/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-shopping-merchant-accounts/MANIFEST.in b/packages/google-shopping-merchant-accounts/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-shopping-merchant-accounts/MANIFEST.in +++ b/packages/google-shopping-merchant-accounts/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-accounts/docs/conf.py b/packages/google-shopping-merchant-accounts/docs/conf.py index 83da92ecec22..4fdbf91e9e96 100644 --- a/packages/google-shopping-merchant-accounts/docs/conf.py +++ b/packages/google-shopping-merchant-accounts/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 b6c6b38c64a0..00df2d37ee7c 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 985fa95d6269..abf839241aca 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 @@ -44,7 +44,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 928ae4a3e37e..e497a179734f 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 d24313bb2f19..286471f99b66 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 4f276d1b7029..676645a4e162 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 40b25eebeefa..7de136978256 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 bc42e6fca75f..42876f3e5661 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 15a92ae52f30..75e036c32d11 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 e65c3b752bd3..61874b2f4e85 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 332e16772f4a..9b7a57ef5356 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 6dcd70521c82..a1928d09add4 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 cf453743199c..693d3bad2b85 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 c4d78bf43048..c39b562df96c 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 8bff19e0c3b8..ccafb072649b 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 c1e3aec5f48a..ef09abb79ed8 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 @@ -43,7 +43,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/merchant-accounts-v1beta-py.tar.gz b/packages/google-shopping-merchant-accounts/merchant-accounts-v1beta-py.tar.gz similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/merchant-accounts-v1beta-py.tar.gz rename to packages/google-shopping-merchant-accounts/merchant-accounts-v1beta-py.tar.gz diff --git a/packages/google-shopping-merchant-accounts/noxfile.py b/packages/google-shopping-merchant-accounts/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-shopping-merchant-accounts/noxfile.py +++ b/packages/google-shopping-merchant-accounts/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-shopping-merchant-accounts/scripts/decrypt-secrets.sh b/packages/google-shopping-merchant-accounts/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-shopping-merchant-accounts/scripts/decrypt-secrets.sh +++ b/packages/google-shopping-merchant-accounts/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-accounts/setup.py b/packages/google-shopping-merchant-accounts/setup.py index cd289e2d1c81..f6975541a5ec 100644 --- a/packages/google-shopping-merchant-accounts/setup.py +++ b/packages/google-shopping-merchant-accounts/setup.py @@ -46,6 +46,7 @@ # 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", ] @@ -85,6 +86,7 @@ "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", ], diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.13.txt b/packages/google-shopping-merchant-accounts/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.13.txt rename to packages/google-shopping-merchant-accounts/testing/constraints-3.13.txt diff --git a/packages/google-shopping-merchant-conversions/.flake8 b/packages/google-shopping-merchant-conversions/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-shopping-merchant-conversions/.flake8 +++ b/packages/google-shopping-merchant-conversions/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-conversions/CONTRIBUTING.rst b/packages/google-shopping-merchant-conversions/CONTRIBUTING.rst index ccaf61f0d4b8..2661d0b9207b 100644 --- a/packages/google-shopping-merchant-conversions/CONTRIBUTING.rst +++ b/packages/google-shopping-merchant-conversions/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-shopping-merchant-conversions/MANIFEST.in b/packages/google-shopping-merchant-conversions/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-shopping-merchant-conversions/MANIFEST.in +++ b/packages/google-shopping-merchant-conversions/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-conversions/docs/conf.py b/packages/google-shopping-merchant-conversions/docs/conf.py index d84a411224fe..79e5fb1f56cc 100644 --- a/packages/google-shopping-merchant-conversions/docs/conf.py +++ b/packages/google-shopping-merchant-conversions/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 196fc300bdf6..0aeab813fb6a 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-shopping-merchant-conversions/noxfile.py b/packages/google-shopping-merchant-conversions/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-shopping-merchant-conversions/noxfile.py +++ b/packages/google-shopping-merchant-conversions/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-shopping-merchant-conversions/scripts/decrypt-secrets.sh b/packages/google-shopping-merchant-conversions/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-shopping-merchant-conversions/scripts/decrypt-secrets.sh +++ b/packages/google-shopping-merchant-conversions/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-conversions/setup.py b/packages/google-shopping-merchant-conversions/setup.py index 77e80b0f6063..799a7f935672 100644 --- a/packages/google-shopping-merchant-conversions/setup.py +++ b/packages/google-shopping-merchant-conversions/setup.py @@ -46,6 +46,7 @@ # 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 = {} @@ -84,6 +85,7 @@ "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", ], diff --git a/owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt b/packages/google-shopping-merchant-conversions/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-maps-mapsplatformdatasets/v1/testing/constraints-3.13.txt rename to packages/google-shopping-merchant-conversions/testing/constraints-3.13.txt diff --git a/packages/google-shopping-merchant-datasources/.flake8 b/packages/google-shopping-merchant-datasources/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-shopping-merchant-datasources/.flake8 +++ b/packages/google-shopping-merchant-datasources/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-datasources/CONTRIBUTING.rst b/packages/google-shopping-merchant-datasources/CONTRIBUTING.rst index d0d396fddf2d..e0504329b598 100644 --- a/packages/google-shopping-merchant-datasources/CONTRIBUTING.rst +++ b/packages/google-shopping-merchant-datasources/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-shopping-merchant-datasources/MANIFEST.in b/packages/google-shopping-merchant-datasources/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-shopping-merchant-datasources/MANIFEST.in +++ b/packages/google-shopping-merchant-datasources/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-datasources/docs/conf.py b/packages/google-shopping-merchant-datasources/docs/conf.py index 98c379590d16..d1801cca20bb 100644 --- a/packages/google-shopping-merchant-datasources/docs/conf.py +++ b/packages/google-shopping-merchant-datasources/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 e4de94262023..e864db17089a 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 4ad41fab303c..e54b65f178a1 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-shopping-merchant-datasources/noxfile.py b/packages/google-shopping-merchant-datasources/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-shopping-merchant-datasources/noxfile.py +++ b/packages/google-shopping-merchant-datasources/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-shopping-merchant-datasources/scripts/decrypt-secrets.sh b/packages/google-shopping-merchant-datasources/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-shopping-merchant-datasources/scripts/decrypt-secrets.sh +++ b/packages/google-shopping-merchant-datasources/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-datasources/setup.py b/packages/google-shopping-merchant-datasources/setup.py index 7ac5bf511e28..46c6d7285a32 100644 --- a/packages/google-shopping-merchant-datasources/setup.py +++ b/packages/google-shopping-merchant-datasources/setup.py @@ -46,6 +46,7 @@ # 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 = {} @@ -84,6 +85,7 @@ "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", ], diff --git a/owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt b/packages/google-shopping-merchant-datasources/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-maps-routeoptimization/v1/testing/constraints-3.13.txt rename to packages/google-shopping-merchant-datasources/testing/constraints-3.13.txt diff --git a/packages/google-shopping-merchant-inventories/.flake8 b/packages/google-shopping-merchant-inventories/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-shopping-merchant-inventories/.flake8 +++ b/packages/google-shopping-merchant-inventories/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-inventories/CONTRIBUTING.rst b/packages/google-shopping-merchant-inventories/CONTRIBUTING.rst index ae148622b21c..23fb3de6cbad 100644 --- a/packages/google-shopping-merchant-inventories/CONTRIBUTING.rst +++ b/packages/google-shopping-merchant-inventories/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-shopping-merchant-inventories/MANIFEST.in b/packages/google-shopping-merchant-inventories/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-shopping-merchant-inventories/MANIFEST.in +++ b/packages/google-shopping-merchant-inventories/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-inventories/docs/conf.py b/packages/google-shopping-merchant-inventories/docs/conf.py index 974f8826fcee..fab0a2d15422 100644 --- a/packages/google-shopping-merchant-inventories/docs/conf.py +++ b/packages/google-shopping-merchant-inventories/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 7a17a0203e3c..ec939a04a0c4 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 e1cbde0e8436..9c4f8f69ed40 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-shopping-merchant-inventories/noxfile.py b/packages/google-shopping-merchant-inventories/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-shopping-merchant-inventories/noxfile.py +++ b/packages/google-shopping-merchant-inventories/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-shopping-merchant-inventories/scripts/decrypt-secrets.sh b/packages/google-shopping-merchant-inventories/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-shopping-merchant-inventories/scripts/decrypt-secrets.sh +++ b/packages/google-shopping-merchant-inventories/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-inventories/setup.py b/packages/google-shopping-merchant-inventories/setup.py index 417f532a2718..071f7c82c900 100644 --- a/packages/google-shopping-merchant-inventories/setup.py +++ b/packages/google-shopping-merchant-inventories/setup.py @@ -46,6 +46,7 @@ # 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", ] @@ -85,6 +86,7 @@ "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", ], diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt b/packages/google-shopping-merchant-inventories/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt rename to packages/google-shopping-merchant-inventories/testing/constraints-3.13.txt diff --git a/packages/google-shopping-merchant-lfp/.flake8 b/packages/google-shopping-merchant-lfp/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-shopping-merchant-lfp/.flake8 +++ b/packages/google-shopping-merchant-lfp/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-lfp/CONTRIBUTING.rst b/packages/google-shopping-merchant-lfp/CONTRIBUTING.rst index c63661c0ea9d..98de2d3f49f2 100644 --- a/packages/google-shopping-merchant-lfp/CONTRIBUTING.rst +++ b/packages/google-shopping-merchant-lfp/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-shopping-merchant-lfp/MANIFEST.in b/packages/google-shopping-merchant-lfp/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-shopping-merchant-lfp/MANIFEST.in +++ b/packages/google-shopping-merchant-lfp/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-lfp/docs/conf.py b/packages/google-shopping-merchant-lfp/docs/conf.py index 6cb89ff13afe..967d922a48ad 100644 --- a/packages/google-shopping-merchant-lfp/docs/conf.py +++ b/packages/google-shopping-merchant-lfp/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 14ac9ea2bc33..f123a2fa4f5e 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 f01a9cf78957..e0078cda11d2 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 @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) 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 63c289cfdd69..7a07da90e2c7 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-shopping-merchant-lfp/noxfile.py b/packages/google-shopping-merchant-lfp/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-shopping-merchant-lfp/noxfile.py +++ b/packages/google-shopping-merchant-lfp/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-shopping-merchant-lfp/scripts/decrypt-secrets.sh b/packages/google-shopping-merchant-lfp/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-shopping-merchant-lfp/scripts/decrypt-secrets.sh +++ b/packages/google-shopping-merchant-lfp/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-lfp/setup.py b/packages/google-shopping-merchant-lfp/setup.py index fd3d3bf22fe6..bab3f71948f1 100644 --- a/packages/google-shopping-merchant-lfp/setup.py +++ b/packages/google-shopping-merchant-lfp/setup.py @@ -46,6 +46,7 @@ # 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", ] @@ -85,6 +86,7 @@ "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", ], diff --git a/owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.13.txt b/packages/google-shopping-merchant-lfp/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-shopping-merchant-lfp/v1beta/testing/constraints-3.13.txt rename to packages/google-shopping-merchant-lfp/testing/constraints-3.13.txt diff --git a/packages/google-shopping-merchant-notifications/.flake8 b/packages/google-shopping-merchant-notifications/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-shopping-merchant-notifications/.flake8 +++ b/packages/google-shopping-merchant-notifications/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-notifications/CONTRIBUTING.rst b/packages/google-shopping-merchant-notifications/CONTRIBUTING.rst index c979593e3d94..03423bb986f3 100644 --- a/packages/google-shopping-merchant-notifications/CONTRIBUTING.rst +++ b/packages/google-shopping-merchant-notifications/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-shopping-merchant-notifications/MANIFEST.in b/packages/google-shopping-merchant-notifications/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-shopping-merchant-notifications/MANIFEST.in +++ b/packages/google-shopping-merchant-notifications/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-notifications/docs/conf.py b/packages/google-shopping-merchant-notifications/docs/conf.py index 04fcad0f4ed3..94a9bbceea5b 100644 --- a/packages/google-shopping-merchant-notifications/docs/conf.py +++ b/packages/google-shopping-merchant-notifications/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 61128c9b493e..7c61a8e38280 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 @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-shopping-merchant-notifications/noxfile.py b/packages/google-shopping-merchant-notifications/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-shopping-merchant-notifications/noxfile.py +++ b/packages/google-shopping-merchant-notifications/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-shopping-merchant-notifications/scripts/decrypt-secrets.sh b/packages/google-shopping-merchant-notifications/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-shopping-merchant-notifications/scripts/decrypt-secrets.sh +++ b/packages/google-shopping-merchant-notifications/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-notifications/setup.py b/packages/google-shopping-merchant-notifications/setup.py index c86790568d0e..ae89691aa7d0 100644 --- a/packages/google-shopping-merchant-notifications/setup.py +++ b/packages/google-shopping-merchant-notifications/setup.py @@ -48,6 +48,7 @@ # 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", ] @@ -87,6 +88,7 @@ "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", ], diff --git a/owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.13.txt b/packages/google-shopping-merchant-notifications/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-shopping-merchant-notifications/v1beta/testing/constraints-3.13.txt rename to packages/google-shopping-merchant-notifications/testing/constraints-3.13.txt diff --git a/packages/google-shopping-merchant-products/.flake8 b/packages/google-shopping-merchant-products/.flake8 index 87f6e408c47d..32986c79287a 100644 --- a/packages/google-shopping-merchant-products/.flake8 +++ b/packages/google-shopping-merchant-products/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-products/CONTRIBUTING.rst b/packages/google-shopping-merchant-products/CONTRIBUTING.rst index 9017c23d46ad..6792df47a481 100644 --- a/packages/google-shopping-merchant-products/CONTRIBUTING.rst +++ b/packages/google-shopping-merchant-products/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.12 -- -k + $ nox -s unit-3.13 -- -k .. note:: @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system-3.12 -- -k + $ nox -s system-3.13 -- -k .. note:: - System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local @@ -227,6 +227,7 @@ We support: - `Python 3.10`_ - `Python 3.11`_ - `Python 3.12`_ +- `Python 3.13`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ @@ -234,6 +235,7 @@ We support: .. _Python 3.10: https://docs.python.org/3.10/ .. _Python 3.11: https://docs.python.org/3.11/ .. _Python 3.12: https://docs.python.org/3.12/ +.. _Python 3.13: https://docs.python.org/3.13/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/packages/google-shopping-merchant-products/MANIFEST.in b/packages/google-shopping-merchant-products/MANIFEST.in index e0a66705318e..d6814cd60037 100644 --- a/packages/google-shopping-merchant-products/MANIFEST.in +++ b/packages/google-shopping-merchant-products/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-products/docs/conf.py b/packages/google-shopping-merchant-products/docs/conf.py index 54f7734b648e..0307610b0b6f 100644 --- a/packages/google-shopping-merchant-products/docs/conf.py +++ b/packages/google-shopping-merchant-products/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py index 728fa2bcdb9f..d473a49ec5aa 100644 --- a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py +++ b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1beta/services/product_inputs_service/transports/rest.py @@ -42,7 +42,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py index 99b50e2d557b..1f3b93a3bd8f 100644 --- a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py +++ b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1beta/services/products_service/transports/rest.py @@ -41,7 +41,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-shopping-merchant-products/noxfile.py b/packages/google-shopping-merchant-products/noxfile.py index 67b7265f7586..a9ceef47133c 100644 --- a/packages/google-shopping-merchant-products/noxfile.py +++ b/packages/google-shopping-merchant-products/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2023 Google LLC +# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,15 @@ DEFAULT_PYTHON_VERSION = "3.10" -UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_PYTHON_VERSIONS: List[str] = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -49,7 +57,7 @@ UNIT_TEST_EXTRAS: List[str] = [] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints): def unit(session, protobuf_implementation): # Install all test dependencies, then install this package in-place. - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -368,7 +376,7 @@ def docfx(session): ) -@nox.session(python="3.12") +@nox.session(python="3.13") @nox.parametrize( "protobuf_implementation", ["python", "upb", "cpp"], @@ -376,7 +384,7 @@ def docfx(session): def prerelease_deps(session, protobuf_implementation): """Run all tests with prerelease versions of dependencies installed.""" - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-shopping-merchant-products/scripts/decrypt-secrets.sh b/packages/google-shopping-merchant-products/scripts/decrypt-secrets.sh index 0018b421ddf8..120b0ddc4364 100755 --- a/packages/google-shopping-merchant-products/scripts/decrypt-secrets.sh +++ b/packages/google-shopping-merchant-products/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2023 Google LLC All rights reserved. +# Copyright 2024 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-shopping-merchant-products/setup.py b/packages/google-shopping-merchant-products/setup.py index 1af4ea8d2cf0..0c89d84d7782 100644 --- a/packages/google-shopping-merchant-products/setup.py +++ b/packages/google-shopping-merchant-products/setup.py @@ -46,6 +46,7 @@ # 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", ] @@ -85,6 +86,7 @@ "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", ], diff --git a/owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.13.txt b/packages/google-shopping-merchant-products/testing/constraints-3.13.txt similarity index 100% rename from owl-bot-staging/google-shopping-merchant-products/v1beta/testing/constraints-3.13.txt rename to packages/google-shopping-merchant-products/testing/constraints-3.13.txt